AVX-512: Implemented all forms of sign-extend and zero-extend instructions for KNL...
[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::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1008     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1009     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1010
1011     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1012     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1013
1014     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1015     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1016
1017     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1018     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1019
1020     // In the customized shift lowering, the legal cases in AVX2 will be
1021     // recognized.
1022     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1023     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1024
1025     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1026     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1027
1028     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1029   }
1030
1031   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1032     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1033     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1034     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1035     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1036     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1037     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1038
1039     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1040     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1041     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1042
1043     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1044     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1045     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1046     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1047     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1048     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1049     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1050     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1051     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1052     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1053     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1054     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1055
1056     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1057     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1058     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1059     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1060     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1061     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1062     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1063     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1064     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1065     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1066     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1067     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1068
1069     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1070     // even though v8i16 is a legal type.
1071     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1072     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1073     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1074
1075     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1076     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1077     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1078
1079     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1080     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1081
1082     for (MVT VT : MVT::fp_vector_valuetypes())
1083       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1084
1085     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1086     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1087
1088     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1089     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1090
1091     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1092     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1093
1094     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1095     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1096     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1097     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1098
1099     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1100     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1101     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1102
1103     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1104     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1105     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1106     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1107     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1108     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1109     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1110     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1111     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1112     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1113     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1114     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1115
1116     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1117       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1118       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1119       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1120       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1121       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1122       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1123     }
1124
1125     if (Subtarget->hasInt256()) {
1126       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1127       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1128       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1129       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1130
1131       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1132       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1133       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1134       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1135
1136       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1137       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1138       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1139       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1140
1141       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1142       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1143       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1144       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1145
1146       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1147       // when we have a 256bit-wide blend with immediate.
1148       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1149
1150       // Only provide customized ctpop vector bit twiddling for vector types we
1151       // know to perform better than using the popcnt instructions on each
1152       // vector element. If popcnt isn't supported, always provide the custom
1153       // version.
1154       if (!Subtarget->hasPOPCNT())
1155         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1156
1157       // Custom CTPOP always performs better on natively supported v8i32
1158       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1159
1160       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1161       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1162       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1163       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1164       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1165       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1166       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1167
1168       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1169       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1170       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1171       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1172       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1173       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1174     } else {
1175       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1176       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1177       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1178       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1179
1180       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1181       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1182       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1183       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1184
1185       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1186       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1187       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1188       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1189     }
1190
1191     // In the customized shift lowering, the legal cases in AVX2 will be
1192     // recognized.
1193     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1194     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1195
1196     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1197     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1198
1199     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1200
1201     // Custom lower several nodes for 256-bit types.
1202     for (MVT VT : MVT::vector_valuetypes()) {
1203       if (VT.getScalarSizeInBits() >= 32) {
1204         setOperationAction(ISD::MLOAD,  VT, Legal);
1205         setOperationAction(ISD::MSTORE, VT, Legal);
1206       }
1207       // Extract subvector is special because the value type
1208       // (result) is 128-bit but the source is 256-bit wide.
1209       if (VT.is128BitVector()) {
1210         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1211       }
1212       // Do not attempt to custom lower other non-256-bit vectors
1213       if (!VT.is256BitVector())
1214         continue;
1215
1216       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1217       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1218       setOperationAction(ISD::VSELECT,            VT, Custom);
1219       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1220       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1221       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1222       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1223       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1224     }
1225
1226     if (Subtarget->hasInt256())
1227       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1228
1229
1230     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1231     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1232       MVT VT = (MVT::SimpleValueType)i;
1233
1234       // Do not attempt to promote non-256-bit vectors
1235       if (!VT.is256BitVector())
1236         continue;
1237
1238       setOperationAction(ISD::AND,    VT, Promote);
1239       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1240       setOperationAction(ISD::OR,     VT, Promote);
1241       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1242       setOperationAction(ISD::XOR,    VT, Promote);
1243       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1244       setOperationAction(ISD::LOAD,   VT, Promote);
1245       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1246       setOperationAction(ISD::SELECT, VT, Promote);
1247       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1248     }
1249   }
1250
1251   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1252     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1253     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1254     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1255     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1256
1257     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1258     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1259     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1260
1261     for (MVT VT : MVT::fp_vector_valuetypes())
1262       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1263
1264     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1265     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1266     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1267     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1268     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1269     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1270     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1271     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1272     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1273     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1274     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1275     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1276     
1277     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1278     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1279     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1280     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1281     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1282     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1283     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1284     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1285     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1286     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1287     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1288     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1289     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1290
1291     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1292     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1293     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1294     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1295     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1296     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1297
1298     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1299     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1300     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1301     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1302     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1303     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1304     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1305     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1306
1307     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1308     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1309     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1310     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1311     if (Subtarget->is64Bit()) {
1312       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1313       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1314       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1315       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1316     }
1317     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1318     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1319     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1320     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1321     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1322     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1323     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1324     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1325     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1326     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1327     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1328     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1329     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1330     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1331     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1332     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1333
1334     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1335     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1336     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1337     if (Subtarget->hasDQI()) {
1338       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1339       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1340     }
1341     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1342     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1343     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1344     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1345     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1346     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1347     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1348     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1349     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1350     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1351     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1352     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1353     if (Subtarget->hasDQI()) {
1354       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1355       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1356     }
1357     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1358     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1359     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1360     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1361     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1362     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1363     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1364     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1365     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1366     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1367
1368     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1369     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1370     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1371     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1372     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1373
1374     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1375     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1376
1377     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1378
1379     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1380     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1381     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1382     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1383     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1384     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1385     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1386     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1387     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1388     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1389     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1390
1391     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1392     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1393
1394     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1395     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1396
1397     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1398
1399     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1400     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1401
1402     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1403     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1404
1405     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1406     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1407
1408     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1409     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1410     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1411     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1412     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1413     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1414
1415     if (Subtarget->hasCDI()) {
1416       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1417       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1418     }
1419     if (Subtarget->hasDQI()) {
1420       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1421       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1422       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1423     }
1424     // Custom lower several nodes.
1425     for (MVT VT : MVT::vector_valuetypes()) {
1426       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1427       if (EltSize == 1) {
1428         setOperationAction(ISD::AND, VT, Legal);
1429         setOperationAction(ISD::OR,  VT, Legal);
1430         setOperationAction(ISD::XOR,  VT, Legal);
1431       }
1432       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1433         setOperationAction(ISD::MGATHER,  VT, Custom);
1434         setOperationAction(ISD::MSCATTER, VT, Custom);
1435       }
1436       // Extract subvector is special because the value type
1437       // (result) is 256/128-bit but the source is 512-bit wide.
1438       if (VT.is128BitVector() || VT.is256BitVector()) {
1439         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1440       }
1441       if (VT.getVectorElementType() == MVT::i1)
1442         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1443
1444       // Do not attempt to custom lower other non-512-bit vectors
1445       if (!VT.is512BitVector())
1446         continue;
1447
1448       if (EltSize >= 32) {
1449         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1450         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1451         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1452         setOperationAction(ISD::VSELECT,             VT, Legal);
1453         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1454         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1455         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1456         setOperationAction(ISD::MLOAD,               VT, Legal);
1457         setOperationAction(ISD::MSTORE,              VT, Legal);
1458       }
1459     }
1460     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1461       MVT VT = (MVT::SimpleValueType)i;
1462
1463       // Do not attempt to promote non-512-bit vectors.
1464       if (!VT.is512BitVector())
1465         continue;
1466
1467       setOperationAction(ISD::SELECT, VT, Promote);
1468       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1469     }
1470   }// has  AVX-512
1471
1472   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1473     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1474     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1475
1476     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1477     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1478
1479     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1480     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1481     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1482     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1483     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1484     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1485     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1486     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1487     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1488     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1489     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1490     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1491     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1492     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1493     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1494     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1495     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1496     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1497     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1498     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1499     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1500     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1501     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1502     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1503     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1504     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1505     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1506
1507     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1508       const MVT VT = (MVT::SimpleValueType)i;
1509
1510       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1511
1512       // Do not attempt to promote non-512-bit vectors.
1513       if (!VT.is512BitVector())
1514         continue;
1515
1516       if (EltSize < 32) {
1517         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1518         setOperationAction(ISD::VSELECT,             VT, Legal);
1519       }
1520     }
1521   }
1522
1523   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1524     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1525     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1526
1527     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1528     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1529     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1530     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1531     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1532     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1533     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1534     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1535     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1536     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1537
1538     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1539     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1540     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1541     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1542     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1543     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1544     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1545     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1546   }
1547
1548   // We want to custom lower some of our intrinsics.
1549   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1550   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1551   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1552   if (!Subtarget->is64Bit())
1553     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1554
1555   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1556   // handle type legalization for these operations here.
1557   //
1558   // FIXME: We really should do custom legalization for addition and
1559   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1560   // than generic legalization for 64-bit multiplication-with-overflow, though.
1561   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1562     // Add/Sub/Mul with overflow operations are custom lowered.
1563     MVT VT = IntVTs[i];
1564     setOperationAction(ISD::SADDO, VT, Custom);
1565     setOperationAction(ISD::UADDO, VT, Custom);
1566     setOperationAction(ISD::SSUBO, VT, Custom);
1567     setOperationAction(ISD::USUBO, VT, Custom);
1568     setOperationAction(ISD::SMULO, VT, Custom);
1569     setOperationAction(ISD::UMULO, VT, Custom);
1570   }
1571
1572
1573   if (!Subtarget->is64Bit()) {
1574     // These libcalls are not available in 32-bit.
1575     setLibcallName(RTLIB::SHL_I128, nullptr);
1576     setLibcallName(RTLIB::SRL_I128, nullptr);
1577     setLibcallName(RTLIB::SRA_I128, nullptr);
1578   }
1579
1580   // Combine sin / cos into one node or libcall if possible.
1581   if (Subtarget->hasSinCos()) {
1582     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1583     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1584     if (Subtarget->isTargetDarwin()) {
1585       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1586       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1587       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1588       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1589     }
1590   }
1591
1592   if (Subtarget->isTargetWin64()) {
1593     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1594     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1595     setOperationAction(ISD::SREM, MVT::i128, Custom);
1596     setOperationAction(ISD::UREM, MVT::i128, Custom);
1597     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1598     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1599   }
1600
1601   // We have target-specific dag combine patterns for the following nodes:
1602   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1603   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1604   setTargetDAGCombine(ISD::BITCAST);
1605   setTargetDAGCombine(ISD::VSELECT);
1606   setTargetDAGCombine(ISD::SELECT);
1607   setTargetDAGCombine(ISD::SHL);
1608   setTargetDAGCombine(ISD::SRA);
1609   setTargetDAGCombine(ISD::SRL);
1610   setTargetDAGCombine(ISD::OR);
1611   setTargetDAGCombine(ISD::AND);
1612   setTargetDAGCombine(ISD::ADD);
1613   setTargetDAGCombine(ISD::FADD);
1614   setTargetDAGCombine(ISD::FSUB);
1615   setTargetDAGCombine(ISD::FMA);
1616   setTargetDAGCombine(ISD::SUB);
1617   setTargetDAGCombine(ISD::LOAD);
1618   setTargetDAGCombine(ISD::MLOAD);
1619   setTargetDAGCombine(ISD::STORE);
1620   setTargetDAGCombine(ISD::MSTORE);
1621   setTargetDAGCombine(ISD::ZERO_EXTEND);
1622   setTargetDAGCombine(ISD::ANY_EXTEND);
1623   setTargetDAGCombine(ISD::SIGN_EXTEND);
1624   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1625   setTargetDAGCombine(ISD::SINT_TO_FP);
1626   setTargetDAGCombine(ISD::SETCC);
1627   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1628   setTargetDAGCombine(ISD::BUILD_VECTOR);
1629   setTargetDAGCombine(ISD::MUL);
1630   setTargetDAGCombine(ISD::XOR);
1631
1632   computeRegisterProperties(Subtarget->getRegisterInfo());
1633
1634   // On Darwin, -Os means optimize for size without hurting performance,
1635   // do not reduce the limit.
1636   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1637   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1638   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1639   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1640   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1641   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1642   setPrefLoopAlignment(4); // 2^4 bytes.
1643
1644   // Predictable cmov don't hurt on atom because it's in-order.
1645   PredictableSelectIsExpensive = !Subtarget->isAtom();
1646   EnableExtLdPromotion = true;
1647   setPrefFunctionAlignment(4); // 2^4 bytes.
1648
1649   verifyIntrinsicTables();
1650 }
1651
1652 // This has so far only been implemented for 64-bit MachO.
1653 bool X86TargetLowering::useLoadStackGuardNode() const {
1654   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1655 }
1656
1657 TargetLoweringBase::LegalizeTypeAction
1658 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1659   if (ExperimentalVectorWideningLegalization &&
1660       VT.getVectorNumElements() != 1 &&
1661       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1662     return TypeWidenVector;
1663
1664   return TargetLoweringBase::getPreferredVectorAction(VT);
1665 }
1666
1667 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1668   if (!VT.isVector())
1669     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1670
1671   const unsigned NumElts = VT.getVectorNumElements();
1672   const EVT EltVT = VT.getVectorElementType();
1673   if (VT.is512BitVector()) {
1674     if (Subtarget->hasAVX512())
1675       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1676           EltVT == MVT::f32 || EltVT == MVT::f64)
1677         switch(NumElts) {
1678         case  8: return MVT::v8i1;
1679         case 16: return MVT::v16i1;
1680       }
1681     if (Subtarget->hasBWI())
1682       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1683         switch(NumElts) {
1684         case 32: return MVT::v32i1;
1685         case 64: return MVT::v64i1;
1686       }
1687   }
1688
1689   if (VT.is256BitVector() || VT.is128BitVector()) {
1690     if (Subtarget->hasVLX())
1691       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1692           EltVT == MVT::f32 || EltVT == MVT::f64)
1693         switch(NumElts) {
1694         case 2: return MVT::v2i1;
1695         case 4: return MVT::v4i1;
1696         case 8: return MVT::v8i1;
1697       }
1698     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1699       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1700         switch(NumElts) {
1701         case  8: return MVT::v8i1;
1702         case 16: return MVT::v16i1;
1703         case 32: return MVT::v32i1;
1704       }
1705   }
1706
1707   return VT.changeVectorElementTypeToInteger();
1708 }
1709
1710 /// Helper for getByValTypeAlignment to determine
1711 /// the desired ByVal argument alignment.
1712 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1713   if (MaxAlign == 16)
1714     return;
1715   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1716     if (VTy->getBitWidth() == 128)
1717       MaxAlign = 16;
1718   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1719     unsigned EltAlign = 0;
1720     getMaxByValAlign(ATy->getElementType(), EltAlign);
1721     if (EltAlign > MaxAlign)
1722       MaxAlign = EltAlign;
1723   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1724     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1725       unsigned EltAlign = 0;
1726       getMaxByValAlign(STy->getElementType(i), EltAlign);
1727       if (EltAlign > MaxAlign)
1728         MaxAlign = EltAlign;
1729       if (MaxAlign == 16)
1730         break;
1731     }
1732   }
1733 }
1734
1735 /// Return the desired alignment for ByVal aggregate
1736 /// function arguments in the caller parameter area. For X86, aggregates
1737 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1738 /// are at 4-byte boundaries.
1739 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1740   if (Subtarget->is64Bit()) {
1741     // Max of 8 and alignment of type.
1742     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1743     if (TyAlign > 8)
1744       return TyAlign;
1745     return 8;
1746   }
1747
1748   unsigned Align = 4;
1749   if (Subtarget->hasSSE1())
1750     getMaxByValAlign(Ty, Align);
1751   return Align;
1752 }
1753
1754 /// Returns the target specific optimal type for load
1755 /// and store operations as a result of memset, memcpy, and memmove
1756 /// lowering. If DstAlign is zero that means it's safe to destination
1757 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1758 /// means there isn't a need to check it against alignment requirement,
1759 /// probably because the source does not need to be loaded. If 'IsMemset' is
1760 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1761 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1762 /// source is constant so it does not need to be loaded.
1763 /// It returns EVT::Other if the type should be determined using generic
1764 /// target-independent logic.
1765 EVT
1766 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1767                                        unsigned DstAlign, unsigned SrcAlign,
1768                                        bool IsMemset, bool ZeroMemset,
1769                                        bool MemcpyStrSrc,
1770                                        MachineFunction &MF) const {
1771   const Function *F = MF.getFunction();
1772   if ((!IsMemset || ZeroMemset) &&
1773       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1774     if (Size >= 16 &&
1775         (Subtarget->isUnalignedMemAccessFast() ||
1776          ((DstAlign == 0 || DstAlign >= 16) &&
1777           (SrcAlign == 0 || SrcAlign >= 16)))) {
1778       if (Size >= 32) {
1779         if (Subtarget->hasInt256())
1780           return MVT::v8i32;
1781         if (Subtarget->hasFp256())
1782           return MVT::v8f32;
1783       }
1784       if (Subtarget->hasSSE2())
1785         return MVT::v4i32;
1786       if (Subtarget->hasSSE1())
1787         return MVT::v4f32;
1788     } else if (!MemcpyStrSrc && Size >= 8 &&
1789                !Subtarget->is64Bit() &&
1790                Subtarget->hasSSE2()) {
1791       // Do not use f64 to lower memcpy if source is string constant. It's
1792       // better to use i32 to avoid the loads.
1793       return MVT::f64;
1794     }
1795   }
1796   if (Subtarget->is64Bit() && Size >= 8)
1797     return MVT::i64;
1798   return MVT::i32;
1799 }
1800
1801 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1802   if (VT == MVT::f32)
1803     return X86ScalarSSEf32;
1804   else if (VT == MVT::f64)
1805     return X86ScalarSSEf64;
1806   return true;
1807 }
1808
1809 bool
1810 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1811                                                   unsigned,
1812                                                   unsigned,
1813                                                   bool *Fast) const {
1814   if (Fast)
1815     *Fast = Subtarget->isUnalignedMemAccessFast();
1816   return true;
1817 }
1818
1819 /// Return the entry encoding for a jump table in the
1820 /// current function.  The returned value is a member of the
1821 /// MachineJumpTableInfo::JTEntryKind enum.
1822 unsigned X86TargetLowering::getJumpTableEncoding() const {
1823   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1824   // symbol.
1825   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1826       Subtarget->isPICStyleGOT())
1827     return MachineJumpTableInfo::EK_Custom32;
1828
1829   // Otherwise, use the normal jump table encoding heuristics.
1830   return TargetLowering::getJumpTableEncoding();
1831 }
1832
1833 bool X86TargetLowering::useSoftFloat() const {
1834   return Subtarget->useSoftFloat();
1835 }
1836
1837 const MCExpr *
1838 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1839                                              const MachineBasicBlock *MBB,
1840                                              unsigned uid,MCContext &Ctx) const{
1841   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1842          Subtarget->isPICStyleGOT());
1843   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1844   // entries.
1845   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1846                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1847 }
1848
1849 /// Returns relocation base for the given PIC jumptable.
1850 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1851                                                     SelectionDAG &DAG) const {
1852   if (!Subtarget->is64Bit())
1853     // This doesn't have SDLoc associated with it, but is not really the
1854     // same as a Register.
1855     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1856   return Table;
1857 }
1858
1859 /// This returns the relocation base for the given PIC jumptable,
1860 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1861 const MCExpr *X86TargetLowering::
1862 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1863                              MCContext &Ctx) const {
1864   // X86-64 uses RIP relative addressing based on the jump table label.
1865   if (Subtarget->isPICStyleRIPRel())
1866     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1867
1868   // Otherwise, the reference is relative to the PIC base.
1869   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1870 }
1871
1872 std::pair<const TargetRegisterClass *, uint8_t>
1873 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1874                                            MVT VT) const {
1875   const TargetRegisterClass *RRC = nullptr;
1876   uint8_t Cost = 1;
1877   switch (VT.SimpleTy) {
1878   default:
1879     return TargetLowering::findRepresentativeClass(TRI, VT);
1880   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1881     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1882     break;
1883   case MVT::x86mmx:
1884     RRC = &X86::VR64RegClass;
1885     break;
1886   case MVT::f32: case MVT::f64:
1887   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1888   case MVT::v4f32: case MVT::v2f64:
1889   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1890   case MVT::v4f64:
1891     RRC = &X86::VR128RegClass;
1892     break;
1893   }
1894   return std::make_pair(RRC, Cost);
1895 }
1896
1897 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1898                                                unsigned &Offset) const {
1899   if (!Subtarget->isTargetLinux())
1900     return false;
1901
1902   if (Subtarget->is64Bit()) {
1903     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1904     Offset = 0x28;
1905     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1906       AddressSpace = 256;
1907     else
1908       AddressSpace = 257;
1909   } else {
1910     // %gs:0x14 on i386
1911     Offset = 0x14;
1912     AddressSpace = 256;
1913   }
1914   return true;
1915 }
1916
1917 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1918                                             unsigned DestAS) const {
1919   assert(SrcAS != DestAS && "Expected different address spaces!");
1920
1921   return SrcAS < 256 && DestAS < 256;
1922 }
1923
1924 //===----------------------------------------------------------------------===//
1925 //               Return Value Calling Convention Implementation
1926 //===----------------------------------------------------------------------===//
1927
1928 #include "X86GenCallingConv.inc"
1929
1930 bool
1931 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1932                                   MachineFunction &MF, bool isVarArg,
1933                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1934                         LLVMContext &Context) const {
1935   SmallVector<CCValAssign, 16> RVLocs;
1936   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1937   return CCInfo.CheckReturn(Outs, RetCC_X86);
1938 }
1939
1940 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1941   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1942   return ScratchRegs;
1943 }
1944
1945 SDValue
1946 X86TargetLowering::LowerReturn(SDValue Chain,
1947                                CallingConv::ID CallConv, bool isVarArg,
1948                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1949                                const SmallVectorImpl<SDValue> &OutVals,
1950                                SDLoc dl, SelectionDAG &DAG) const {
1951   MachineFunction &MF = DAG.getMachineFunction();
1952   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1953
1954   SmallVector<CCValAssign, 16> RVLocs;
1955   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1956   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1957
1958   SDValue Flag;
1959   SmallVector<SDValue, 6> RetOps;
1960   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1961   // Operand #1 = Bytes To Pop
1962   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1963                    MVT::i16));
1964
1965   // Copy the result values into the output registers.
1966   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1967     CCValAssign &VA = RVLocs[i];
1968     assert(VA.isRegLoc() && "Can only return in registers!");
1969     SDValue ValToCopy = OutVals[i];
1970     EVT ValVT = ValToCopy.getValueType();
1971
1972     // Promote values to the appropriate types.
1973     if (VA.getLocInfo() == CCValAssign::SExt)
1974       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1975     else if (VA.getLocInfo() == CCValAssign::ZExt)
1976       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1977     else if (VA.getLocInfo() == CCValAssign::AExt) {
1978       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
1979         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1980       else
1981         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1982     }
1983     else if (VA.getLocInfo() == CCValAssign::BCvt)
1984       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1985
1986     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1987            "Unexpected FP-extend for return value.");
1988
1989     // If this is x86-64, and we disabled SSE, we can't return FP values,
1990     // or SSE or MMX vectors.
1991     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1992          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1993           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1994       report_fatal_error("SSE register return with SSE disabled");
1995     }
1996     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1997     // llvm-gcc has never done it right and no one has noticed, so this
1998     // should be OK for now.
1999     if (ValVT == MVT::f64 &&
2000         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2001       report_fatal_error("SSE2 register return with SSE2 disabled");
2002
2003     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2004     // the RET instruction and handled by the FP Stackifier.
2005     if (VA.getLocReg() == X86::FP0 ||
2006         VA.getLocReg() == X86::FP1) {
2007       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2008       // change the value to the FP stack register class.
2009       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2010         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2011       RetOps.push_back(ValToCopy);
2012       // Don't emit a copytoreg.
2013       continue;
2014     }
2015
2016     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2017     // which is returned in RAX / RDX.
2018     if (Subtarget->is64Bit()) {
2019       if (ValVT == MVT::x86mmx) {
2020         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2021           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2022           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2023                                   ValToCopy);
2024           // If we don't have SSE2 available, convert to v4f32 so the generated
2025           // register is legal.
2026           if (!Subtarget->hasSSE2())
2027             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2028         }
2029       }
2030     }
2031
2032     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2033     Flag = Chain.getValue(1);
2034     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2035   }
2036
2037   // All x86 ABIs require that for returning structs by value we copy
2038   // the sret argument into %rax/%eax (depending on ABI) for the return.
2039   // We saved the argument into a virtual register in the entry block,
2040   // so now we copy the value out and into %rax/%eax.
2041   //
2042   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2043   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2044   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2045   // either case FuncInfo->setSRetReturnReg() will have been called.
2046   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2047     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2048
2049     unsigned RetValReg
2050         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2051           X86::RAX : X86::EAX;
2052     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2053     Flag = Chain.getValue(1);
2054
2055     // RAX/EAX now acts like a return value.
2056     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2057   }
2058
2059   RetOps[0] = Chain;  // Update chain.
2060
2061   // Add the flag if we have it.
2062   if (Flag.getNode())
2063     RetOps.push_back(Flag);
2064
2065   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2066 }
2067
2068 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2069   if (N->getNumValues() != 1)
2070     return false;
2071   if (!N->hasNUsesOfValue(1, 0))
2072     return false;
2073
2074   SDValue TCChain = Chain;
2075   SDNode *Copy = *N->use_begin();
2076   if (Copy->getOpcode() == ISD::CopyToReg) {
2077     // If the copy has a glue operand, we conservatively assume it isn't safe to
2078     // perform a tail call.
2079     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2080       return false;
2081     TCChain = Copy->getOperand(0);
2082   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2083     return false;
2084
2085   bool HasRet = false;
2086   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2087        UI != UE; ++UI) {
2088     if (UI->getOpcode() != X86ISD::RET_FLAG)
2089       return false;
2090     // If we are returning more than one value, we can definitely
2091     // not make a tail call see PR19530
2092     if (UI->getNumOperands() > 4)
2093       return false;
2094     if (UI->getNumOperands() == 4 &&
2095         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2096       return false;
2097     HasRet = true;
2098   }
2099
2100   if (!HasRet)
2101     return false;
2102
2103   Chain = TCChain;
2104   return true;
2105 }
2106
2107 EVT
2108 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2109                                             ISD::NodeType ExtendKind) const {
2110   MVT ReturnMVT;
2111   // TODO: Is this also valid on 32-bit?
2112   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2113     ReturnMVT = MVT::i8;
2114   else
2115     ReturnMVT = MVT::i32;
2116
2117   EVT MinVT = getRegisterType(Context, ReturnMVT);
2118   return VT.bitsLT(MinVT) ? MinVT : VT;
2119 }
2120
2121 /// Lower the result values of a call into the
2122 /// appropriate copies out of appropriate physical registers.
2123 ///
2124 SDValue
2125 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2126                                    CallingConv::ID CallConv, bool isVarArg,
2127                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2128                                    SDLoc dl, SelectionDAG &DAG,
2129                                    SmallVectorImpl<SDValue> &InVals) const {
2130
2131   // Assign locations to each value returned by this call.
2132   SmallVector<CCValAssign, 16> RVLocs;
2133   bool Is64Bit = Subtarget->is64Bit();
2134   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2135                  *DAG.getContext());
2136   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2137
2138   // Copy all of the result registers out of their specified physreg.
2139   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2140     CCValAssign &VA = RVLocs[i];
2141     EVT CopyVT = VA.getLocVT();
2142
2143     // If this is x86-64, and we disabled SSE, we can't return FP values
2144     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2145         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2146       report_fatal_error("SSE register return with SSE disabled");
2147     }
2148
2149     // If we prefer to use the value in xmm registers, copy it out as f80 and
2150     // use a truncate to move it from fp stack reg to xmm reg.
2151     bool RoundAfterCopy = false;
2152     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2153         isScalarFPTypeInSSEReg(VA.getValVT())) {
2154       CopyVT = MVT::f80;
2155       RoundAfterCopy = (CopyVT != VA.getLocVT());
2156     }
2157
2158     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2159                                CopyVT, InFlag).getValue(1);
2160     SDValue Val = Chain.getValue(0);
2161
2162     if (RoundAfterCopy)
2163       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2164                         // This truncation won't change the value.
2165                         DAG.getIntPtrConstant(1, dl));
2166
2167     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2168       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2169
2170     InFlag = Chain.getValue(2);
2171     InVals.push_back(Val);
2172   }
2173
2174   return Chain;
2175 }
2176
2177 //===----------------------------------------------------------------------===//
2178 //                C & StdCall & Fast Calling Convention implementation
2179 //===----------------------------------------------------------------------===//
2180 //  StdCall calling convention seems to be standard for many Windows' API
2181 //  routines and around. It differs from C calling convention just a little:
2182 //  callee should clean up the stack, not caller. Symbols should be also
2183 //  decorated in some fancy way :) It doesn't support any vector arguments.
2184 //  For info on fast calling convention see Fast Calling Convention (tail call)
2185 //  implementation LowerX86_32FastCCCallTo.
2186
2187 /// CallIsStructReturn - Determines whether a call uses struct return
2188 /// semantics.
2189 enum StructReturnType {
2190   NotStructReturn,
2191   RegStructReturn,
2192   StackStructReturn
2193 };
2194 static StructReturnType
2195 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2196   if (Outs.empty())
2197     return NotStructReturn;
2198
2199   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2200   if (!Flags.isSRet())
2201     return NotStructReturn;
2202   if (Flags.isInReg())
2203     return RegStructReturn;
2204   return StackStructReturn;
2205 }
2206
2207 /// Determines whether a function uses struct return semantics.
2208 static StructReturnType
2209 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2210   if (Ins.empty())
2211     return NotStructReturn;
2212
2213   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2214   if (!Flags.isSRet())
2215     return NotStructReturn;
2216   if (Flags.isInReg())
2217     return RegStructReturn;
2218   return StackStructReturn;
2219 }
2220
2221 /// Make a copy of an aggregate at address specified by "Src" to address
2222 /// "Dst" with size and alignment information specified by the specific
2223 /// parameter attribute. The copy will be passed as a byval function parameter.
2224 static SDValue
2225 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2226                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2227                           SDLoc dl) {
2228   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2229
2230   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2231                        /*isVolatile*/false, /*AlwaysInline=*/true,
2232                        /*isTailCall*/false,
2233                        MachinePointerInfo(), MachinePointerInfo());
2234 }
2235
2236 /// Return true if the calling convention is one that
2237 /// supports tail call optimization.
2238 static bool IsTailCallConvention(CallingConv::ID CC) {
2239   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2240           CC == CallingConv::HiPE);
2241 }
2242
2243 /// \brief Return true if the calling convention is a C calling convention.
2244 static bool IsCCallConvention(CallingConv::ID CC) {
2245   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2246           CC == CallingConv::X86_64_SysV);
2247 }
2248
2249 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2250   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2251     return false;
2252
2253   CallSite CS(CI);
2254   CallingConv::ID CalleeCC = CS.getCallingConv();
2255   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2256     return false;
2257
2258   return true;
2259 }
2260
2261 /// Return true if the function is being made into
2262 /// a tailcall target by changing its ABI.
2263 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2264                                    bool GuaranteedTailCallOpt) {
2265   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2266 }
2267
2268 SDValue
2269 X86TargetLowering::LowerMemArgument(SDValue Chain,
2270                                     CallingConv::ID CallConv,
2271                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2272                                     SDLoc dl, SelectionDAG &DAG,
2273                                     const CCValAssign &VA,
2274                                     MachineFrameInfo *MFI,
2275                                     unsigned i) const {
2276   // Create the nodes corresponding to a load from this parameter slot.
2277   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2278   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2279       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2280   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2281   EVT ValVT;
2282
2283   // If value is passed by pointer we have address passed instead of the value
2284   // itself.
2285   bool ExtendedInMem = VA.isExtInLoc() &&
2286     VA.getValVT().getScalarType() == MVT::i1;
2287
2288   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2289     ValVT = VA.getLocVT();
2290   else
2291     ValVT = VA.getValVT();
2292
2293   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2294   // changed with more analysis.
2295   // In case of tail call optimization mark all arguments mutable. Since they
2296   // could be overwritten by lowering of arguments in case of a tail call.
2297   if (Flags.isByVal()) {
2298     unsigned Bytes = Flags.getByValSize();
2299     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2300     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2301     return DAG.getFrameIndex(FI, getPointerTy());
2302   } else {
2303     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2304                                     VA.getLocMemOffset(), isImmutable);
2305     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2306     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2307                                MachinePointerInfo::getFixedStack(FI),
2308                                false, false, false, 0);
2309     return ExtendedInMem ?
2310       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2311   }
2312 }
2313
2314 // FIXME: Get this from tablegen.
2315 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2316                                                 const X86Subtarget *Subtarget) {
2317   assert(Subtarget->is64Bit());
2318
2319   if (Subtarget->isCallingConvWin64(CallConv)) {
2320     static const MCPhysReg GPR64ArgRegsWin64[] = {
2321       X86::RCX, X86::RDX, X86::R8,  X86::R9
2322     };
2323     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2324   }
2325
2326   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2327     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2328   };
2329   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2330 }
2331
2332 // FIXME: Get this from tablegen.
2333 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2334                                                 CallingConv::ID CallConv,
2335                                                 const X86Subtarget *Subtarget) {
2336   assert(Subtarget->is64Bit());
2337   if (Subtarget->isCallingConvWin64(CallConv)) {
2338     // The XMM registers which might contain var arg parameters are shadowed
2339     // in their paired GPR.  So we only need to save the GPR to their home
2340     // slots.
2341     // TODO: __vectorcall will change this.
2342     return None;
2343   }
2344
2345   const Function *Fn = MF.getFunction();
2346   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2347   bool isSoftFloat = Subtarget->useSoftFloat();
2348   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2349          "SSE register cannot be used when SSE is disabled!");
2350   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2351     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2352     // registers.
2353     return None;
2354
2355   static const MCPhysReg XMMArgRegs64Bit[] = {
2356     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2357     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2358   };
2359   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2360 }
2361
2362 SDValue
2363 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2364                                         CallingConv::ID CallConv,
2365                                         bool isVarArg,
2366                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2367                                         SDLoc dl,
2368                                         SelectionDAG &DAG,
2369                                         SmallVectorImpl<SDValue> &InVals)
2370                                           const {
2371   MachineFunction &MF = DAG.getMachineFunction();
2372   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2373   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2374
2375   const Function* Fn = MF.getFunction();
2376   if (Fn->hasExternalLinkage() &&
2377       Subtarget->isTargetCygMing() &&
2378       Fn->getName() == "main")
2379     FuncInfo->setForceFramePointer(true);
2380
2381   MachineFrameInfo *MFI = MF.getFrameInfo();
2382   bool Is64Bit = Subtarget->is64Bit();
2383   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2384
2385   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2386          "Var args not supported with calling convention fastcc, ghc or hipe");
2387
2388   // Assign locations to all of the incoming arguments.
2389   SmallVector<CCValAssign, 16> ArgLocs;
2390   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2391
2392   // Allocate shadow area for Win64
2393   if (IsWin64)
2394     CCInfo.AllocateStack(32, 8);
2395
2396   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2397
2398   unsigned LastVal = ~0U;
2399   SDValue ArgValue;
2400   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2401     CCValAssign &VA = ArgLocs[i];
2402     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2403     // places.
2404     assert(VA.getValNo() != LastVal &&
2405            "Don't support value assigned to multiple locs yet");
2406     (void)LastVal;
2407     LastVal = VA.getValNo();
2408
2409     if (VA.isRegLoc()) {
2410       EVT RegVT = VA.getLocVT();
2411       const TargetRegisterClass *RC;
2412       if (RegVT == MVT::i32)
2413         RC = &X86::GR32RegClass;
2414       else if (Is64Bit && RegVT == MVT::i64)
2415         RC = &X86::GR64RegClass;
2416       else if (RegVT == MVT::f32)
2417         RC = &X86::FR32RegClass;
2418       else if (RegVT == MVT::f64)
2419         RC = &X86::FR64RegClass;
2420       else if (RegVT.is512BitVector())
2421         RC = &X86::VR512RegClass;
2422       else if (RegVT.is256BitVector())
2423         RC = &X86::VR256RegClass;
2424       else if (RegVT.is128BitVector())
2425         RC = &X86::VR128RegClass;
2426       else if (RegVT == MVT::x86mmx)
2427         RC = &X86::VR64RegClass;
2428       else if (RegVT == MVT::i1)
2429         RC = &X86::VK1RegClass;
2430       else if (RegVT == MVT::v8i1)
2431         RC = &X86::VK8RegClass;
2432       else if (RegVT == MVT::v16i1)
2433         RC = &X86::VK16RegClass;
2434       else if (RegVT == MVT::v32i1)
2435         RC = &X86::VK32RegClass;
2436       else if (RegVT == MVT::v64i1)
2437         RC = &X86::VK64RegClass;
2438       else
2439         llvm_unreachable("Unknown argument type!");
2440
2441       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2442       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2443
2444       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2445       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2446       // right size.
2447       if (VA.getLocInfo() == CCValAssign::SExt)
2448         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2449                                DAG.getValueType(VA.getValVT()));
2450       else if (VA.getLocInfo() == CCValAssign::ZExt)
2451         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2452                                DAG.getValueType(VA.getValVT()));
2453       else if (VA.getLocInfo() == CCValAssign::BCvt)
2454         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2455
2456       if (VA.isExtInLoc()) {
2457         // Handle MMX values passed in XMM regs.
2458         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2459           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2460         else
2461           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2462       }
2463     } else {
2464       assert(VA.isMemLoc());
2465       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2466     }
2467
2468     // If value is passed via pointer - do a load.
2469     if (VA.getLocInfo() == CCValAssign::Indirect)
2470       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2471                              MachinePointerInfo(), false, false, false, 0);
2472
2473     InVals.push_back(ArgValue);
2474   }
2475
2476   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2477     // All x86 ABIs require that for returning structs by value we copy the
2478     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2479     // the argument into a virtual register so that we can access it from the
2480     // return points.
2481     if (Ins[i].Flags.isSRet()) {
2482       unsigned Reg = FuncInfo->getSRetReturnReg();
2483       if (!Reg) {
2484         MVT PtrTy = getPointerTy();
2485         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2486         FuncInfo->setSRetReturnReg(Reg);
2487       }
2488       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2489       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2490       break;
2491     }
2492   }
2493
2494   unsigned StackSize = CCInfo.getNextStackOffset();
2495   // Align stack specially for tail calls.
2496   if (FuncIsMadeTailCallSafe(CallConv,
2497                              MF.getTarget().Options.GuaranteedTailCallOpt))
2498     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2499
2500   // If the function takes variable number of arguments, make a frame index for
2501   // the start of the first vararg value... for expansion of llvm.va_start. We
2502   // can skip this if there are no va_start calls.
2503   if (MFI->hasVAStart() &&
2504       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2505                    CallConv != CallingConv::X86_ThisCall))) {
2506     FuncInfo->setVarArgsFrameIndex(
2507         MFI->CreateFixedObject(1, StackSize, true));
2508   }
2509
2510   MachineModuleInfo &MMI = MF.getMMI();
2511   const Function *WinEHParent = nullptr;
2512   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2513     WinEHParent = MMI.getWinEHParent(Fn);
2514   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2515   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2516
2517   // Figure out if XMM registers are in use.
2518   assert(!(Subtarget->useSoftFloat() &&
2519            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2520          "SSE register cannot be used when SSE is disabled!");
2521
2522   // 64-bit calling conventions support varargs and register parameters, so we
2523   // have to do extra work to spill them in the prologue.
2524   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2525     // Find the first unallocated argument registers.
2526     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2527     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2528     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2529     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2530     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2531            "SSE register cannot be used when SSE is disabled!");
2532
2533     // Gather all the live in physical registers.
2534     SmallVector<SDValue, 6> LiveGPRs;
2535     SmallVector<SDValue, 8> LiveXMMRegs;
2536     SDValue ALVal;
2537     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2538       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2539       LiveGPRs.push_back(
2540           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2541     }
2542     if (!ArgXMMs.empty()) {
2543       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2544       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2545       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2546         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2547         LiveXMMRegs.push_back(
2548             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2549       }
2550     }
2551
2552     if (IsWin64) {
2553       // Get to the caller-allocated home save location.  Add 8 to account
2554       // for the return address.
2555       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2556       FuncInfo->setRegSaveFrameIndex(
2557           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2558       // Fixup to set vararg frame on shadow area (4 x i64).
2559       if (NumIntRegs < 4)
2560         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2561     } else {
2562       // For X86-64, if there are vararg parameters that are passed via
2563       // registers, then we must store them to their spots on the stack so
2564       // they may be loaded by deferencing the result of va_next.
2565       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2566       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2567       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2568           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2569     }
2570
2571     // Store the integer parameter registers.
2572     SmallVector<SDValue, 8> MemOps;
2573     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2574                                       getPointerTy());
2575     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2576     for (SDValue Val : LiveGPRs) {
2577       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2578                                 DAG.getIntPtrConstant(Offset, dl));
2579       SDValue Store =
2580         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2581                      MachinePointerInfo::getFixedStack(
2582                        FuncInfo->getRegSaveFrameIndex(), Offset),
2583                      false, false, 0);
2584       MemOps.push_back(Store);
2585       Offset += 8;
2586     }
2587
2588     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2589       // Now store the XMM (fp + vector) parameter registers.
2590       SmallVector<SDValue, 12> SaveXMMOps;
2591       SaveXMMOps.push_back(Chain);
2592       SaveXMMOps.push_back(ALVal);
2593       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2594                              FuncInfo->getRegSaveFrameIndex(), dl));
2595       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2596                              FuncInfo->getVarArgsFPOffset(), dl));
2597       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2598                         LiveXMMRegs.end());
2599       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2600                                    MVT::Other, SaveXMMOps));
2601     }
2602
2603     if (!MemOps.empty())
2604       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2605   } else if (IsWinEHOutlined) {
2606     // Get to the caller-allocated home save location.  Add 8 to account
2607     // for the return address.
2608     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2609     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2610         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2611
2612     MMI.getWinEHFuncInfo(Fn)
2613         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2614         FuncInfo->getRegSaveFrameIndex();
2615
2616     // Store the second integer parameter (rdx) into rsp+16 relative to the
2617     // stack pointer at the entry of the function.
2618     SDValue RSFIN =
2619         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2620     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2621     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2622     Chain = DAG.getStore(
2623         Val.getValue(1), dl, Val, RSFIN,
2624         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2625         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2626   }
2627
2628   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2629     // Find the largest legal vector type.
2630     MVT VecVT = MVT::Other;
2631     // FIXME: Only some x86_32 calling conventions support AVX512.
2632     if (Subtarget->hasAVX512() &&
2633         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2634                      CallConv == CallingConv::Intel_OCL_BI)))
2635       VecVT = MVT::v16f32;
2636     else if (Subtarget->hasAVX())
2637       VecVT = MVT::v8f32;
2638     else if (Subtarget->hasSSE2())
2639       VecVT = MVT::v4f32;
2640
2641     // We forward some GPRs and some vector types.
2642     SmallVector<MVT, 2> RegParmTypes;
2643     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2644     RegParmTypes.push_back(IntVT);
2645     if (VecVT != MVT::Other)
2646       RegParmTypes.push_back(VecVT);
2647
2648     // Compute the set of forwarded registers. The rest are scratch.
2649     SmallVectorImpl<ForwardedRegister> &Forwards =
2650         FuncInfo->getForwardedMustTailRegParms();
2651     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2652
2653     // Conservatively forward AL on x86_64, since it might be used for varargs.
2654     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2655       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2656       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2657     }
2658
2659     // Copy all forwards from physical to virtual registers.
2660     for (ForwardedRegister &F : Forwards) {
2661       // FIXME: Can we use a less constrained schedule?
2662       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2663       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2664       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2665     }
2666   }
2667
2668   // Some CCs need callee pop.
2669   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2670                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2671     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2672   } else {
2673     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2674     // If this is an sret function, the return should pop the hidden pointer.
2675     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2676         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2677         argsAreStructReturn(Ins) == StackStructReturn)
2678       FuncInfo->setBytesToPopOnReturn(4);
2679   }
2680
2681   if (!Is64Bit) {
2682     // RegSaveFrameIndex is X86-64 only.
2683     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2684     if (CallConv == CallingConv::X86_FastCall ||
2685         CallConv == CallingConv::X86_ThisCall)
2686       // fastcc functions can't have varargs.
2687       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2688   }
2689
2690   FuncInfo->setArgumentStackSize(StackSize);
2691
2692   if (IsWinEHParent) {
2693     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2694     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2695     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2696     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2697     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2698                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2699                          /*isVolatile=*/true,
2700                          /*isNonTemporal=*/false, /*Alignment=*/0);
2701   }
2702
2703   return Chain;
2704 }
2705
2706 SDValue
2707 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2708                                     SDValue StackPtr, SDValue Arg,
2709                                     SDLoc dl, SelectionDAG &DAG,
2710                                     const CCValAssign &VA,
2711                                     ISD::ArgFlagsTy Flags) const {
2712   unsigned LocMemOffset = VA.getLocMemOffset();
2713   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2714   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2715   if (Flags.isByVal())
2716     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2717
2718   return DAG.getStore(Chain, dl, Arg, PtrOff,
2719                       MachinePointerInfo::getStack(LocMemOffset),
2720                       false, false, 0);
2721 }
2722
2723 /// Emit a load of return address if tail call
2724 /// optimization is performed and it is required.
2725 SDValue
2726 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2727                                            SDValue &OutRetAddr, SDValue Chain,
2728                                            bool IsTailCall, bool Is64Bit,
2729                                            int FPDiff, SDLoc dl) const {
2730   // Adjust the Return address stack slot.
2731   EVT VT = getPointerTy();
2732   OutRetAddr = getReturnAddressFrameIndex(DAG);
2733
2734   // Load the "old" Return address.
2735   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2736                            false, false, false, 0);
2737   return SDValue(OutRetAddr.getNode(), 1);
2738 }
2739
2740 /// Emit a store of the return address if tail call
2741 /// optimization is performed and it is required (FPDiff!=0).
2742 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2743                                         SDValue Chain, SDValue RetAddrFrIdx,
2744                                         EVT PtrVT, unsigned SlotSize,
2745                                         int FPDiff, SDLoc dl) {
2746   // Store the return address to the appropriate stack slot.
2747   if (!FPDiff) return Chain;
2748   // Calculate the new stack slot for the return address.
2749   int NewReturnAddrFI =
2750     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2751                                          false);
2752   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2753   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2754                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2755                        false, false, 0);
2756   return Chain;
2757 }
2758
2759 SDValue
2760 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2761                              SmallVectorImpl<SDValue> &InVals) const {
2762   SelectionDAG &DAG                     = CLI.DAG;
2763   SDLoc &dl                             = CLI.DL;
2764   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2765   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2766   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2767   SDValue Chain                         = CLI.Chain;
2768   SDValue Callee                        = CLI.Callee;
2769   CallingConv::ID CallConv              = CLI.CallConv;
2770   bool &isTailCall                      = CLI.IsTailCall;
2771   bool isVarArg                         = CLI.IsVarArg;
2772
2773   MachineFunction &MF = DAG.getMachineFunction();
2774   bool Is64Bit        = Subtarget->is64Bit();
2775   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2776   StructReturnType SR = callIsStructReturn(Outs);
2777   bool IsSibcall      = false;
2778   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2779
2780   if (MF.getTarget().Options.DisableTailCalls)
2781     isTailCall = false;
2782
2783   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2784   if (IsMustTail) {
2785     // Force this to be a tail call.  The verifier rules are enough to ensure
2786     // that we can lower this successfully without moving the return address
2787     // around.
2788     isTailCall = true;
2789   } else if (isTailCall) {
2790     // Check if it's really possible to do a tail call.
2791     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2792                     isVarArg, SR != NotStructReturn,
2793                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2794                     Outs, OutVals, Ins, DAG);
2795
2796     // Sibcalls are automatically detected tailcalls which do not require
2797     // ABI changes.
2798     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2799       IsSibcall = true;
2800
2801     if (isTailCall)
2802       ++NumTailCalls;
2803   }
2804
2805   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2806          "Var args not supported with calling convention fastcc, ghc or hipe");
2807
2808   // Analyze operands of the call, assigning locations to each operand.
2809   SmallVector<CCValAssign, 16> ArgLocs;
2810   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2811
2812   // Allocate shadow area for Win64
2813   if (IsWin64)
2814     CCInfo.AllocateStack(32, 8);
2815
2816   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2817
2818   // Get a count of how many bytes are to be pushed on the stack.
2819   unsigned NumBytes = CCInfo.getNextStackOffset();
2820   if (IsSibcall)
2821     // This is a sibcall. The memory operands are available in caller's
2822     // own caller's stack.
2823     NumBytes = 0;
2824   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2825            IsTailCallConvention(CallConv))
2826     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2827
2828   int FPDiff = 0;
2829   if (isTailCall && !IsSibcall && !IsMustTail) {
2830     // Lower arguments at fp - stackoffset + fpdiff.
2831     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2832
2833     FPDiff = NumBytesCallerPushed - NumBytes;
2834
2835     // Set the delta of movement of the returnaddr stackslot.
2836     // But only set if delta is greater than previous delta.
2837     if (FPDiff < X86Info->getTCReturnAddrDelta())
2838       X86Info->setTCReturnAddrDelta(FPDiff);
2839   }
2840
2841   unsigned NumBytesToPush = NumBytes;
2842   unsigned NumBytesToPop = NumBytes;
2843
2844   // If we have an inalloca argument, all stack space has already been allocated
2845   // for us and be right at the top of the stack.  We don't support multiple
2846   // arguments passed in memory when using inalloca.
2847   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2848     NumBytesToPush = 0;
2849     if (!ArgLocs.back().isMemLoc())
2850       report_fatal_error("cannot use inalloca attribute on a register "
2851                          "parameter");
2852     if (ArgLocs.back().getLocMemOffset() != 0)
2853       report_fatal_error("any parameter with the inalloca attribute must be "
2854                          "the only memory argument");
2855   }
2856
2857   if (!IsSibcall)
2858     Chain = DAG.getCALLSEQ_START(
2859         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2860
2861   SDValue RetAddrFrIdx;
2862   // Load return address for tail calls.
2863   if (isTailCall && FPDiff)
2864     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2865                                     Is64Bit, FPDiff, dl);
2866
2867   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2868   SmallVector<SDValue, 8> MemOpChains;
2869   SDValue StackPtr;
2870
2871   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2872   // of tail call optimization arguments are handle later.
2873   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2874   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2875     // Skip inalloca arguments, they have already been written.
2876     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2877     if (Flags.isInAlloca())
2878       continue;
2879
2880     CCValAssign &VA = ArgLocs[i];
2881     EVT RegVT = VA.getLocVT();
2882     SDValue Arg = OutVals[i];
2883     bool isByVal = Flags.isByVal();
2884
2885     // Promote the value if needed.
2886     switch (VA.getLocInfo()) {
2887     default: llvm_unreachable("Unknown loc info!");
2888     case CCValAssign::Full: break;
2889     case CCValAssign::SExt:
2890       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2891       break;
2892     case CCValAssign::ZExt:
2893       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2894       break;
2895     case CCValAssign::AExt:
2896       if (Arg.getValueType().isVector() &&
2897           Arg.getValueType().getScalarType() == MVT::i1)
2898         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2899       else if (RegVT.is128BitVector()) {
2900         // Special case: passing MMX values in XMM registers.
2901         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2902         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2903         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2904       } else
2905         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2906       break;
2907     case CCValAssign::BCvt:
2908       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2909       break;
2910     case CCValAssign::Indirect: {
2911       // Store the argument.
2912       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2913       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2914       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2915                            MachinePointerInfo::getFixedStack(FI),
2916                            false, false, 0);
2917       Arg = SpillSlot;
2918       break;
2919     }
2920     }
2921
2922     if (VA.isRegLoc()) {
2923       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2924       if (isVarArg && IsWin64) {
2925         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2926         // shadow reg if callee is a varargs function.
2927         unsigned ShadowReg = 0;
2928         switch (VA.getLocReg()) {
2929         case X86::XMM0: ShadowReg = X86::RCX; break;
2930         case X86::XMM1: ShadowReg = X86::RDX; break;
2931         case X86::XMM2: ShadowReg = X86::R8; break;
2932         case X86::XMM3: ShadowReg = X86::R9; break;
2933         }
2934         if (ShadowReg)
2935           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2936       }
2937     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2938       assert(VA.isMemLoc());
2939       if (!StackPtr.getNode())
2940         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2941                                       getPointerTy());
2942       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2943                                              dl, DAG, VA, Flags));
2944     }
2945   }
2946
2947   if (!MemOpChains.empty())
2948     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2949
2950   if (Subtarget->isPICStyleGOT()) {
2951     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2952     // GOT pointer.
2953     if (!isTailCall) {
2954       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2955                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2956     } else {
2957       // If we are tail calling and generating PIC/GOT style code load the
2958       // address of the callee into ECX. The value in ecx is used as target of
2959       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2960       // for tail calls on PIC/GOT architectures. Normally we would just put the
2961       // address of GOT into ebx and then call target@PLT. But for tail calls
2962       // ebx would be restored (since ebx is callee saved) before jumping to the
2963       // target@PLT.
2964
2965       // Note: The actual moving to ECX is done further down.
2966       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2967       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2968           !G->getGlobal()->hasProtectedVisibility())
2969         Callee = LowerGlobalAddress(Callee, DAG);
2970       else if (isa<ExternalSymbolSDNode>(Callee))
2971         Callee = LowerExternalSymbol(Callee, DAG);
2972     }
2973   }
2974
2975   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2976     // From AMD64 ABI document:
2977     // For calls that may call functions that use varargs or stdargs
2978     // (prototype-less calls or calls to functions containing ellipsis (...) in
2979     // the declaration) %al is used as hidden argument to specify the number
2980     // of SSE registers used. The contents of %al do not need to match exactly
2981     // the number of registers, but must be an ubound on the number of SSE
2982     // registers used and is in the range 0 - 8 inclusive.
2983
2984     // Count the number of XMM registers allocated.
2985     static const MCPhysReg XMMArgRegs[] = {
2986       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2987       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2988     };
2989     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2990     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2991            && "SSE registers cannot be used when SSE is disabled");
2992
2993     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2994                                         DAG.getConstant(NumXMMRegs, dl,
2995                                                         MVT::i8)));
2996   }
2997
2998   if (isVarArg && IsMustTail) {
2999     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3000     for (const auto &F : Forwards) {
3001       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3002       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3003     }
3004   }
3005
3006   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3007   // don't need this because the eligibility check rejects calls that require
3008   // shuffling arguments passed in memory.
3009   if (!IsSibcall && isTailCall) {
3010     // Force all the incoming stack arguments to be loaded from the stack
3011     // before any new outgoing arguments are stored to the stack, because the
3012     // outgoing stack slots may alias the incoming argument stack slots, and
3013     // the alias isn't otherwise explicit. This is slightly more conservative
3014     // than necessary, because it means that each store effectively depends
3015     // on every argument instead of just those arguments it would clobber.
3016     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3017
3018     SmallVector<SDValue, 8> MemOpChains2;
3019     SDValue FIN;
3020     int FI = 0;
3021     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3022       CCValAssign &VA = ArgLocs[i];
3023       if (VA.isRegLoc())
3024         continue;
3025       assert(VA.isMemLoc());
3026       SDValue Arg = OutVals[i];
3027       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3028       // Skip inalloca arguments.  They don't require any work.
3029       if (Flags.isInAlloca())
3030         continue;
3031       // Create frame index.
3032       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3033       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3034       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3035       FIN = DAG.getFrameIndex(FI, getPointerTy());
3036
3037       if (Flags.isByVal()) {
3038         // Copy relative to framepointer.
3039         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3040         if (!StackPtr.getNode())
3041           StackPtr = DAG.getCopyFromReg(Chain, dl,
3042                                         RegInfo->getStackRegister(),
3043                                         getPointerTy());
3044         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3045
3046         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3047                                                          ArgChain,
3048                                                          Flags, DAG, dl));
3049       } else {
3050         // Store relative to framepointer.
3051         MemOpChains2.push_back(
3052           DAG.getStore(ArgChain, dl, Arg, FIN,
3053                        MachinePointerInfo::getFixedStack(FI),
3054                        false, false, 0));
3055       }
3056     }
3057
3058     if (!MemOpChains2.empty())
3059       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3060
3061     // Store the return address to the appropriate stack slot.
3062     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3063                                      getPointerTy(), RegInfo->getSlotSize(),
3064                                      FPDiff, dl);
3065   }
3066
3067   // Build a sequence of copy-to-reg nodes chained together with token chain
3068   // and flag operands which copy the outgoing args into registers.
3069   SDValue InFlag;
3070   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3071     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3072                              RegsToPass[i].second, InFlag);
3073     InFlag = Chain.getValue(1);
3074   }
3075
3076   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3077     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3078     // In the 64-bit large code model, we have to make all calls
3079     // through a register, since the call instruction's 32-bit
3080     // pc-relative offset may not be large enough to hold the whole
3081     // address.
3082   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3083     // If the callee is a GlobalAddress node (quite common, every direct call
3084     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3085     // it.
3086     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3087
3088     // We should use extra load for direct calls to dllimported functions in
3089     // non-JIT mode.
3090     const GlobalValue *GV = G->getGlobal();
3091     if (!GV->hasDLLImportStorageClass()) {
3092       unsigned char OpFlags = 0;
3093       bool ExtraLoad = false;
3094       unsigned WrapperKind = ISD::DELETED_NODE;
3095
3096       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3097       // external symbols most go through the PLT in PIC mode.  If the symbol
3098       // has hidden or protected visibility, or if it is static or local, then
3099       // we don't need to use the PLT - we can directly call it.
3100       if (Subtarget->isTargetELF() &&
3101           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3102           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3103         OpFlags = X86II::MO_PLT;
3104       } else if (Subtarget->isPICStyleStubAny() &&
3105                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3106                  (!Subtarget->getTargetTriple().isMacOSX() ||
3107                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3108         // PC-relative references to external symbols should go through $stub,
3109         // unless we're building with the leopard linker or later, which
3110         // automatically synthesizes these stubs.
3111         OpFlags = X86II::MO_DARWIN_STUB;
3112       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3113                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3114         // If the function is marked as non-lazy, generate an indirect call
3115         // which loads from the GOT directly. This avoids runtime overhead
3116         // at the cost of eager binding (and one extra byte of encoding).
3117         OpFlags = X86II::MO_GOTPCREL;
3118         WrapperKind = X86ISD::WrapperRIP;
3119         ExtraLoad = true;
3120       }
3121
3122       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3123                                           G->getOffset(), OpFlags);
3124
3125       // Add a wrapper if needed.
3126       if (WrapperKind != ISD::DELETED_NODE)
3127         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3128       // Add extra indirection if needed.
3129       if (ExtraLoad)
3130         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3131                              MachinePointerInfo::getGOT(),
3132                              false, false, false, 0);
3133     }
3134   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3135     unsigned char OpFlags = 0;
3136
3137     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3138     // external symbols should go through the PLT.
3139     if (Subtarget->isTargetELF() &&
3140         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3141       OpFlags = X86II::MO_PLT;
3142     } else if (Subtarget->isPICStyleStubAny() &&
3143                (!Subtarget->getTargetTriple().isMacOSX() ||
3144                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3145       // PC-relative references to external symbols should go through $stub,
3146       // unless we're building with the leopard linker or later, which
3147       // automatically synthesizes these stubs.
3148       OpFlags = X86II::MO_DARWIN_STUB;
3149     }
3150
3151     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3152                                          OpFlags);
3153   } else if (Subtarget->isTarget64BitILP32() &&
3154              Callee->getValueType(0) == MVT::i32) {
3155     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3156     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3157   }
3158
3159   // Returns a chain & a flag for retval copy to use.
3160   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3161   SmallVector<SDValue, 8> Ops;
3162
3163   if (!IsSibcall && isTailCall) {
3164     Chain = DAG.getCALLSEQ_END(Chain,
3165                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3166                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3167     InFlag = Chain.getValue(1);
3168   }
3169
3170   Ops.push_back(Chain);
3171   Ops.push_back(Callee);
3172
3173   if (isTailCall)
3174     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3175
3176   // Add argument registers to the end of the list so that they are known live
3177   // into the call.
3178   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3179     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3180                                   RegsToPass[i].second.getValueType()));
3181
3182   // Add a register mask operand representing the call-preserved registers.
3183   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3184   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3185   assert(Mask && "Missing call preserved mask for calling convention");
3186   Ops.push_back(DAG.getRegisterMask(Mask));
3187
3188   if (InFlag.getNode())
3189     Ops.push_back(InFlag);
3190
3191   if (isTailCall) {
3192     // We used to do:
3193     //// If this is the first return lowered for this function, add the regs
3194     //// to the liveout set for the function.
3195     // This isn't right, although it's probably harmless on x86; liveouts
3196     // should be computed from returns not tail calls.  Consider a void
3197     // function making a tail call to a function returning int.
3198     MF.getFrameInfo()->setHasTailCall();
3199     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3200   }
3201
3202   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3203   InFlag = Chain.getValue(1);
3204
3205   // Create the CALLSEQ_END node.
3206   unsigned NumBytesForCalleeToPop;
3207   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3208                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3209     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3210   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3211            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3212            SR == StackStructReturn)
3213     // If this is a call to a struct-return function, the callee
3214     // pops the hidden struct pointer, so we have to push it back.
3215     // This is common for Darwin/X86, Linux & Mingw32 targets.
3216     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3217     NumBytesForCalleeToPop = 4;
3218   else
3219     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3220
3221   // Returns a flag for retval copy to use.
3222   if (!IsSibcall) {
3223     Chain = DAG.getCALLSEQ_END(Chain,
3224                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3225                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3226                                                      true),
3227                                InFlag, dl);
3228     InFlag = Chain.getValue(1);
3229   }
3230
3231   // Handle result values, copying them out of physregs into vregs that we
3232   // return.
3233   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3234                          Ins, dl, DAG, InVals);
3235 }
3236
3237 //===----------------------------------------------------------------------===//
3238 //                Fast Calling Convention (tail call) implementation
3239 //===----------------------------------------------------------------------===//
3240
3241 //  Like std call, callee cleans arguments, convention except that ECX is
3242 //  reserved for storing the tail called function address. Only 2 registers are
3243 //  free for argument passing (inreg). Tail call optimization is performed
3244 //  provided:
3245 //                * tailcallopt is enabled
3246 //                * caller/callee are fastcc
3247 //  On X86_64 architecture with GOT-style position independent code only local
3248 //  (within module) calls are supported at the moment.
3249 //  To keep the stack aligned according to platform abi the function
3250 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3251 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3252 //  If a tail called function callee has more arguments than the caller the
3253 //  caller needs to make sure that there is room to move the RETADDR to. This is
3254 //  achieved by reserving an area the size of the argument delta right after the
3255 //  original RETADDR, but before the saved framepointer or the spilled registers
3256 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3257 //  stack layout:
3258 //    arg1
3259 //    arg2
3260 //    RETADDR
3261 //    [ new RETADDR
3262 //      move area ]
3263 //    (possible EBP)
3264 //    ESI
3265 //    EDI
3266 //    local1 ..
3267
3268 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3269 /// for a 16 byte align requirement.
3270 unsigned
3271 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3272                                                SelectionDAG& DAG) const {
3273   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3274   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3275   unsigned StackAlignment = TFI.getStackAlignment();
3276   uint64_t AlignMask = StackAlignment - 1;
3277   int64_t Offset = StackSize;
3278   unsigned SlotSize = RegInfo->getSlotSize();
3279   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3280     // Number smaller than 12 so just add the difference.
3281     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3282   } else {
3283     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3284     Offset = ((~AlignMask) & Offset) + StackAlignment +
3285       (StackAlignment-SlotSize);
3286   }
3287   return Offset;
3288 }
3289
3290 /// MatchingStackOffset - Return true if the given stack call argument is
3291 /// already available in the same position (relatively) of the caller's
3292 /// incoming argument stack.
3293 static
3294 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3295                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3296                          const X86InstrInfo *TII) {
3297   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3298   int FI = INT_MAX;
3299   if (Arg.getOpcode() == ISD::CopyFromReg) {
3300     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3301     if (!TargetRegisterInfo::isVirtualRegister(VR))
3302       return false;
3303     MachineInstr *Def = MRI->getVRegDef(VR);
3304     if (!Def)
3305       return false;
3306     if (!Flags.isByVal()) {
3307       if (!TII->isLoadFromStackSlot(Def, FI))
3308         return false;
3309     } else {
3310       unsigned Opcode = Def->getOpcode();
3311       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3312            Opcode == X86::LEA64_32r) &&
3313           Def->getOperand(1).isFI()) {
3314         FI = Def->getOperand(1).getIndex();
3315         Bytes = Flags.getByValSize();
3316       } else
3317         return false;
3318     }
3319   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3320     if (Flags.isByVal())
3321       // ByVal argument is passed in as a pointer but it's now being
3322       // dereferenced. e.g.
3323       // define @foo(%struct.X* %A) {
3324       //   tail call @bar(%struct.X* byval %A)
3325       // }
3326       return false;
3327     SDValue Ptr = Ld->getBasePtr();
3328     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3329     if (!FINode)
3330       return false;
3331     FI = FINode->getIndex();
3332   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3333     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3334     FI = FINode->getIndex();
3335     Bytes = Flags.getByValSize();
3336   } else
3337     return false;
3338
3339   assert(FI != INT_MAX);
3340   if (!MFI->isFixedObjectIndex(FI))
3341     return false;
3342   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3343 }
3344
3345 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3346 /// for tail call optimization. Targets which want to do tail call
3347 /// optimization should implement this function.
3348 bool
3349 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3350                                                      CallingConv::ID CalleeCC,
3351                                                      bool isVarArg,
3352                                                      bool isCalleeStructRet,
3353                                                      bool isCallerStructRet,
3354                                                      Type *RetTy,
3355                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3356                                     const SmallVectorImpl<SDValue> &OutVals,
3357                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3358                                                      SelectionDAG &DAG) const {
3359   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3360     return false;
3361
3362   // If -tailcallopt is specified, make fastcc functions tail-callable.
3363   const MachineFunction &MF = DAG.getMachineFunction();
3364   const Function *CallerF = MF.getFunction();
3365
3366   // If the function return type is x86_fp80 and the callee return type is not,
3367   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3368   // perform a tailcall optimization here.
3369   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3370     return false;
3371
3372   CallingConv::ID CallerCC = CallerF->getCallingConv();
3373   bool CCMatch = CallerCC == CalleeCC;
3374   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3375   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3376
3377   // Win64 functions have extra shadow space for argument homing. Don't do the
3378   // sibcall if the caller and callee have mismatched expectations for this
3379   // space.
3380   if (IsCalleeWin64 != IsCallerWin64)
3381     return false;
3382
3383   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3384     if (IsTailCallConvention(CalleeCC) && CCMatch)
3385       return true;
3386     return false;
3387   }
3388
3389   // Look for obvious safe cases to perform tail call optimization that do not
3390   // require ABI changes. This is what gcc calls sibcall.
3391
3392   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3393   // emit a special epilogue.
3394   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3395   if (RegInfo->needsStackRealignment(MF))
3396     return false;
3397
3398   // Also avoid sibcall optimization if either caller or callee uses struct
3399   // return semantics.
3400   if (isCalleeStructRet || isCallerStructRet)
3401     return false;
3402
3403   // An stdcall/thiscall caller is expected to clean up its arguments; the
3404   // callee isn't going to do that.
3405   // FIXME: this is more restrictive than needed. We could produce a tailcall
3406   // when the stack adjustment matches. For example, with a thiscall that takes
3407   // only one argument.
3408   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3409                    CallerCC == CallingConv::X86_ThisCall))
3410     return false;
3411
3412   // Do not sibcall optimize vararg calls unless all arguments are passed via
3413   // registers.
3414   if (isVarArg && !Outs.empty()) {
3415
3416     // Optimizing for varargs on Win64 is unlikely to be safe without
3417     // additional testing.
3418     if (IsCalleeWin64 || IsCallerWin64)
3419       return false;
3420
3421     SmallVector<CCValAssign, 16> ArgLocs;
3422     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3423                    *DAG.getContext());
3424
3425     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3426     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3427       if (!ArgLocs[i].isRegLoc())
3428         return false;
3429   }
3430
3431   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3432   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3433   // this into a sibcall.
3434   bool Unused = false;
3435   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3436     if (!Ins[i].Used) {
3437       Unused = true;
3438       break;
3439     }
3440   }
3441   if (Unused) {
3442     SmallVector<CCValAssign, 16> RVLocs;
3443     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3444                    *DAG.getContext());
3445     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3446     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3447       CCValAssign &VA = RVLocs[i];
3448       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3449         return false;
3450     }
3451   }
3452
3453   // If the calling conventions do not match, then we'd better make sure the
3454   // results are returned in the same way as what the caller expects.
3455   if (!CCMatch) {
3456     SmallVector<CCValAssign, 16> RVLocs1;
3457     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3458                     *DAG.getContext());
3459     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3460
3461     SmallVector<CCValAssign, 16> RVLocs2;
3462     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3463                     *DAG.getContext());
3464     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3465
3466     if (RVLocs1.size() != RVLocs2.size())
3467       return false;
3468     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3469       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3470         return false;
3471       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3472         return false;
3473       if (RVLocs1[i].isRegLoc()) {
3474         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3475           return false;
3476       } else {
3477         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3478           return false;
3479       }
3480     }
3481   }
3482
3483   // If the callee takes no arguments then go on to check the results of the
3484   // call.
3485   if (!Outs.empty()) {
3486     // Check if stack adjustment is needed. For now, do not do this if any
3487     // argument is passed on the stack.
3488     SmallVector<CCValAssign, 16> ArgLocs;
3489     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3490                    *DAG.getContext());
3491
3492     // Allocate shadow area for Win64
3493     if (IsCalleeWin64)
3494       CCInfo.AllocateStack(32, 8);
3495
3496     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3497     if (CCInfo.getNextStackOffset()) {
3498       MachineFunction &MF = DAG.getMachineFunction();
3499       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3500         return false;
3501
3502       // Check if the arguments are already laid out in the right way as
3503       // the caller's fixed stack objects.
3504       MachineFrameInfo *MFI = MF.getFrameInfo();
3505       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3506       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3507       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3508         CCValAssign &VA = ArgLocs[i];
3509         SDValue Arg = OutVals[i];
3510         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3511         if (VA.getLocInfo() == CCValAssign::Indirect)
3512           return false;
3513         if (!VA.isRegLoc()) {
3514           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3515                                    MFI, MRI, TII))
3516             return false;
3517         }
3518       }
3519     }
3520
3521     // If the tailcall address may be in a register, then make sure it's
3522     // possible to register allocate for it. In 32-bit, the call address can
3523     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3524     // callee-saved registers are restored. These happen to be the same
3525     // registers used to pass 'inreg' arguments so watch out for those.
3526     if (!Subtarget->is64Bit() &&
3527         ((!isa<GlobalAddressSDNode>(Callee) &&
3528           !isa<ExternalSymbolSDNode>(Callee)) ||
3529          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3530       unsigned NumInRegs = 0;
3531       // In PIC we need an extra register to formulate the address computation
3532       // for the callee.
3533       unsigned MaxInRegs =
3534         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3535
3536       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3537         CCValAssign &VA = ArgLocs[i];
3538         if (!VA.isRegLoc())
3539           continue;
3540         unsigned Reg = VA.getLocReg();
3541         switch (Reg) {
3542         default: break;
3543         case X86::EAX: case X86::EDX: case X86::ECX:
3544           if (++NumInRegs == MaxInRegs)
3545             return false;
3546           break;
3547         }
3548       }
3549     }
3550   }
3551
3552   return true;
3553 }
3554
3555 FastISel *
3556 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3557                                   const TargetLibraryInfo *libInfo) const {
3558   return X86::createFastISel(funcInfo, libInfo);
3559 }
3560
3561 //===----------------------------------------------------------------------===//
3562 //                           Other Lowering Hooks
3563 //===----------------------------------------------------------------------===//
3564
3565 static bool MayFoldLoad(SDValue Op) {
3566   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3567 }
3568
3569 static bool MayFoldIntoStore(SDValue Op) {
3570   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3571 }
3572
3573 static bool isTargetShuffle(unsigned Opcode) {
3574   switch(Opcode) {
3575   default: return false;
3576   case X86ISD::BLENDI:
3577   case X86ISD::PSHUFB:
3578   case X86ISD::PSHUFD:
3579   case X86ISD::PSHUFHW:
3580   case X86ISD::PSHUFLW:
3581   case X86ISD::SHUFP:
3582   case X86ISD::PALIGNR:
3583   case X86ISD::MOVLHPS:
3584   case X86ISD::MOVLHPD:
3585   case X86ISD::MOVHLPS:
3586   case X86ISD::MOVLPS:
3587   case X86ISD::MOVLPD:
3588   case X86ISD::MOVSHDUP:
3589   case X86ISD::MOVSLDUP:
3590   case X86ISD::MOVDDUP:
3591   case X86ISD::MOVSS:
3592   case X86ISD::MOVSD:
3593   case X86ISD::UNPCKL:
3594   case X86ISD::UNPCKH:
3595   case X86ISD::VPERMILPI:
3596   case X86ISD::VPERM2X128:
3597   case X86ISD::VPERMI:
3598     return true;
3599   }
3600 }
3601
3602 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3603                                     SDValue V1, unsigned TargetMask,
3604                                     SelectionDAG &DAG) {
3605   switch(Opc) {
3606   default: llvm_unreachable("Unknown x86 shuffle node");
3607   case X86ISD::PSHUFD:
3608   case X86ISD::PSHUFHW:
3609   case X86ISD::PSHUFLW:
3610   case X86ISD::VPERMILPI:
3611   case X86ISD::VPERMI:
3612     return DAG.getNode(Opc, dl, VT, V1,
3613                        DAG.getConstant(TargetMask, dl, MVT::i8));
3614   }
3615 }
3616
3617 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3618                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3619   switch(Opc) {
3620   default: llvm_unreachable("Unknown x86 shuffle node");
3621   case X86ISD::MOVLHPS:
3622   case X86ISD::MOVLHPD:
3623   case X86ISD::MOVHLPS:
3624   case X86ISD::MOVLPS:
3625   case X86ISD::MOVLPD:
3626   case X86ISD::MOVSS:
3627   case X86ISD::MOVSD:
3628   case X86ISD::UNPCKL:
3629   case X86ISD::UNPCKH:
3630     return DAG.getNode(Opc, dl, VT, V1, V2);
3631   }
3632 }
3633
3634 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3635   MachineFunction &MF = DAG.getMachineFunction();
3636   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3637   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3638   int ReturnAddrIndex = FuncInfo->getRAIndex();
3639
3640   if (ReturnAddrIndex == 0) {
3641     // Set up a frame object for the return address.
3642     unsigned SlotSize = RegInfo->getSlotSize();
3643     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3644                                                            -(int64_t)SlotSize,
3645                                                            false);
3646     FuncInfo->setRAIndex(ReturnAddrIndex);
3647   }
3648
3649   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3650 }
3651
3652 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3653                                        bool hasSymbolicDisplacement) {
3654   // Offset should fit into 32 bit immediate field.
3655   if (!isInt<32>(Offset))
3656     return false;
3657
3658   // If we don't have a symbolic displacement - we don't have any extra
3659   // restrictions.
3660   if (!hasSymbolicDisplacement)
3661     return true;
3662
3663   // FIXME: Some tweaks might be needed for medium code model.
3664   if (M != CodeModel::Small && M != CodeModel::Kernel)
3665     return false;
3666
3667   // For small code model we assume that latest object is 16MB before end of 31
3668   // bits boundary. We may also accept pretty large negative constants knowing
3669   // that all objects are in the positive half of address space.
3670   if (M == CodeModel::Small && Offset < 16*1024*1024)
3671     return true;
3672
3673   // For kernel code model we know that all object resist in the negative half
3674   // of 32bits address space. We may not accept negative offsets, since they may
3675   // be just off and we may accept pretty large positive ones.
3676   if (M == CodeModel::Kernel && Offset >= 0)
3677     return true;
3678
3679   return false;
3680 }
3681
3682 /// isCalleePop - Determines whether the callee is required to pop its
3683 /// own arguments. Callee pop is necessary to support tail calls.
3684 bool X86::isCalleePop(CallingConv::ID CallingConv,
3685                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3686   switch (CallingConv) {
3687   default:
3688     return false;
3689   case CallingConv::X86_StdCall:
3690   case CallingConv::X86_FastCall:
3691   case CallingConv::X86_ThisCall:
3692     return !is64Bit;
3693   case CallingConv::Fast:
3694   case CallingConv::GHC:
3695   case CallingConv::HiPE:
3696     if (IsVarArg)
3697       return false;
3698     return TailCallOpt;
3699   }
3700 }
3701
3702 /// \brief Return true if the condition is an unsigned comparison operation.
3703 static bool isX86CCUnsigned(unsigned X86CC) {
3704   switch (X86CC) {
3705   default: llvm_unreachable("Invalid integer condition!");
3706   case X86::COND_E:     return true;
3707   case X86::COND_G:     return false;
3708   case X86::COND_GE:    return false;
3709   case X86::COND_L:     return false;
3710   case X86::COND_LE:    return false;
3711   case X86::COND_NE:    return true;
3712   case X86::COND_B:     return true;
3713   case X86::COND_A:     return true;
3714   case X86::COND_BE:    return true;
3715   case X86::COND_AE:    return true;
3716   }
3717   llvm_unreachable("covered switch fell through?!");
3718 }
3719
3720 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3721 /// specific condition code, returning the condition code and the LHS/RHS of the
3722 /// comparison to make.
3723 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3724                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3725   if (!isFP) {
3726     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3727       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3728         // X > -1   -> X == 0, jump !sign.
3729         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3730         return X86::COND_NS;
3731       }
3732       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3733         // X < 0   -> X == 0, jump on sign.
3734         return X86::COND_S;
3735       }
3736       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3737         // X < 1   -> X <= 0
3738         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3739         return X86::COND_LE;
3740       }
3741     }
3742
3743     switch (SetCCOpcode) {
3744     default: llvm_unreachable("Invalid integer condition!");
3745     case ISD::SETEQ:  return X86::COND_E;
3746     case ISD::SETGT:  return X86::COND_G;
3747     case ISD::SETGE:  return X86::COND_GE;
3748     case ISD::SETLT:  return X86::COND_L;
3749     case ISD::SETLE:  return X86::COND_LE;
3750     case ISD::SETNE:  return X86::COND_NE;
3751     case ISD::SETULT: return X86::COND_B;
3752     case ISD::SETUGT: return X86::COND_A;
3753     case ISD::SETULE: return X86::COND_BE;
3754     case ISD::SETUGE: return X86::COND_AE;
3755     }
3756   }
3757
3758   // First determine if it is required or is profitable to flip the operands.
3759
3760   // If LHS is a foldable load, but RHS is not, flip the condition.
3761   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3762       !ISD::isNON_EXTLoad(RHS.getNode())) {
3763     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3764     std::swap(LHS, RHS);
3765   }
3766
3767   switch (SetCCOpcode) {
3768   default: break;
3769   case ISD::SETOLT:
3770   case ISD::SETOLE:
3771   case ISD::SETUGT:
3772   case ISD::SETUGE:
3773     std::swap(LHS, RHS);
3774     break;
3775   }
3776
3777   // On a floating point condition, the flags are set as follows:
3778   // ZF  PF  CF   op
3779   //  0 | 0 | 0 | X > Y
3780   //  0 | 0 | 1 | X < Y
3781   //  1 | 0 | 0 | X == Y
3782   //  1 | 1 | 1 | unordered
3783   switch (SetCCOpcode) {
3784   default: llvm_unreachable("Condcode should be pre-legalized away");
3785   case ISD::SETUEQ:
3786   case ISD::SETEQ:   return X86::COND_E;
3787   case ISD::SETOLT:              // flipped
3788   case ISD::SETOGT:
3789   case ISD::SETGT:   return X86::COND_A;
3790   case ISD::SETOLE:              // flipped
3791   case ISD::SETOGE:
3792   case ISD::SETGE:   return X86::COND_AE;
3793   case ISD::SETUGT:              // flipped
3794   case ISD::SETULT:
3795   case ISD::SETLT:   return X86::COND_B;
3796   case ISD::SETUGE:              // flipped
3797   case ISD::SETULE:
3798   case ISD::SETLE:   return X86::COND_BE;
3799   case ISD::SETONE:
3800   case ISD::SETNE:   return X86::COND_NE;
3801   case ISD::SETUO:   return X86::COND_P;
3802   case ISD::SETO:    return X86::COND_NP;
3803   case ISD::SETOEQ:
3804   case ISD::SETUNE:  return X86::COND_INVALID;
3805   }
3806 }
3807
3808 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3809 /// code. Current x86 isa includes the following FP cmov instructions:
3810 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3811 static bool hasFPCMov(unsigned X86CC) {
3812   switch (X86CC) {
3813   default:
3814     return false;
3815   case X86::COND_B:
3816   case X86::COND_BE:
3817   case X86::COND_E:
3818   case X86::COND_P:
3819   case X86::COND_A:
3820   case X86::COND_AE:
3821   case X86::COND_NE:
3822   case X86::COND_NP:
3823     return true;
3824   }
3825 }
3826
3827 /// isFPImmLegal - Returns true if the target can instruction select the
3828 /// specified FP immediate natively. If false, the legalizer will
3829 /// materialize the FP immediate as a load from a constant pool.
3830 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3831   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3832     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3833       return true;
3834   }
3835   return false;
3836 }
3837
3838 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3839                                               ISD::LoadExtType ExtTy,
3840                                               EVT NewVT) const {
3841   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3842   // relocation target a movq or addq instruction: don't let the load shrink.
3843   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3844   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3845     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3846       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3847   return true;
3848 }
3849
3850 /// \brief Returns true if it is beneficial to convert a load of a constant
3851 /// to just the constant itself.
3852 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3853                                                           Type *Ty) const {
3854   assert(Ty->isIntegerTy());
3855
3856   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3857   if (BitSize == 0 || BitSize > 64)
3858     return false;
3859   return true;
3860 }
3861
3862 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3863                                                 unsigned Index) const {
3864   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3865     return false;
3866
3867   return (Index == 0 || Index == ResVT.getVectorNumElements());
3868 }
3869
3870 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3871   // Speculate cttz only if we can directly use TZCNT.
3872   return Subtarget->hasBMI();
3873 }
3874
3875 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3876   // Speculate ctlz only if we can directly use LZCNT.
3877   return Subtarget->hasLZCNT();
3878 }
3879
3880 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3881 /// the specified range (L, H].
3882 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3883   return (Val < 0) || (Val >= Low && Val < Hi);
3884 }
3885
3886 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3887 /// specified value.
3888 static bool isUndefOrEqual(int Val, int CmpVal) {
3889   return (Val < 0 || Val == CmpVal);
3890 }
3891
3892 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3893 /// from position Pos and ending in Pos+Size, falls within the specified
3894 /// sequential range (Low, Low+Size]. or is undef.
3895 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3896                                        unsigned Pos, unsigned Size, int Low) {
3897   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3898     if (!isUndefOrEqual(Mask[i], Low))
3899       return false;
3900   return true;
3901 }
3902
3903 /// isVEXTRACTIndex - Return true if the specified
3904 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3905 /// suitable for instruction that extract 128 or 256 bit vectors
3906 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3907   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3908   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3909     return false;
3910
3911   // The index should be aligned on a vecWidth-bit boundary.
3912   uint64_t Index =
3913     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3914
3915   MVT VT = N->getSimpleValueType(0);
3916   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3917   bool Result = (Index * ElSize) % vecWidth == 0;
3918
3919   return Result;
3920 }
3921
3922 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3923 /// operand specifies a subvector insert that is suitable for input to
3924 /// insertion of 128 or 256-bit subvectors
3925 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3926   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3927   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3928     return false;
3929   // The index should be aligned on a vecWidth-bit boundary.
3930   uint64_t Index =
3931     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3932
3933   MVT VT = N->getSimpleValueType(0);
3934   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3935   bool Result = (Index * ElSize) % vecWidth == 0;
3936
3937   return Result;
3938 }
3939
3940 bool X86::isVINSERT128Index(SDNode *N) {
3941   return isVINSERTIndex(N, 128);
3942 }
3943
3944 bool X86::isVINSERT256Index(SDNode *N) {
3945   return isVINSERTIndex(N, 256);
3946 }
3947
3948 bool X86::isVEXTRACT128Index(SDNode *N) {
3949   return isVEXTRACTIndex(N, 128);
3950 }
3951
3952 bool X86::isVEXTRACT256Index(SDNode *N) {
3953   return isVEXTRACTIndex(N, 256);
3954 }
3955
3956 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3957   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3958   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3959     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3960
3961   uint64_t Index =
3962     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3963
3964   MVT VecVT = N->getOperand(0).getSimpleValueType();
3965   MVT ElVT = VecVT.getVectorElementType();
3966
3967   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3968   return Index / NumElemsPerChunk;
3969 }
3970
3971 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3972   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3973   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3974     llvm_unreachable("Illegal insert subvector for VINSERT");
3975
3976   uint64_t Index =
3977     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3978
3979   MVT VecVT = N->getSimpleValueType(0);
3980   MVT ElVT = VecVT.getVectorElementType();
3981
3982   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3983   return Index / NumElemsPerChunk;
3984 }
3985
3986 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3987 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3988 /// and VINSERTI128 instructions.
3989 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3990   return getExtractVEXTRACTImmediate(N, 128);
3991 }
3992
3993 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3994 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3995 /// and VINSERTI64x4 instructions.
3996 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3997   return getExtractVEXTRACTImmediate(N, 256);
3998 }
3999
4000 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4001 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4002 /// and VINSERTI128 instructions.
4003 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4004   return getInsertVINSERTImmediate(N, 128);
4005 }
4006
4007 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4008 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4009 /// and VINSERTI64x4 instructions.
4010 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4011   return getInsertVINSERTImmediate(N, 256);
4012 }
4013
4014 /// isZero - Returns true if Elt is a constant integer zero
4015 static bool isZero(SDValue V) {
4016   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4017   return C && C->isNullValue();
4018 }
4019
4020 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4021 /// constant +0.0.
4022 bool X86::isZeroNode(SDValue Elt) {
4023   if (isZero(Elt))
4024     return true;
4025   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4026     return CFP->getValueAPF().isPosZero();
4027   return false;
4028 }
4029
4030 /// getZeroVector - Returns a vector of specified type with all zero elements.
4031 ///
4032 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4033                              SelectionDAG &DAG, SDLoc dl) {
4034   assert(VT.isVector() && "Expected a vector type");
4035
4036   // Always build SSE zero vectors as <4 x i32> bitcasted
4037   // to their dest type. This ensures they get CSE'd.
4038   SDValue Vec;
4039   if (VT.is128BitVector()) {  // SSE
4040     if (Subtarget->hasSSE2()) {  // SSE2
4041       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4042       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4043     } else { // SSE1
4044       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4045       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4046     }
4047   } else if (VT.is256BitVector()) { // AVX
4048     if (Subtarget->hasInt256()) { // AVX2
4049       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4050       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4051       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4052     } else {
4053       // 256-bit logic and arithmetic instructions in AVX are all
4054       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4055       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4056       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4057       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4058     }
4059   } else if (VT.is512BitVector()) { // AVX-512
4060       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4061       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4062                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4063       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4064   } else if (VT.getScalarType() == MVT::i1) {
4065
4066     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4067             && "Unexpected vector type");
4068     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4069             && "Unexpected vector type");
4070     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4071     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4072     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4073   } else
4074     llvm_unreachable("Unexpected vector type");
4075
4076   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4077 }
4078
4079 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4080                                 SelectionDAG &DAG, SDLoc dl,
4081                                 unsigned vectorWidth) {
4082   assert((vectorWidth == 128 || vectorWidth == 256) &&
4083          "Unsupported vector width");
4084   EVT VT = Vec.getValueType();
4085   EVT ElVT = VT.getVectorElementType();
4086   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4087   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4088                                   VT.getVectorNumElements()/Factor);
4089
4090   // Extract from UNDEF is UNDEF.
4091   if (Vec.getOpcode() == ISD::UNDEF)
4092     return DAG.getUNDEF(ResultVT);
4093
4094   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4095   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4096
4097   // This is the index of the first element of the vectorWidth-bit chunk
4098   // we want.
4099   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4100                                * ElemsPerChunk);
4101
4102   // If the input is a buildvector just emit a smaller one.
4103   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4104     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4105                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4106                                     ElemsPerChunk));
4107
4108   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4109   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4110 }
4111
4112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4115 /// instructions or a simple subregister reference. Idx is an index in the
4116 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4117 /// lowering EXTRACT_VECTOR_ELT operations easier.
4118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4119                                    SelectionDAG &DAG, SDLoc dl) {
4120   assert((Vec.getValueType().is256BitVector() ||
4121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4123 }
4124
4125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4127                                    SelectionDAG &DAG, SDLoc dl) {
4128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4130 }
4131
4132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4133                                unsigned IdxVal, SelectionDAG &DAG,
4134                                SDLoc dl, unsigned vectorWidth) {
4135   assert((vectorWidth == 128 || vectorWidth == 256) &&
4136          "Unsupported vector width");
4137   // Inserting UNDEF is Result
4138   if (Vec.getOpcode() == ISD::UNDEF)
4139     return Result;
4140   EVT VT = Vec.getValueType();
4141   EVT ElVT = VT.getVectorElementType();
4142   EVT ResultVT = Result.getValueType();
4143
4144   // Insert the relevant vectorWidth bits.
4145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4146
4147   // This is the index of the first element of the vectorWidth-bit chunk
4148   // we want.
4149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4150                                * ElemsPerChunk);
4151
4152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4154 }
4155
4156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4159 /// simple superregister reference.  Idx is an index in the 128 bits
4160 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4161 /// lowering INSERT_VECTOR_ELT operations easier.
4162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4163                                   SelectionDAG &DAG, SDLoc dl) {
4164   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4165
4166   // For insertion into the zero index (low half) of a 256-bit vector, it is
4167   // more efficient to generate a blend with immediate instead of an insert*128.
4168   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4169   // extend the subvector to the size of the result vector. Make sure that
4170   // we are not recursing on that node by checking for undef here.
4171   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4172       Result.getOpcode() != ISD::UNDEF) {
4173     EVT ResultVT = Result.getValueType();
4174     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4175     SDValue Undef = DAG.getUNDEF(ResultVT);
4176     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4177                                  Vec, ZeroIndex);
4178
4179     // The blend instruction, and therefore its mask, depend on the data type.
4180     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4181     if (ScalarType.isFloatingPoint()) {
4182       // Choose either vblendps (float) or vblendpd (double).
4183       unsigned ScalarSize = ScalarType.getSizeInBits();
4184       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4185       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4186       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4187       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4188     }
4189
4190     const X86Subtarget &Subtarget =
4191     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4192
4193     // AVX2 is needed for 256-bit integer blend support.
4194     // Integers must be cast to 32-bit because there is only vpblendd;
4195     // vpblendw can't be used for this because it has a handicapped mask.
4196
4197     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4198     // is still more efficient than using the wrong domain vinsertf128 that
4199     // will be created by InsertSubVector().
4200     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4201
4202     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4203     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4204     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4205     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4206   }
4207
4208   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4209 }
4210
4211 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4212                                   SelectionDAG &DAG, SDLoc dl) {
4213   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4214   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4215 }
4216
4217 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4218 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4219 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4220 /// large BUILD_VECTORS.
4221 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4222                                    unsigned NumElems, SelectionDAG &DAG,
4223                                    SDLoc dl) {
4224   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4225   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4226 }
4227
4228 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4229                                    unsigned NumElems, SelectionDAG &DAG,
4230                                    SDLoc dl) {
4231   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4232   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4233 }
4234
4235 /// getOnesVector - Returns a vector of specified type with all bits set.
4236 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4237 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4238 /// Then bitcast to their original type, ensuring they get CSE'd.
4239 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4240                              SDLoc dl) {
4241   assert(VT.isVector() && "Expected a vector type");
4242
4243   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4244   SDValue Vec;
4245   if (VT.is256BitVector()) {
4246     if (HasInt256) { // AVX2
4247       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4248       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4249     } else { // AVX
4250       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4251       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4252     }
4253   } else if (VT.is128BitVector()) {
4254     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4255   } else
4256     llvm_unreachable("Unexpected vector type");
4257
4258   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4259 }
4260
4261 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4262 /// operation of specified width.
4263 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4264                        SDValue V2) {
4265   unsigned NumElems = VT.getVectorNumElements();
4266   SmallVector<int, 8> Mask;
4267   Mask.push_back(NumElems);
4268   for (unsigned i = 1; i != NumElems; ++i)
4269     Mask.push_back(i);
4270   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4271 }
4272
4273 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4274 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4275                           SDValue V2) {
4276   unsigned NumElems = VT.getVectorNumElements();
4277   SmallVector<int, 8> Mask;
4278   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4279     Mask.push_back(i);
4280     Mask.push_back(i + NumElems);
4281   }
4282   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4283 }
4284
4285 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4286 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4287                           SDValue V2) {
4288   unsigned NumElems = VT.getVectorNumElements();
4289   SmallVector<int, 8> Mask;
4290   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4291     Mask.push_back(i + Half);
4292     Mask.push_back(i + NumElems + Half);
4293   }
4294   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4295 }
4296
4297 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4298 /// vector of zero or undef vector.  This produces a shuffle where the low
4299 /// element of V2 is swizzled into the zero/undef vector, landing at element
4300 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4301 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4302                                            bool IsZero,
4303                                            const X86Subtarget *Subtarget,
4304                                            SelectionDAG &DAG) {
4305   MVT VT = V2.getSimpleValueType();
4306   SDValue V1 = IsZero
4307     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4308   unsigned NumElems = VT.getVectorNumElements();
4309   SmallVector<int, 16> MaskVec;
4310   for (unsigned i = 0; i != NumElems; ++i)
4311     // If this is the insertion idx, put the low elt of V2 here.
4312     MaskVec.push_back(i == Idx ? NumElems : i);
4313   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4314 }
4315
4316 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4317 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4318 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4319 /// shuffles which use a single input multiple times, and in those cases it will
4320 /// adjust the mask to only have indices within that single input.
4321 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4322                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4323   unsigned NumElems = VT.getVectorNumElements();
4324   SDValue ImmN;
4325
4326   IsUnary = false;
4327   bool IsFakeUnary = false;
4328   switch(N->getOpcode()) {
4329   case X86ISD::BLENDI:
4330     ImmN = N->getOperand(N->getNumOperands()-1);
4331     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4332     break;
4333   case X86ISD::SHUFP:
4334     ImmN = N->getOperand(N->getNumOperands()-1);
4335     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4336     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4337     break;
4338   case X86ISD::UNPCKH:
4339     DecodeUNPCKHMask(VT, Mask);
4340     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4341     break;
4342   case X86ISD::UNPCKL:
4343     DecodeUNPCKLMask(VT, Mask);
4344     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4345     break;
4346   case X86ISD::MOVHLPS:
4347     DecodeMOVHLPSMask(NumElems, Mask);
4348     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4349     break;
4350   case X86ISD::MOVLHPS:
4351     DecodeMOVLHPSMask(NumElems, Mask);
4352     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4353     break;
4354   case X86ISD::PALIGNR:
4355     ImmN = N->getOperand(N->getNumOperands()-1);
4356     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4357     break;
4358   case X86ISD::PSHUFD:
4359   case X86ISD::VPERMILPI:
4360     ImmN = N->getOperand(N->getNumOperands()-1);
4361     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4362     IsUnary = true;
4363     break;
4364   case X86ISD::PSHUFHW:
4365     ImmN = N->getOperand(N->getNumOperands()-1);
4366     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4367     IsUnary = true;
4368     break;
4369   case X86ISD::PSHUFLW:
4370     ImmN = N->getOperand(N->getNumOperands()-1);
4371     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4372     IsUnary = true;
4373     break;
4374   case X86ISD::PSHUFB: {
4375     IsUnary = true;
4376     SDValue MaskNode = N->getOperand(1);
4377     while (MaskNode->getOpcode() == ISD::BITCAST)
4378       MaskNode = MaskNode->getOperand(0);
4379
4380     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4381       // If we have a build-vector, then things are easy.
4382       EVT VT = MaskNode.getValueType();
4383       assert(VT.isVector() &&
4384              "Can't produce a non-vector with a build_vector!");
4385       if (!VT.isInteger())
4386         return false;
4387
4388       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4389
4390       SmallVector<uint64_t, 32> RawMask;
4391       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4392         SDValue Op = MaskNode->getOperand(i);
4393         if (Op->getOpcode() == ISD::UNDEF) {
4394           RawMask.push_back((uint64_t)SM_SentinelUndef);
4395           continue;
4396         }
4397         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4398         if (!CN)
4399           return false;
4400         APInt MaskElement = CN->getAPIntValue();
4401
4402         // We now have to decode the element which could be any integer size and
4403         // extract each byte of it.
4404         for (int j = 0; j < NumBytesPerElement; ++j) {
4405           // Note that this is x86 and so always little endian: the low byte is
4406           // the first byte of the mask.
4407           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4408           MaskElement = MaskElement.lshr(8);
4409         }
4410       }
4411       DecodePSHUFBMask(RawMask, Mask);
4412       break;
4413     }
4414
4415     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4416     if (!MaskLoad)
4417       return false;
4418
4419     SDValue Ptr = MaskLoad->getBasePtr();
4420     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4421         Ptr->getOpcode() == X86ISD::WrapperRIP)
4422       Ptr = Ptr->getOperand(0);
4423
4424     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4425     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4426       return false;
4427
4428     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4429       DecodePSHUFBMask(C, Mask);
4430       if (Mask.empty())
4431         return false;
4432       break;
4433     }
4434
4435     return false;
4436   }
4437   case X86ISD::VPERMI:
4438     ImmN = N->getOperand(N->getNumOperands()-1);
4439     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4440     IsUnary = true;
4441     break;
4442   case X86ISD::MOVSS:
4443   case X86ISD::MOVSD:
4444     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4445     break;
4446   case X86ISD::VPERM2X128:
4447     ImmN = N->getOperand(N->getNumOperands()-1);
4448     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4449     if (Mask.empty()) return false;
4450     break;
4451   case X86ISD::MOVSLDUP:
4452     DecodeMOVSLDUPMask(VT, Mask);
4453     IsUnary = true;
4454     break;
4455   case X86ISD::MOVSHDUP:
4456     DecodeMOVSHDUPMask(VT, Mask);
4457     IsUnary = true;
4458     break;
4459   case X86ISD::MOVDDUP:
4460     DecodeMOVDDUPMask(VT, Mask);
4461     IsUnary = true;
4462     break;
4463   case X86ISD::MOVLHPD:
4464   case X86ISD::MOVLPD:
4465   case X86ISD::MOVLPS:
4466     // Not yet implemented
4467     return false;
4468   default: llvm_unreachable("unknown target shuffle node");
4469   }
4470
4471   // If we have a fake unary shuffle, the shuffle mask is spread across two
4472   // inputs that are actually the same node. Re-map the mask to always point
4473   // into the first input.
4474   if (IsFakeUnary)
4475     for (int &M : Mask)
4476       if (M >= (int)Mask.size())
4477         M -= Mask.size();
4478
4479   return true;
4480 }
4481
4482 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4483 /// element of the result of the vector shuffle.
4484 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4485                                    unsigned Depth) {
4486   if (Depth == 6)
4487     return SDValue();  // Limit search depth.
4488
4489   SDValue V = SDValue(N, 0);
4490   EVT VT = V.getValueType();
4491   unsigned Opcode = V.getOpcode();
4492
4493   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4494   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4495     int Elt = SV->getMaskElt(Index);
4496
4497     if (Elt < 0)
4498       return DAG.getUNDEF(VT.getVectorElementType());
4499
4500     unsigned NumElems = VT.getVectorNumElements();
4501     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4502                                          : SV->getOperand(1);
4503     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4504   }
4505
4506   // Recurse into target specific vector shuffles to find scalars.
4507   if (isTargetShuffle(Opcode)) {
4508     MVT ShufVT = V.getSimpleValueType();
4509     unsigned NumElems = ShufVT.getVectorNumElements();
4510     SmallVector<int, 16> ShuffleMask;
4511     bool IsUnary;
4512
4513     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4514       return SDValue();
4515
4516     int Elt = ShuffleMask[Index];
4517     if (Elt < 0)
4518       return DAG.getUNDEF(ShufVT.getVectorElementType());
4519
4520     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4521                                          : N->getOperand(1);
4522     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4523                                Depth+1);
4524   }
4525
4526   // Actual nodes that may contain scalar elements
4527   if (Opcode == ISD::BITCAST) {
4528     V = V.getOperand(0);
4529     EVT SrcVT = V.getValueType();
4530     unsigned NumElems = VT.getVectorNumElements();
4531
4532     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4533       return SDValue();
4534   }
4535
4536   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4537     return (Index == 0) ? V.getOperand(0)
4538                         : DAG.getUNDEF(VT.getVectorElementType());
4539
4540   if (V.getOpcode() == ISD::BUILD_VECTOR)
4541     return V.getOperand(Index);
4542
4543   return SDValue();
4544 }
4545
4546 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4547 ///
4548 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4549                                        unsigned NumNonZero, unsigned NumZero,
4550                                        SelectionDAG &DAG,
4551                                        const X86Subtarget* Subtarget,
4552                                        const TargetLowering &TLI) {
4553   if (NumNonZero > 8)
4554     return SDValue();
4555
4556   SDLoc dl(Op);
4557   SDValue V;
4558   bool First = true;
4559
4560   // SSE4.1 - use PINSRB to insert each byte directly.
4561   if (Subtarget->hasSSE41()) {
4562     for (unsigned i = 0; i < 16; ++i) {
4563       bool isNonZero = (NonZeros & (1 << i)) != 0;
4564       if (isNonZero) {
4565         if (First) {
4566           if (NumZero)
4567             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4568           else
4569             V = DAG.getUNDEF(MVT::v16i8);
4570           First = false;
4571         }
4572         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4573                         MVT::v16i8, V, Op.getOperand(i),
4574                         DAG.getIntPtrConstant(i, dl));
4575       }
4576     }
4577
4578     return V;
4579   }
4580
4581   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4582   for (unsigned i = 0; i < 16; ++i) {
4583     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4584     if (ThisIsNonZero && First) {
4585       if (NumZero)
4586         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4587       else
4588         V = DAG.getUNDEF(MVT::v8i16);
4589       First = false;
4590     }
4591
4592     if ((i & 1) != 0) {
4593       SDValue ThisElt, LastElt;
4594       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4595       if (LastIsNonZero) {
4596         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4597                               MVT::i16, Op.getOperand(i-1));
4598       }
4599       if (ThisIsNonZero) {
4600         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4601         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4602                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4603         if (LastIsNonZero)
4604           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4605       } else
4606         ThisElt = LastElt;
4607
4608       if (ThisElt.getNode())
4609         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4610                         DAG.getIntPtrConstant(i/2, dl));
4611     }
4612   }
4613
4614   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4615 }
4616
4617 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4618 ///
4619 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4620                                      unsigned NumNonZero, unsigned NumZero,
4621                                      SelectionDAG &DAG,
4622                                      const X86Subtarget* Subtarget,
4623                                      const TargetLowering &TLI) {
4624   if (NumNonZero > 4)
4625     return SDValue();
4626
4627   SDLoc dl(Op);
4628   SDValue V;
4629   bool First = true;
4630   for (unsigned i = 0; i < 8; ++i) {
4631     bool isNonZero = (NonZeros & (1 << i)) != 0;
4632     if (isNonZero) {
4633       if (First) {
4634         if (NumZero)
4635           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4636         else
4637           V = DAG.getUNDEF(MVT::v8i16);
4638         First = false;
4639       }
4640       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4641                       MVT::v8i16, V, Op.getOperand(i),
4642                       DAG.getIntPtrConstant(i, dl));
4643     }
4644   }
4645
4646   return V;
4647 }
4648
4649 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4650 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4651                                      const X86Subtarget *Subtarget,
4652                                      const TargetLowering &TLI) {
4653   // Find all zeroable elements.
4654   std::bitset<4> Zeroable;
4655   for (int i=0; i < 4; ++i) {
4656     SDValue Elt = Op->getOperand(i);
4657     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4658   }
4659   assert(Zeroable.size() - Zeroable.count() > 1 &&
4660          "We expect at least two non-zero elements!");
4661
4662   // We only know how to deal with build_vector nodes where elements are either
4663   // zeroable or extract_vector_elt with constant index.
4664   SDValue FirstNonZero;
4665   unsigned FirstNonZeroIdx;
4666   for (unsigned i=0; i < 4; ++i) {
4667     if (Zeroable[i])
4668       continue;
4669     SDValue Elt = Op->getOperand(i);
4670     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4671         !isa<ConstantSDNode>(Elt.getOperand(1)))
4672       return SDValue();
4673     // Make sure that this node is extracting from a 128-bit vector.
4674     MVT VT = Elt.getOperand(0).getSimpleValueType();
4675     if (!VT.is128BitVector())
4676       return SDValue();
4677     if (!FirstNonZero.getNode()) {
4678       FirstNonZero = Elt;
4679       FirstNonZeroIdx = i;
4680     }
4681   }
4682
4683   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4684   SDValue V1 = FirstNonZero.getOperand(0);
4685   MVT VT = V1.getSimpleValueType();
4686
4687   // See if this build_vector can be lowered as a blend with zero.
4688   SDValue Elt;
4689   unsigned EltMaskIdx, EltIdx;
4690   int Mask[4];
4691   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4692     if (Zeroable[EltIdx]) {
4693       // The zero vector will be on the right hand side.
4694       Mask[EltIdx] = EltIdx+4;
4695       continue;
4696     }
4697
4698     Elt = Op->getOperand(EltIdx);
4699     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4700     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4701     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4702       break;
4703     Mask[EltIdx] = EltIdx;
4704   }
4705
4706   if (EltIdx == 4) {
4707     // Let the shuffle legalizer deal with blend operations.
4708     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4709     if (V1.getSimpleValueType() != VT)
4710       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4711     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4712   }
4713
4714   // See if we can lower this build_vector to a INSERTPS.
4715   if (!Subtarget->hasSSE41())
4716     return SDValue();
4717
4718   SDValue V2 = Elt.getOperand(0);
4719   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4720     V1 = SDValue();
4721
4722   bool CanFold = true;
4723   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4724     if (Zeroable[i])
4725       continue;
4726
4727     SDValue Current = Op->getOperand(i);
4728     SDValue SrcVector = Current->getOperand(0);
4729     if (!V1.getNode())
4730       V1 = SrcVector;
4731     CanFold = SrcVector == V1 &&
4732       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4733   }
4734
4735   if (!CanFold)
4736     return SDValue();
4737
4738   assert(V1.getNode() && "Expected at least two non-zero elements!");
4739   if (V1.getSimpleValueType() != MVT::v4f32)
4740     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4741   if (V2.getSimpleValueType() != MVT::v4f32)
4742     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4743
4744   // Ok, we can emit an INSERTPS instruction.
4745   unsigned ZMask = Zeroable.to_ulong();
4746
4747   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4748   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4749   SDLoc DL(Op);
4750   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4751                                DAG.getIntPtrConstant(InsertPSMask, DL));
4752   return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4753 }
4754
4755 /// Return a vector logical shift node.
4756 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4757                          unsigned NumBits, SelectionDAG &DAG,
4758                          const TargetLowering &TLI, SDLoc dl) {
4759   assert(VT.is128BitVector() && "Unknown type for VShift");
4760   MVT ShVT = MVT::v2i64;
4761   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4762   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4763   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4764   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4765   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4766   return DAG.getNode(ISD::BITCAST, dl, VT,
4767                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4768 }
4769
4770 static SDValue
4771 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4772
4773   // Check if the scalar load can be widened into a vector load. And if
4774   // the address is "base + cst" see if the cst can be "absorbed" into
4775   // the shuffle mask.
4776   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4777     SDValue Ptr = LD->getBasePtr();
4778     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4779       return SDValue();
4780     EVT PVT = LD->getValueType(0);
4781     if (PVT != MVT::i32 && PVT != MVT::f32)
4782       return SDValue();
4783
4784     int FI = -1;
4785     int64_t Offset = 0;
4786     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4787       FI = FINode->getIndex();
4788       Offset = 0;
4789     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4790                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4791       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4792       Offset = Ptr.getConstantOperandVal(1);
4793       Ptr = Ptr.getOperand(0);
4794     } else {
4795       return SDValue();
4796     }
4797
4798     // FIXME: 256-bit vector instructions don't require a strict alignment,
4799     // improve this code to support it better.
4800     unsigned RequiredAlign = VT.getSizeInBits()/8;
4801     SDValue Chain = LD->getChain();
4802     // Make sure the stack object alignment is at least 16 or 32.
4803     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4804     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4805       if (MFI->isFixedObjectIndex(FI)) {
4806         // Can't change the alignment. FIXME: It's possible to compute
4807         // the exact stack offset and reference FI + adjust offset instead.
4808         // If someone *really* cares about this. That's the way to implement it.
4809         return SDValue();
4810       } else {
4811         MFI->setObjectAlignment(FI, RequiredAlign);
4812       }
4813     }
4814
4815     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4816     // Ptr + (Offset & ~15).
4817     if (Offset < 0)
4818       return SDValue();
4819     if ((Offset % RequiredAlign) & 3)
4820       return SDValue();
4821     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4822     if (StartOffset) {
4823       SDLoc DL(Ptr);
4824       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4825                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4826     }
4827
4828     int EltNo = (Offset - StartOffset) >> 2;
4829     unsigned NumElems = VT.getVectorNumElements();
4830
4831     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4832     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4833                              LD->getPointerInfo().getWithOffset(StartOffset),
4834                              false, false, false, 0);
4835
4836     SmallVector<int, 8> Mask(NumElems, EltNo);
4837
4838     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4839   }
4840
4841   return SDValue();
4842 }
4843
4844 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4845 /// elements can be replaced by a single large load which has the same value as
4846 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4847 ///
4848 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4849 ///
4850 /// FIXME: we'd also like to handle the case where the last elements are zero
4851 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4852 /// There's even a handy isZeroNode for that purpose.
4853 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4854                                         SDLoc &DL, SelectionDAG &DAG,
4855                                         bool isAfterLegalize) {
4856   unsigned NumElems = Elts.size();
4857
4858   LoadSDNode *LDBase = nullptr;
4859   unsigned LastLoadedElt = -1U;
4860
4861   // For each element in the initializer, see if we've found a load or an undef.
4862   // If we don't find an initial load element, or later load elements are
4863   // non-consecutive, bail out.
4864   for (unsigned i = 0; i < NumElems; ++i) {
4865     SDValue Elt = Elts[i];
4866     // Look through a bitcast.
4867     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4868       Elt = Elt.getOperand(0);
4869     if (!Elt.getNode() ||
4870         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4871       return SDValue();
4872     if (!LDBase) {
4873       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4874         return SDValue();
4875       LDBase = cast<LoadSDNode>(Elt.getNode());
4876       LastLoadedElt = i;
4877       continue;
4878     }
4879     if (Elt.getOpcode() == ISD::UNDEF)
4880       continue;
4881
4882     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4883     EVT LdVT = Elt.getValueType();
4884     // Each loaded element must be the correct fractional portion of the
4885     // requested vector load.
4886     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4887       return SDValue();
4888     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4889       return SDValue();
4890     LastLoadedElt = i;
4891   }
4892
4893   // If we have found an entire vector of loads and undefs, then return a large
4894   // load of the entire vector width starting at the base pointer.  If we found
4895   // consecutive loads for the low half, generate a vzext_load node.
4896   if (LastLoadedElt == NumElems - 1) {
4897     assert(LDBase && "Did not find base load for merging consecutive loads");
4898     EVT EltVT = LDBase->getValueType(0);
4899     // Ensure that the input vector size for the merged loads matches the
4900     // cumulative size of the input elements.
4901     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4902       return SDValue();
4903
4904     if (isAfterLegalize &&
4905         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4906       return SDValue();
4907
4908     SDValue NewLd = SDValue();
4909
4910     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4911                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4912                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4913                         LDBase->getAlignment());
4914
4915     if (LDBase->hasAnyUseOfValue(1)) {
4916       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4917                                      SDValue(LDBase, 1),
4918                                      SDValue(NewLd.getNode(), 1));
4919       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4920       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4921                              SDValue(NewLd.getNode(), 1));
4922     }
4923
4924     return NewLd;
4925   }
4926
4927   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4928   //of a v4i32 / v4f32. It's probably worth generalizing.
4929   EVT EltVT = VT.getVectorElementType();
4930   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4931       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4932     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4933     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4934     SDValue ResNode =
4935         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4936                                 LDBase->getPointerInfo(),
4937                                 LDBase->getAlignment(),
4938                                 false/*isVolatile*/, true/*ReadMem*/,
4939                                 false/*WriteMem*/);
4940
4941     // Make sure the newly-created LOAD is in the same position as LDBase in
4942     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4943     // update uses of LDBase's output chain to use the TokenFactor.
4944     if (LDBase->hasAnyUseOfValue(1)) {
4945       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4946                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4947       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4948       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4949                              SDValue(ResNode.getNode(), 1));
4950     }
4951
4952     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4953   }
4954   return SDValue();
4955 }
4956
4957 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4958 /// to generate a splat value for the following cases:
4959 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4960 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4961 /// a scalar load, or a constant.
4962 /// The VBROADCAST node is returned when a pattern is found,
4963 /// or SDValue() otherwise.
4964 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4965                                     SelectionDAG &DAG) {
4966   // VBROADCAST requires AVX.
4967   // TODO: Splats could be generated for non-AVX CPUs using SSE
4968   // instructions, but there's less potential gain for only 128-bit vectors.
4969   if (!Subtarget->hasAVX())
4970     return SDValue();
4971
4972   MVT VT = Op.getSimpleValueType();
4973   SDLoc dl(Op);
4974
4975   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4976          "Unsupported vector type for broadcast.");
4977
4978   SDValue Ld;
4979   bool ConstSplatVal;
4980
4981   switch (Op.getOpcode()) {
4982     default:
4983       // Unknown pattern found.
4984       return SDValue();
4985
4986     case ISD::BUILD_VECTOR: {
4987       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4988       BitVector UndefElements;
4989       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4990
4991       // We need a splat of a single value to use broadcast, and it doesn't
4992       // make any sense if the value is only in one element of the vector.
4993       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4994         return SDValue();
4995
4996       Ld = Splat;
4997       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4998                        Ld.getOpcode() == ISD::ConstantFP);
4999
5000       // Make sure that all of the users of a non-constant load are from the
5001       // BUILD_VECTOR node.
5002       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5003         return SDValue();
5004       break;
5005     }
5006
5007     case ISD::VECTOR_SHUFFLE: {
5008       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5009
5010       // Shuffles must have a splat mask where the first element is
5011       // broadcasted.
5012       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5013         return SDValue();
5014
5015       SDValue Sc = Op.getOperand(0);
5016       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5017           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5018
5019         if (!Subtarget->hasInt256())
5020           return SDValue();
5021
5022         // Use the register form of the broadcast instruction available on AVX2.
5023         if (VT.getSizeInBits() >= 256)
5024           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5025         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5026       }
5027
5028       Ld = Sc.getOperand(0);
5029       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5030                        Ld.getOpcode() == ISD::ConstantFP);
5031
5032       // The scalar_to_vector node and the suspected
5033       // load node must have exactly one user.
5034       // Constants may have multiple users.
5035
5036       // AVX-512 has register version of the broadcast
5037       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5038         Ld.getValueType().getSizeInBits() >= 32;
5039       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5040           !hasRegVer))
5041         return SDValue();
5042       break;
5043     }
5044   }
5045
5046   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5047   bool IsGE256 = (VT.getSizeInBits() >= 256);
5048
5049   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5050   // instruction to save 8 or more bytes of constant pool data.
5051   // TODO: If multiple splats are generated to load the same constant,
5052   // it may be detrimental to overall size. There needs to be a way to detect
5053   // that condition to know if this is truly a size win.
5054   const Function *F = DAG.getMachineFunction().getFunction();
5055   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5056
5057   // Handle broadcasting a single constant scalar from the constant pool
5058   // into a vector.
5059   // On Sandybridge (no AVX2), it is still better to load a constant vector
5060   // from the constant pool and not to broadcast it from a scalar.
5061   // But override that restriction when optimizing for size.
5062   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5063   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5064     EVT CVT = Ld.getValueType();
5065     assert(!CVT.isVector() && "Must not broadcast a vector type");
5066
5067     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5068     // For size optimization, also splat v2f64 and v2i64, and for size opt
5069     // with AVX2, also splat i8 and i16.
5070     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5071     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5072         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5073       const Constant *C = nullptr;
5074       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5075         C = CI->getConstantIntValue();
5076       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5077         C = CF->getConstantFPValue();
5078
5079       assert(C && "Invalid constant type");
5080
5081       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5082       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5083       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5084       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5085                        MachinePointerInfo::getConstantPool(),
5086                        false, false, false, Alignment);
5087
5088       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5089     }
5090   }
5091
5092   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5093
5094   // Handle AVX2 in-register broadcasts.
5095   if (!IsLoad && Subtarget->hasInt256() &&
5096       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5097     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5098
5099   // The scalar source must be a normal load.
5100   if (!IsLoad)
5101     return SDValue();
5102
5103   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5104       (Subtarget->hasVLX() && ScalarSize == 64))
5105     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5106
5107   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5108   // double since there is no vbroadcastsd xmm
5109   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5110     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5111       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5112   }
5113
5114   // Unsupported broadcast.
5115   return SDValue();
5116 }
5117
5118 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5119 /// underlying vector and index.
5120 ///
5121 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5122 /// index.
5123 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5124                                          SDValue ExtIdx) {
5125   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5126   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5127     return Idx;
5128
5129   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5130   // lowered this:
5131   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5132   // to:
5133   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5134   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5135   //                           undef)
5136   //                       Constant<0>)
5137   // In this case the vector is the extract_subvector expression and the index
5138   // is 2, as specified by the shuffle.
5139   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5140   SDValue ShuffleVec = SVOp->getOperand(0);
5141   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5142   assert(ShuffleVecVT.getVectorElementType() ==
5143          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5144
5145   int ShuffleIdx = SVOp->getMaskElt(Idx);
5146   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5147     ExtractedFromVec = ShuffleVec;
5148     return ShuffleIdx;
5149   }
5150   return Idx;
5151 }
5152
5153 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5154   MVT VT = Op.getSimpleValueType();
5155
5156   // Skip if insert_vec_elt is not supported.
5157   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5158   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5159     return SDValue();
5160
5161   SDLoc DL(Op);
5162   unsigned NumElems = Op.getNumOperands();
5163
5164   SDValue VecIn1;
5165   SDValue VecIn2;
5166   SmallVector<unsigned, 4> InsertIndices;
5167   SmallVector<int, 8> Mask(NumElems, -1);
5168
5169   for (unsigned i = 0; i != NumElems; ++i) {
5170     unsigned Opc = Op.getOperand(i).getOpcode();
5171
5172     if (Opc == ISD::UNDEF)
5173       continue;
5174
5175     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5176       // Quit if more than 1 elements need inserting.
5177       if (InsertIndices.size() > 1)
5178         return SDValue();
5179
5180       InsertIndices.push_back(i);
5181       continue;
5182     }
5183
5184     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5185     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5186     // Quit if non-constant index.
5187     if (!isa<ConstantSDNode>(ExtIdx))
5188       return SDValue();
5189     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5190
5191     // Quit if extracted from vector of different type.
5192     if (ExtractedFromVec.getValueType() != VT)
5193       return SDValue();
5194
5195     if (!VecIn1.getNode())
5196       VecIn1 = ExtractedFromVec;
5197     else if (VecIn1 != ExtractedFromVec) {
5198       if (!VecIn2.getNode())
5199         VecIn2 = ExtractedFromVec;
5200       else if (VecIn2 != ExtractedFromVec)
5201         // Quit if more than 2 vectors to shuffle
5202         return SDValue();
5203     }
5204
5205     if (ExtractedFromVec == VecIn1)
5206       Mask[i] = Idx;
5207     else if (ExtractedFromVec == VecIn2)
5208       Mask[i] = Idx + NumElems;
5209   }
5210
5211   if (!VecIn1.getNode())
5212     return SDValue();
5213
5214   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5215   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5216   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5217     unsigned Idx = InsertIndices[i];
5218     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5219                      DAG.getIntPtrConstant(Idx, DL));
5220   }
5221
5222   return NV;
5223 }
5224
5225 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5226   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5227          Op.getScalarValueSizeInBits() == 1 &&
5228          "Can not convert non-constant vector");
5229   uint64_t Immediate = 0;
5230   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5231     SDValue In = Op.getOperand(idx);
5232     if (In.getOpcode() != ISD::UNDEF)
5233       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5234   }
5235   SDLoc dl(Op);
5236   MVT VT =
5237    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5238   return DAG.getConstant(Immediate, dl, VT);
5239 }
5240 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5241 SDValue
5242 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5243
5244   MVT VT = Op.getSimpleValueType();
5245   assert((VT.getVectorElementType() == MVT::i1) &&
5246          "Unexpected type in LowerBUILD_VECTORvXi1!");
5247
5248   SDLoc dl(Op);
5249   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5250     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5251     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5252     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5253   }
5254
5255   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5256     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5257     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5258     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5259   }
5260
5261   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5262     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5263     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5264       return DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5265     SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5266     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5267                         DAG.getIntPtrConstant(0, dl));
5268   }
5269
5270   // Vector has one or more non-const elements
5271   uint64_t Immediate = 0;
5272   SmallVector<unsigned, 16> NonConstIdx;
5273   bool IsSplat = true;
5274   bool HasConstElts = false;
5275   int SplatIdx = -1;
5276   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5277     SDValue In = Op.getOperand(idx);
5278     if (In.getOpcode() == ISD::UNDEF)
5279       continue;
5280     if (!isa<ConstantSDNode>(In)) 
5281       NonConstIdx.push_back(idx);
5282     else {
5283       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5284       HasConstElts = true;
5285     }
5286     if (SplatIdx == -1)
5287       SplatIdx = idx;
5288     else if (In != Op.getOperand(SplatIdx))
5289       IsSplat = false;
5290   }
5291
5292   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5293   if (IsSplat)
5294     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5295                        DAG.getConstant(1, dl, VT),
5296                        DAG.getConstant(0, dl, VT));
5297
5298   // insert elements one by one
5299   SDValue DstVec;
5300   SDValue Imm;
5301   if (Immediate) {
5302     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5303     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5304   }
5305   else if (HasConstElts)
5306     Imm = DAG.getConstant(0, dl, VT);
5307   else 
5308     Imm = DAG.getUNDEF(VT);
5309   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5310     DstVec = DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5311   else {
5312     SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5313     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5314                          DAG.getIntPtrConstant(0, dl));
5315   }
5316
5317   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5318     unsigned InsertIdx = NonConstIdx[i];
5319     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5320                          Op.getOperand(InsertIdx),
5321                          DAG.getIntPtrConstant(InsertIdx, dl));
5322   }
5323   return DstVec;
5324 }
5325
5326 /// \brief Return true if \p N implements a horizontal binop and return the
5327 /// operands for the horizontal binop into V0 and V1.
5328 ///
5329 /// This is a helper function of LowerToHorizontalOp().
5330 /// This function checks that the build_vector \p N in input implements a
5331 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5332 /// operation to match.
5333 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5334 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5335 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5336 /// arithmetic sub.
5337 ///
5338 /// This function only analyzes elements of \p N whose indices are
5339 /// in range [BaseIdx, LastIdx).
5340 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5341                               SelectionDAG &DAG,
5342                               unsigned BaseIdx, unsigned LastIdx,
5343                               SDValue &V0, SDValue &V1) {
5344   EVT VT = N->getValueType(0);
5345
5346   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5347   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5348          "Invalid Vector in input!");
5349
5350   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5351   bool CanFold = true;
5352   unsigned ExpectedVExtractIdx = BaseIdx;
5353   unsigned NumElts = LastIdx - BaseIdx;
5354   V0 = DAG.getUNDEF(VT);
5355   V1 = DAG.getUNDEF(VT);
5356
5357   // Check if N implements a horizontal binop.
5358   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5359     SDValue Op = N->getOperand(i + BaseIdx);
5360
5361     // Skip UNDEFs.
5362     if (Op->getOpcode() == ISD::UNDEF) {
5363       // Update the expected vector extract index.
5364       if (i * 2 == NumElts)
5365         ExpectedVExtractIdx = BaseIdx;
5366       ExpectedVExtractIdx += 2;
5367       continue;
5368     }
5369
5370     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5371
5372     if (!CanFold)
5373       break;
5374
5375     SDValue Op0 = Op.getOperand(0);
5376     SDValue Op1 = Op.getOperand(1);
5377
5378     // Try to match the following pattern:
5379     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5380     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5381         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5382         Op0.getOperand(0) == Op1.getOperand(0) &&
5383         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5384         isa<ConstantSDNode>(Op1.getOperand(1)));
5385     if (!CanFold)
5386       break;
5387
5388     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5389     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5390
5391     if (i * 2 < NumElts) {
5392       if (V0.getOpcode() == ISD::UNDEF) {
5393         V0 = Op0.getOperand(0);
5394         if (V0.getValueType() != VT)
5395           return false;
5396       }
5397     } else {
5398       if (V1.getOpcode() == ISD::UNDEF) {
5399         V1 = Op0.getOperand(0);
5400         if (V1.getValueType() != VT)
5401           return false;
5402       }
5403       if (i * 2 == NumElts)
5404         ExpectedVExtractIdx = BaseIdx;
5405     }
5406
5407     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5408     if (I0 == ExpectedVExtractIdx)
5409       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5410     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5411       // Try to match the following dag sequence:
5412       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5413       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5414     } else
5415       CanFold = false;
5416
5417     ExpectedVExtractIdx += 2;
5418   }
5419
5420   return CanFold;
5421 }
5422
5423 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5424 /// a concat_vector.
5425 ///
5426 /// This is a helper function of LowerToHorizontalOp().
5427 /// This function expects two 256-bit vectors called V0 and V1.
5428 /// At first, each vector is split into two separate 128-bit vectors.
5429 /// Then, the resulting 128-bit vectors are used to implement two
5430 /// horizontal binary operations.
5431 ///
5432 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5433 ///
5434 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5435 /// the two new horizontal binop.
5436 /// When Mode is set, the first horizontal binop dag node would take as input
5437 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5438 /// horizontal binop dag node would take as input the lower 128-bit of V1
5439 /// and the upper 128-bit of V1.
5440 ///   Example:
5441 ///     HADD V0_LO, V0_HI
5442 ///     HADD V1_LO, V1_HI
5443 ///
5444 /// Otherwise, the first horizontal binop dag node takes as input the lower
5445 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5446 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5447 ///   Example:
5448 ///     HADD V0_LO, V1_LO
5449 ///     HADD V0_HI, V1_HI
5450 ///
5451 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5452 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5453 /// the upper 128-bits of the result.
5454 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5455                                      SDLoc DL, SelectionDAG &DAG,
5456                                      unsigned X86Opcode, bool Mode,
5457                                      bool isUndefLO, bool isUndefHI) {
5458   EVT VT = V0.getValueType();
5459   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5460          "Invalid nodes in input!");
5461
5462   unsigned NumElts = VT.getVectorNumElements();
5463   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5464   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5465   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5466   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5467   EVT NewVT = V0_LO.getValueType();
5468
5469   SDValue LO = DAG.getUNDEF(NewVT);
5470   SDValue HI = DAG.getUNDEF(NewVT);
5471
5472   if (Mode) {
5473     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5474     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5475       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5476     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5477       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5478   } else {
5479     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5480     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5481                        V1_LO->getOpcode() != ISD::UNDEF))
5482       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5483
5484     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5485                        V1_HI->getOpcode() != ISD::UNDEF))
5486       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5487   }
5488
5489   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5490 }
5491
5492 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5493 /// node.
5494 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5495                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5496   EVT VT = BV->getValueType(0);
5497   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5498       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5499     return SDValue();
5500
5501   SDLoc DL(BV);
5502   unsigned NumElts = VT.getVectorNumElements();
5503   SDValue InVec0 = DAG.getUNDEF(VT);
5504   SDValue InVec1 = DAG.getUNDEF(VT);
5505
5506   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5507           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5508
5509   // Odd-numbered elements in the input build vector are obtained from
5510   // adding two integer/float elements.
5511   // Even-numbered elements in the input build vector are obtained from
5512   // subtracting two integer/float elements.
5513   unsigned ExpectedOpcode = ISD::FSUB;
5514   unsigned NextExpectedOpcode = ISD::FADD;
5515   bool AddFound = false;
5516   bool SubFound = false;
5517
5518   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5519     SDValue Op = BV->getOperand(i);
5520
5521     // Skip 'undef' values.
5522     unsigned Opcode = Op.getOpcode();
5523     if (Opcode == ISD::UNDEF) {
5524       std::swap(ExpectedOpcode, NextExpectedOpcode);
5525       continue;
5526     }
5527
5528     // Early exit if we found an unexpected opcode.
5529     if (Opcode != ExpectedOpcode)
5530       return SDValue();
5531
5532     SDValue Op0 = Op.getOperand(0);
5533     SDValue Op1 = Op.getOperand(1);
5534
5535     // Try to match the following pattern:
5536     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5537     // Early exit if we cannot match that sequence.
5538     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5539         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5540         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5541         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5542         Op0.getOperand(1) != Op1.getOperand(1))
5543       return SDValue();
5544
5545     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5546     if (I0 != i)
5547       return SDValue();
5548
5549     // We found a valid add/sub node. Update the information accordingly.
5550     if (i & 1)
5551       AddFound = true;
5552     else
5553       SubFound = true;
5554
5555     // Update InVec0 and InVec1.
5556     if (InVec0.getOpcode() == ISD::UNDEF) {
5557       InVec0 = Op0.getOperand(0);
5558       if (InVec0.getValueType() != VT)
5559         return SDValue();
5560     }
5561     if (InVec1.getOpcode() == ISD::UNDEF) {
5562       InVec1 = Op1.getOperand(0);
5563       if (InVec1.getValueType() != VT)
5564         return SDValue();
5565     }
5566
5567     // Make sure that operands in input to each add/sub node always
5568     // come from a same pair of vectors.
5569     if (InVec0 != Op0.getOperand(0)) {
5570       if (ExpectedOpcode == ISD::FSUB)
5571         return SDValue();
5572
5573       // FADD is commutable. Try to commute the operands
5574       // and then test again.
5575       std::swap(Op0, Op1);
5576       if (InVec0 != Op0.getOperand(0))
5577         return SDValue();
5578     }
5579
5580     if (InVec1 != Op1.getOperand(0))
5581       return SDValue();
5582
5583     // Update the pair of expected opcodes.
5584     std::swap(ExpectedOpcode, NextExpectedOpcode);
5585   }
5586
5587   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5588   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5589       InVec1.getOpcode() != ISD::UNDEF)
5590     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5591
5592   return SDValue();
5593 }
5594
5595 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5596 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5597                                    const X86Subtarget *Subtarget,
5598                                    SelectionDAG &DAG) {
5599   EVT VT = BV->getValueType(0);
5600   unsigned NumElts = VT.getVectorNumElements();
5601   unsigned NumUndefsLO = 0;
5602   unsigned NumUndefsHI = 0;
5603   unsigned Half = NumElts/2;
5604
5605   // Count the number of UNDEF operands in the build_vector in input.
5606   for (unsigned i = 0, e = Half; i != e; ++i)
5607     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5608       NumUndefsLO++;
5609
5610   for (unsigned i = Half, e = NumElts; i != e; ++i)
5611     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5612       NumUndefsHI++;
5613
5614   // Early exit if this is either a build_vector of all UNDEFs or all the
5615   // operands but one are UNDEF.
5616   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5617     return SDValue();
5618
5619   SDLoc DL(BV);
5620   SDValue InVec0, InVec1;
5621   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5622     // Try to match an SSE3 float HADD/HSUB.
5623     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5624       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5625
5626     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5627       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5628   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5629     // Try to match an SSSE3 integer HADD/HSUB.
5630     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5631       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5632
5633     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5634       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5635   }
5636
5637   if (!Subtarget->hasAVX())
5638     return SDValue();
5639
5640   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5641     // Try to match an AVX horizontal add/sub of packed single/double
5642     // precision floating point values from 256-bit vectors.
5643     SDValue InVec2, InVec3;
5644     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5645         isHorizontalBinOp(BV, ISD::FADD, 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       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5651
5652     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5653         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5654         ((InVec0.getOpcode() == ISD::UNDEF ||
5655           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5656         ((InVec1.getOpcode() == ISD::UNDEF ||
5657           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5658       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5659   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5660     // Try to match an AVX2 horizontal add/sub of signed integers.
5661     SDValue InVec2, InVec3;
5662     unsigned X86Opcode;
5663     bool CanFold = true;
5664
5665     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5666         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5667         ((InVec0.getOpcode() == ISD::UNDEF ||
5668           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5669         ((InVec1.getOpcode() == ISD::UNDEF ||
5670           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5671       X86Opcode = X86ISD::HADD;
5672     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5673         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5674         ((InVec0.getOpcode() == ISD::UNDEF ||
5675           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5676         ((InVec1.getOpcode() == ISD::UNDEF ||
5677           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5678       X86Opcode = X86ISD::HSUB;
5679     else
5680       CanFold = false;
5681
5682     if (CanFold) {
5683       // Fold this build_vector into a single horizontal add/sub.
5684       // Do this only if the target has AVX2.
5685       if (Subtarget->hasAVX2())
5686         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5687
5688       // Do not try to expand this build_vector into a pair of horizontal
5689       // add/sub if we can 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 a pair of horizontal binop followed by
5694       // a concat vector.
5695       bool isUndefLO = NumUndefsLO == Half;
5696       bool isUndefHI = NumUndefsHI == Half;
5697       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5698                                    isUndefLO, isUndefHI);
5699     }
5700   }
5701
5702   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5703        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5704     unsigned X86Opcode;
5705     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5706       X86Opcode = X86ISD::HADD;
5707     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5708       X86Opcode = X86ISD::HSUB;
5709     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5710       X86Opcode = X86ISD::FHADD;
5711     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5712       X86Opcode = X86ISD::FHSUB;
5713     else
5714       return SDValue();
5715
5716     // Don't try to expand this build_vector into a pair of horizontal add/sub
5717     // if we can simply emit a pair of scalar add/sub.
5718     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5719       return SDValue();
5720
5721     // Convert this build_vector into two horizontal add/sub followed by
5722     // a concat vector.
5723     bool isUndefLO = NumUndefsLO == Half;
5724     bool isUndefHI = NumUndefsHI == Half;
5725     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5726                                  isUndefLO, isUndefHI);
5727   }
5728
5729   return SDValue();
5730 }
5731
5732 SDValue
5733 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5734   SDLoc dl(Op);
5735
5736   MVT VT = Op.getSimpleValueType();
5737   MVT ExtVT = VT.getVectorElementType();
5738   unsigned NumElems = Op.getNumOperands();
5739
5740   // Generate vectors for predicate vectors.
5741   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5742     return LowerBUILD_VECTORvXi1(Op, DAG);
5743
5744   // Vectors containing all zeros can be matched by pxor and xorps later
5745   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5746     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5747     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5748     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5749       return Op;
5750
5751     return getZeroVector(VT, Subtarget, DAG, dl);
5752   }
5753
5754   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5755   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5756   // vpcmpeqd on 256-bit vectors.
5757   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5758     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5759       return Op;
5760
5761     if (!VT.is512BitVector())
5762       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5763   }
5764
5765   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5766   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5767     return AddSub;
5768   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5769     return HorizontalOp;
5770   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5771     return Broadcast;
5772
5773   unsigned EVTBits = ExtVT.getSizeInBits();
5774
5775   unsigned NumZero  = 0;
5776   unsigned NumNonZero = 0;
5777   unsigned NonZeros = 0;
5778   bool IsAllConstants = true;
5779   SmallSet<SDValue, 8> Values;
5780   for (unsigned i = 0; i < NumElems; ++i) {
5781     SDValue Elt = Op.getOperand(i);
5782     if (Elt.getOpcode() == ISD::UNDEF)
5783       continue;
5784     Values.insert(Elt);
5785     if (Elt.getOpcode() != ISD::Constant &&
5786         Elt.getOpcode() != ISD::ConstantFP)
5787       IsAllConstants = false;
5788     if (X86::isZeroNode(Elt))
5789       NumZero++;
5790     else {
5791       NonZeros |= (1 << i);
5792       NumNonZero++;
5793     }
5794   }
5795
5796   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5797   if (NumNonZero == 0)
5798     return DAG.getUNDEF(VT);
5799
5800   // Special case for single non-zero, non-undef, element.
5801   if (NumNonZero == 1) {
5802     unsigned Idx = countTrailingZeros(NonZeros);
5803     SDValue Item = Op.getOperand(Idx);
5804
5805     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5806     // the value are obviously zero, truncate the value to i32 and do the
5807     // insertion that way.  Only do this if the value is non-constant or if the
5808     // value is a constant being inserted into element 0.  It is cheaper to do
5809     // a constant pool load than it is to do a movd + shuffle.
5810     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5811         (!IsAllConstants || Idx == 0)) {
5812       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5813         // Handle SSE only.
5814         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5815         EVT VecVT = MVT::v4i32;
5816
5817         // Truncate the value (which may itself be a constant) to i32, and
5818         // convert it to a vector with movd (S2V+shuffle to zero extend).
5819         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5820         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5821         return DAG.getNode(
5822             ISD::BITCAST, dl, VT,
5823             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5824       }
5825     }
5826
5827     // If we have a constant or non-constant insertion into the low element of
5828     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5829     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5830     // depending on what the source datatype is.
5831     if (Idx == 0) {
5832       if (NumZero == 0)
5833         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5834
5835       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5836           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5837         if (VT.is512BitVector()) {
5838           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5839           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5840                              Item, DAG.getIntPtrConstant(0, dl));
5841         }
5842         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5843                "Expected an SSE value type!");
5844         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5845         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5846         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5847       }
5848
5849       // We can't directly insert an i8 or i16 into a vector, so zero extend
5850       // it to i32 first.
5851       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5852         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5853         if (VT.is256BitVector()) {
5854           if (Subtarget->hasAVX()) {
5855             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5856             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5857           } else {
5858             // Without AVX, we need to extend to a 128-bit vector and then
5859             // insert into the 256-bit vector.
5860             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5861             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5862             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5863           }
5864         } else {
5865           assert(VT.is128BitVector() && "Expected an SSE value type!");
5866           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5867           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5868         }
5869         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5870       }
5871     }
5872
5873     // Is it a vector logical left shift?
5874     if (NumElems == 2 && Idx == 1 &&
5875         X86::isZeroNode(Op.getOperand(0)) &&
5876         !X86::isZeroNode(Op.getOperand(1))) {
5877       unsigned NumBits = VT.getSizeInBits();
5878       return getVShift(true, VT,
5879                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5880                                    VT, Op.getOperand(1)),
5881                        NumBits/2, DAG, *this, dl);
5882     }
5883
5884     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5885       return SDValue();
5886
5887     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5888     // is a non-constant being inserted into an element other than the low one,
5889     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5890     // movd/movss) to move this into the low element, then shuffle it into
5891     // place.
5892     if (EVTBits == 32) {
5893       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5894       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5895     }
5896   }
5897
5898   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5899   if (Values.size() == 1) {
5900     if (EVTBits == 32) {
5901       // Instead of a shuffle like this:
5902       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5903       // Check if it's possible to issue this instead.
5904       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5905       unsigned Idx = countTrailingZeros(NonZeros);
5906       SDValue Item = Op.getOperand(Idx);
5907       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5908         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5909     }
5910     return SDValue();
5911   }
5912
5913   // A vector full of immediates; various special cases are already
5914   // handled, so this is best done with a single constant-pool load.
5915   if (IsAllConstants)
5916     return SDValue();
5917
5918   // For AVX-length vectors, see if we can use a vector load to get all of the
5919   // elements, otherwise build the individual 128-bit pieces and use
5920   // shuffles to put them in place.
5921   if (VT.is256BitVector() || VT.is512BitVector()) {
5922     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5923
5924     // Check for a build vector of consecutive loads.
5925     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5926       return LD;
5927
5928     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5929
5930     // Build both the lower and upper subvector.
5931     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5932                                 makeArrayRef(&V[0], NumElems/2));
5933     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5934                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5935
5936     // Recreate the wider vector with the lower and upper part.
5937     if (VT.is256BitVector())
5938       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5939     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5940   }
5941
5942   // Let legalizer expand 2-wide build_vectors.
5943   if (EVTBits == 64) {
5944     if (NumNonZero == 1) {
5945       // One half is zero or undef.
5946       unsigned Idx = countTrailingZeros(NonZeros);
5947       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5948                                  Op.getOperand(Idx));
5949       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5950     }
5951     return SDValue();
5952   }
5953
5954   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5955   if (EVTBits == 8 && NumElems == 16)
5956     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5957                                         Subtarget, *this))
5958       return V;
5959
5960   if (EVTBits == 16 && NumElems == 8)
5961     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5962                                       Subtarget, *this))
5963       return V;
5964
5965   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5966   if (EVTBits == 32 && NumElems == 4)
5967     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5968       return V;
5969
5970   // If element VT is == 32 bits, turn it into a number of shuffles.
5971   SmallVector<SDValue, 8> V(NumElems);
5972   if (NumElems == 4 && NumZero > 0) {
5973     for (unsigned i = 0; i < 4; ++i) {
5974       bool isZero = !(NonZeros & (1 << i));
5975       if (isZero)
5976         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5977       else
5978         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5979     }
5980
5981     for (unsigned i = 0; i < 2; ++i) {
5982       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5983         default: break;
5984         case 0:
5985           V[i] = V[i*2];  // Must be a zero vector.
5986           break;
5987         case 1:
5988           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5989           break;
5990         case 2:
5991           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5992           break;
5993         case 3:
5994           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5995           break;
5996       }
5997     }
5998
5999     bool Reverse1 = (NonZeros & 0x3) == 2;
6000     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6001     int MaskVec[] = {
6002       Reverse1 ? 1 : 0,
6003       Reverse1 ? 0 : 1,
6004       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6005       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6006     };
6007     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6008   }
6009
6010   if (Values.size() > 1 && VT.is128BitVector()) {
6011     // Check for a build vector of consecutive loads.
6012     for (unsigned i = 0; i < NumElems; ++i)
6013       V[i] = Op.getOperand(i);
6014
6015     // Check for elements which are consecutive loads.
6016     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6017       return LD;
6018
6019     // Check for a build vector from mostly shuffle plus few inserting.
6020     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6021       return Sh;
6022
6023     // For SSE 4.1, use insertps to put the high elements into the low element.
6024     if (Subtarget->hasSSE41()) {
6025       SDValue Result;
6026       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6027         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6028       else
6029         Result = DAG.getUNDEF(VT);
6030
6031       for (unsigned i = 1; i < NumElems; ++i) {
6032         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6033         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6034                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6035       }
6036       return Result;
6037     }
6038
6039     // Otherwise, expand into a number of unpckl*, start by extending each of
6040     // our (non-undef) elements to the full vector width with the element in the
6041     // bottom slot of the vector (which generates no code for SSE).
6042     for (unsigned i = 0; i < NumElems; ++i) {
6043       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6044         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6045       else
6046         V[i] = DAG.getUNDEF(VT);
6047     }
6048
6049     // Next, we iteratively mix elements, e.g. for v4f32:
6050     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6051     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6052     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6053     unsigned EltStride = NumElems >> 1;
6054     while (EltStride != 0) {
6055       for (unsigned i = 0; i < EltStride; ++i) {
6056         // If V[i+EltStride] is undef and this is the first round of mixing,
6057         // then it is safe to just drop this shuffle: V[i] is already in the
6058         // right place, the one element (since it's the first round) being
6059         // inserted as undef can be dropped.  This isn't safe for successive
6060         // rounds because they will permute elements within both vectors.
6061         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6062             EltStride == NumElems/2)
6063           continue;
6064
6065         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6066       }
6067       EltStride >>= 1;
6068     }
6069     return V[0];
6070   }
6071   return SDValue();
6072 }
6073
6074 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6075 // to create 256-bit vectors from two other 128-bit ones.
6076 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6077   SDLoc dl(Op);
6078   MVT ResVT = Op.getSimpleValueType();
6079
6080   assert((ResVT.is256BitVector() ||
6081           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6082
6083   SDValue V1 = Op.getOperand(0);
6084   SDValue V2 = Op.getOperand(1);
6085   unsigned NumElems = ResVT.getVectorNumElements();
6086   if (ResVT.is256BitVector())
6087     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6088
6089   if (Op.getNumOperands() == 4) {
6090     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6091                                 ResVT.getVectorNumElements()/2);
6092     SDValue V3 = Op.getOperand(2);
6093     SDValue V4 = Op.getOperand(3);
6094     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6095       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6096   }
6097   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6098 }
6099
6100 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6101                                        const X86Subtarget *Subtarget,
6102                                        SelectionDAG & DAG) {
6103   SDLoc dl(Op);
6104   MVT ResVT = Op.getSimpleValueType();
6105   unsigned NumOfOperands = Op.getNumOperands();
6106
6107   assert(isPowerOf2_32(NumOfOperands) &&
6108          "Unexpected number of operands in CONCAT_VECTORS");
6109
6110   if (NumOfOperands > 2) {
6111     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6112                                   ResVT.getVectorNumElements()/2);
6113     SmallVector<SDValue, 2> Ops;
6114     for (unsigned i = 0; i < NumOfOperands/2; i++)
6115       Ops.push_back(Op.getOperand(i));
6116     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6117     Ops.clear();
6118     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6119       Ops.push_back(Op.getOperand(i));
6120     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6121     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6122   }
6123
6124   SDValue V1 = Op.getOperand(0);
6125   SDValue V2 = Op.getOperand(1);
6126   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6127   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6128
6129   if (IsZeroV1 && IsZeroV2)
6130     return getZeroVector(ResVT, Subtarget, DAG, dl);
6131
6132   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6133   SDValue Undef = DAG.getUNDEF(ResVT);
6134   unsigned NumElems = ResVT.getVectorNumElements();
6135   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6136
6137   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6138   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6139   if (IsZeroV1)
6140     return V2;
6141
6142   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6143   // Zero the upper bits of V1
6144   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6145   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6146   if (IsZeroV2)
6147     return V1;
6148   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6149 }
6150
6151 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6152                                    const X86Subtarget *Subtarget,
6153                                    SelectionDAG &DAG) {
6154   MVT VT = Op.getSimpleValueType();
6155   if (VT.getVectorElementType() == MVT::i1)
6156     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6157
6158   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6159          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6160           Op.getNumOperands() == 4)));
6161
6162   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6163   // from two other 128-bit ones.
6164
6165   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6166   return LowerAVXCONCAT_VECTORS(Op, DAG);
6167 }
6168
6169
6170 //===----------------------------------------------------------------------===//
6171 // Vector shuffle lowering
6172 //
6173 // This is an experimental code path for lowering vector shuffles on x86. It is
6174 // designed to handle arbitrary vector shuffles and blends, gracefully
6175 // degrading performance as necessary. It works hard to recognize idiomatic
6176 // shuffles and lower them to optimal instruction patterns without leaving
6177 // a framework that allows reasonably efficient handling of all vector shuffle
6178 // patterns.
6179 //===----------------------------------------------------------------------===//
6180
6181 /// \brief Tiny helper function to identify a no-op mask.
6182 ///
6183 /// This is a somewhat boring predicate function. It checks whether the mask
6184 /// array input, which is assumed to be a single-input shuffle mask of the kind
6185 /// used by the X86 shuffle instructions (not a fully general
6186 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6187 /// in-place shuffle are 'no-op's.
6188 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6189   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6190     if (Mask[i] != -1 && Mask[i] != i)
6191       return false;
6192   return true;
6193 }
6194
6195 /// \brief Helper function to classify a mask as a single-input mask.
6196 ///
6197 /// This isn't a generic single-input test because in the vector shuffle
6198 /// lowering we canonicalize single inputs to be the first input operand. This
6199 /// means we can more quickly test for a single input by only checking whether
6200 /// an input from the second operand exists. We also assume that the size of
6201 /// mask corresponds to the size of the input vectors which isn't true in the
6202 /// fully general case.
6203 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6204   for (int M : Mask)
6205     if (M >= (int)Mask.size())
6206       return false;
6207   return true;
6208 }
6209
6210 /// \brief Test whether there are elements crossing 128-bit lanes in this
6211 /// shuffle mask.
6212 ///
6213 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6214 /// and we routinely test for these.
6215 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6216   int LaneSize = 128 / VT.getScalarSizeInBits();
6217   int Size = Mask.size();
6218   for (int i = 0; i < Size; ++i)
6219     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6220       return true;
6221   return false;
6222 }
6223
6224 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6225 ///
6226 /// This checks a shuffle mask to see if it is performing the same
6227 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6228 /// that it is also not lane-crossing. It may however involve a blend from the
6229 /// same lane of a second vector.
6230 ///
6231 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6232 /// non-trivial to compute in the face of undef lanes. The representation is
6233 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6234 /// entries from both V1 and V2 inputs to the wider mask.
6235 static bool
6236 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6237                                 SmallVectorImpl<int> &RepeatedMask) {
6238   int LaneSize = 128 / VT.getScalarSizeInBits();
6239   RepeatedMask.resize(LaneSize, -1);
6240   int Size = Mask.size();
6241   for (int i = 0; i < Size; ++i) {
6242     if (Mask[i] < 0)
6243       continue;
6244     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6245       // This entry crosses lanes, so there is no way to model this shuffle.
6246       return false;
6247
6248     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6249     if (RepeatedMask[i % LaneSize] == -1)
6250       // This is the first non-undef entry in this slot of a 128-bit lane.
6251       RepeatedMask[i % LaneSize] =
6252           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6253     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6254       // Found a mismatch with the repeated mask.
6255       return false;
6256   }
6257   return true;
6258 }
6259
6260 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6261 /// arguments.
6262 ///
6263 /// This is a fast way to test a shuffle mask against a fixed pattern:
6264 ///
6265 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6266 ///
6267 /// It returns true if the mask is exactly as wide as the argument list, and
6268 /// each element of the mask is either -1 (signifying undef) or the value given
6269 /// in the argument.
6270 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6271                                 ArrayRef<int> ExpectedMask) {
6272   if (Mask.size() != ExpectedMask.size())
6273     return false;
6274
6275   int Size = Mask.size();
6276
6277   // If the values are build vectors, we can look through them to find
6278   // equivalent inputs that make the shuffles equivalent.
6279   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6280   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6281
6282   for (int i = 0; i < Size; ++i)
6283     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6284       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6285       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6286       if (!MaskBV || !ExpectedBV ||
6287           MaskBV->getOperand(Mask[i] % Size) !=
6288               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6289         return false;
6290     }
6291
6292   return true;
6293 }
6294
6295 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6296 ///
6297 /// This helper function produces an 8-bit shuffle immediate corresponding to
6298 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6299 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6300 /// example.
6301 ///
6302 /// NB: We rely heavily on "undef" masks preserving the input lane.
6303 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6304                                           SelectionDAG &DAG) {
6305   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6306   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6307   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6308   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6309   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6310
6311   unsigned Imm = 0;
6312   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6313   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6314   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6315   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6316   return DAG.getConstant(Imm, DL, MVT::i8);
6317 }
6318
6319 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6320 ///
6321 /// This is used as a fallback approach when first class blend instructions are
6322 /// unavailable. Currently it is only suitable for integer vectors, but could
6323 /// be generalized for floating point vectors if desirable.
6324 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6325                                             SDValue V2, ArrayRef<int> Mask,
6326                                             SelectionDAG &DAG) {
6327   assert(VT.isInteger() && "Only supports integer vector types!");
6328   MVT EltVT = VT.getScalarType();
6329   int NumEltBits = EltVT.getSizeInBits();
6330   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6331   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6332                                     EltVT);
6333   SmallVector<SDValue, 16> MaskOps;
6334   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6335     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6336       return SDValue(); // Shuffled input!
6337     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6338   }
6339
6340   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6341   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6342   // We have to cast V2 around.
6343   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6344   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6345                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6346                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6347                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6348   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6349 }
6350
6351 /// \brief Try to emit a blend instruction for a shuffle.
6352 ///
6353 /// This doesn't do any checks for the availability of instructions for blending
6354 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6355 /// be matched in the backend with the type given. What it does check for is
6356 /// that the shuffle mask is in fact a blend.
6357 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6358                                          SDValue V2, ArrayRef<int> Mask,
6359                                          const X86Subtarget *Subtarget,
6360                                          SelectionDAG &DAG) {
6361   unsigned BlendMask = 0;
6362   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6363     if (Mask[i] >= Size) {
6364       if (Mask[i] != i + Size)
6365         return SDValue(); // Shuffled V2 input!
6366       BlendMask |= 1u << i;
6367       continue;
6368     }
6369     if (Mask[i] >= 0 && Mask[i] != i)
6370       return SDValue(); // Shuffled V1 input!
6371   }
6372   switch (VT.SimpleTy) {
6373   case MVT::v2f64:
6374   case MVT::v4f32:
6375   case MVT::v4f64:
6376   case MVT::v8f32:
6377     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6378                        DAG.getConstant(BlendMask, DL, MVT::i8));
6379
6380   case MVT::v4i64:
6381   case MVT::v8i32:
6382     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6383     // FALLTHROUGH
6384   case MVT::v2i64:
6385   case MVT::v4i32:
6386     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6387     // that instruction.
6388     if (Subtarget->hasAVX2()) {
6389       // Scale the blend by the number of 32-bit dwords per element.
6390       int Scale =  VT.getScalarSizeInBits() / 32;
6391       BlendMask = 0;
6392       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6393         if (Mask[i] >= Size)
6394           for (int j = 0; j < Scale; ++j)
6395             BlendMask |= 1u << (i * Scale + j);
6396
6397       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6398       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6399       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6400       return DAG.getNode(ISD::BITCAST, DL, VT,
6401                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6402                                      DAG.getConstant(BlendMask, DL, MVT::i8)));
6403     }
6404     // FALLTHROUGH
6405   case MVT::v8i16: {
6406     // For integer shuffles we need to expand the mask and cast the inputs to
6407     // v8i16s prior to blending.
6408     int Scale = 8 / VT.getVectorNumElements();
6409     BlendMask = 0;
6410     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6411       if (Mask[i] >= Size)
6412         for (int j = 0; j < Scale; ++j)
6413           BlendMask |= 1u << (i * Scale + j);
6414
6415     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6416     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6417     return DAG.getNode(ISD::BITCAST, DL, VT,
6418                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6419                                    DAG.getConstant(BlendMask, DL, MVT::i8)));
6420   }
6421
6422   case MVT::v16i16: {
6423     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6424     SmallVector<int, 8> RepeatedMask;
6425     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6426       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6427       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6428       BlendMask = 0;
6429       for (int i = 0; i < 8; ++i)
6430         if (RepeatedMask[i] >= 16)
6431           BlendMask |= 1u << i;
6432       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6433                          DAG.getConstant(BlendMask, DL, MVT::i8));
6434     }
6435   }
6436     // FALLTHROUGH
6437   case MVT::v16i8:
6438   case MVT::v32i8: {
6439     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6440            "256-bit byte-blends require AVX2 support!");
6441
6442     // Scale the blend by the number of bytes per element.
6443     int Scale = VT.getScalarSizeInBits() / 8;
6444
6445     // This form of blend is always done on bytes. Compute the byte vector
6446     // type.
6447     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6448
6449     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6450     // mix of LLVM's code generator and the x86 backend. We tell the code
6451     // generator that boolean values in the elements of an x86 vector register
6452     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6453     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6454     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6455     // of the element (the remaining are ignored) and 0 in that high bit would
6456     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6457     // the LLVM model for boolean values in vector elements gets the relevant
6458     // bit set, it is set backwards and over constrained relative to x86's
6459     // actual model.
6460     SmallVector<SDValue, 32> VSELECTMask;
6461     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6462       for (int j = 0; j < Scale; ++j)
6463         VSELECTMask.push_back(
6464             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6465                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6466                                           MVT::i8));
6467
6468     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6469     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6470     return DAG.getNode(
6471         ISD::BITCAST, DL, VT,
6472         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6473                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6474                     V1, V2));
6475   }
6476
6477   default:
6478     llvm_unreachable("Not a supported integer vector type!");
6479   }
6480 }
6481
6482 /// \brief Try to lower as a blend of elements from two inputs followed by
6483 /// a single-input permutation.
6484 ///
6485 /// This matches the pattern where we can blend elements from two inputs and
6486 /// then reduce the shuffle to a single-input permutation.
6487 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6488                                                    SDValue V2,
6489                                                    ArrayRef<int> Mask,
6490                                                    SelectionDAG &DAG) {
6491   // We build up the blend mask while checking whether a blend is a viable way
6492   // to reduce the shuffle.
6493   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6494   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6495
6496   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6497     if (Mask[i] < 0)
6498       continue;
6499
6500     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6501
6502     if (BlendMask[Mask[i] % Size] == -1)
6503       BlendMask[Mask[i] % Size] = Mask[i];
6504     else if (BlendMask[Mask[i] % Size] != Mask[i])
6505       return SDValue(); // Can't blend in the needed input!
6506
6507     PermuteMask[i] = Mask[i] % Size;
6508   }
6509
6510   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6511   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6512 }
6513
6514 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6515 /// blends and permutes.
6516 ///
6517 /// This matches the extremely common pattern for handling combined
6518 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6519 /// operations. It will try to pick the best arrangement of shuffles and
6520 /// blends.
6521 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6522                                                           SDValue V1,
6523                                                           SDValue V2,
6524                                                           ArrayRef<int> Mask,
6525                                                           SelectionDAG &DAG) {
6526   // Shuffle the input elements into the desired positions in V1 and V2 and
6527   // blend them together.
6528   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6529   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6530   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6531   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6532     if (Mask[i] >= 0 && Mask[i] < Size) {
6533       V1Mask[i] = Mask[i];
6534       BlendMask[i] = i;
6535     } else if (Mask[i] >= Size) {
6536       V2Mask[i] = Mask[i] - Size;
6537       BlendMask[i] = i + Size;
6538     }
6539
6540   // Try to lower with the simpler initial blend strategy unless one of the
6541   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6542   // shuffle may be able to fold with a load or other benefit. However, when
6543   // we'll have to do 2x as many shuffles in order to achieve this, blending
6544   // first is a better strategy.
6545   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6546     if (SDValue BlendPerm =
6547             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6548       return BlendPerm;
6549
6550   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6551   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6552   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6553 }
6554
6555 /// \brief Try to lower a vector shuffle as a byte rotation.
6556 ///
6557 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6558 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6559 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6560 /// try to generically lower a vector shuffle through such an pattern. It
6561 /// does not check for the profitability of lowering either as PALIGNR or
6562 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6563 /// This matches shuffle vectors that look like:
6564 ///
6565 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6566 ///
6567 /// Essentially it concatenates V1 and V2, shifts right by some number of
6568 /// elements, and takes the low elements as the result. Note that while this is
6569 /// specified as a *right shift* because x86 is little-endian, it is a *left
6570 /// rotate* of the vector lanes.
6571 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6572                                               SDValue V2,
6573                                               ArrayRef<int> Mask,
6574                                               const X86Subtarget *Subtarget,
6575                                               SelectionDAG &DAG) {
6576   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6577
6578   int NumElts = Mask.size();
6579   int NumLanes = VT.getSizeInBits() / 128;
6580   int NumLaneElts = NumElts / NumLanes;
6581
6582   // We need to detect various ways of spelling a rotation:
6583   //   [11, 12, 13, 14, 15,  0,  1,  2]
6584   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6585   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6586   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6587   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6588   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6589   int Rotation = 0;
6590   SDValue Lo, Hi;
6591   for (int l = 0; l < NumElts; l += NumLaneElts) {
6592     for (int i = 0; i < NumLaneElts; ++i) {
6593       if (Mask[l + i] == -1)
6594         continue;
6595       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6596
6597       // Get the mod-Size index and lane correct it.
6598       int LaneIdx = (Mask[l + i] % NumElts) - l;
6599       // Make sure it was in this lane.
6600       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6601         return SDValue();
6602
6603       // Determine where a rotated vector would have started.
6604       int StartIdx = i - LaneIdx;
6605       if (StartIdx == 0)
6606         // The identity rotation isn't interesting, stop.
6607         return SDValue();
6608
6609       // If we found the tail of a vector the rotation must be the missing
6610       // front. If we found the head of a vector, it must be how much of the
6611       // head.
6612       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6613
6614       if (Rotation == 0)
6615         Rotation = CandidateRotation;
6616       else if (Rotation != CandidateRotation)
6617         // The rotations don't match, so we can't match this mask.
6618         return SDValue();
6619
6620       // Compute which value this mask is pointing at.
6621       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6622
6623       // Compute which of the two target values this index should be assigned
6624       // to. This reflects whether the high elements are remaining or the low
6625       // elements are remaining.
6626       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6627
6628       // Either set up this value if we've not encountered it before, or check
6629       // that it remains consistent.
6630       if (!TargetV)
6631         TargetV = MaskV;
6632       else if (TargetV != MaskV)
6633         // This may be a rotation, but it pulls from the inputs in some
6634         // unsupported interleaving.
6635         return SDValue();
6636     }
6637   }
6638
6639   // Check that we successfully analyzed the mask, and normalize the results.
6640   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6641   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6642   if (!Lo)
6643     Lo = Hi;
6644   else if (!Hi)
6645     Hi = Lo;
6646
6647   // The actual rotate instruction rotates bytes, so we need to scale the
6648   // rotation based on how many bytes are in the vector lane.
6649   int Scale = 16 / NumLaneElts;
6650
6651   // SSSE3 targets can use the palignr instruction.
6652   if (Subtarget->hasSSSE3()) {
6653     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6654     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6655     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6656     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6657
6658     return DAG.getNode(ISD::BITCAST, DL, VT,
6659                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6660                                    DAG.getConstant(Rotation * Scale, DL,
6661                                                    MVT::i8)));
6662   }
6663
6664   assert(VT.getSizeInBits() == 128 &&
6665          "Rotate-based lowering only supports 128-bit lowering!");
6666   assert(Mask.size() <= 16 &&
6667          "Can shuffle at most 16 bytes in a 128-bit vector!");
6668
6669   // Default SSE2 implementation
6670   int LoByteShift = 16 - Rotation * Scale;
6671   int HiByteShift = Rotation * Scale;
6672
6673   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6674   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6675   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6676
6677   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6678                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6679   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6680                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6681   return DAG.getNode(ISD::BITCAST, DL, VT,
6682                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6683 }
6684
6685 /// \brief Compute whether each element of a shuffle is zeroable.
6686 ///
6687 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6688 /// Either it is an undef element in the shuffle mask, the element of the input
6689 /// referenced is undef, or the element of the input referenced is known to be
6690 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6691 /// as many lanes with this technique as possible to simplify the remaining
6692 /// shuffle.
6693 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6694                                                      SDValue V1, SDValue V2) {
6695   SmallBitVector Zeroable(Mask.size(), false);
6696
6697   while (V1.getOpcode() == ISD::BITCAST)
6698     V1 = V1->getOperand(0);
6699   while (V2.getOpcode() == ISD::BITCAST)
6700     V2 = V2->getOperand(0);
6701
6702   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6703   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6704
6705   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6706     int M = Mask[i];
6707     // Handle the easy cases.
6708     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6709       Zeroable[i] = true;
6710       continue;
6711     }
6712
6713     // If this is an index into a build_vector node (which has the same number
6714     // of elements), dig out the input value and use it.
6715     SDValue V = M < Size ? V1 : V2;
6716     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6717       continue;
6718
6719     SDValue Input = V.getOperand(M % Size);
6720     // The UNDEF opcode check really should be dead code here, but not quite
6721     // worth asserting on (it isn't invalid, just unexpected).
6722     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6723       Zeroable[i] = true;
6724   }
6725
6726   return Zeroable;
6727 }
6728
6729 /// \brief Try to emit a bitmask instruction for a shuffle.
6730 ///
6731 /// This handles cases where we can model a blend exactly as a bitmask due to
6732 /// one of the inputs being zeroable.
6733 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6734                                            SDValue V2, ArrayRef<int> Mask,
6735                                            SelectionDAG &DAG) {
6736   MVT EltVT = VT.getScalarType();
6737   int NumEltBits = EltVT.getSizeInBits();
6738   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6739   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6740   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6741                                     IntEltVT);
6742   if (EltVT.isFloatingPoint()) {
6743     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6744     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6745   }
6746   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6747   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6748   SDValue V;
6749   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6750     if (Zeroable[i])
6751       continue;
6752     if (Mask[i] % Size != i)
6753       return SDValue(); // Not a blend.
6754     if (!V)
6755       V = Mask[i] < Size ? V1 : V2;
6756     else if (V != (Mask[i] < Size ? V1 : V2))
6757       return SDValue(); // Can only let one input through the mask.
6758
6759     VMaskOps[i] = AllOnes;
6760   }
6761   if (!V)
6762     return SDValue(); // No non-zeroable elements!
6763
6764   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6765   V = DAG.getNode(VT.isFloatingPoint()
6766                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6767                   DL, VT, V, VMask);
6768   return V;
6769 }
6770
6771 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6772 ///
6773 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6774 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6775 /// matches elements from one of the input vectors shuffled to the left or
6776 /// right with zeroable elements 'shifted in'. It handles both the strictly
6777 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6778 /// quad word lane.
6779 ///
6780 /// PSHL : (little-endian) left bit shift.
6781 /// [ zz, 0, zz,  2 ]
6782 /// [ -1, 4, zz, -1 ]
6783 /// PSRL : (little-endian) right bit shift.
6784 /// [  1, zz,  3, zz]
6785 /// [ -1, -1,  7, zz]
6786 /// PSLLDQ : (little-endian) left byte shift
6787 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6788 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6789 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6790 /// PSRLDQ : (little-endian) right byte shift
6791 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6792 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6793 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6794 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6795                                          SDValue V2, ArrayRef<int> Mask,
6796                                          SelectionDAG &DAG) {
6797   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6798
6799   int Size = Mask.size();
6800   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6801
6802   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6803     for (int i = 0; i < Size; i += Scale)
6804       for (int j = 0; j < Shift; ++j)
6805         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6806           return false;
6807
6808     return true;
6809   };
6810
6811   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6812     for (int i = 0; i != Size; i += Scale) {
6813       unsigned Pos = Left ? i + Shift : i;
6814       unsigned Low = Left ? i : i + Shift;
6815       unsigned Len = Scale - Shift;
6816       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6817                                       Low + (V == V1 ? 0 : Size)))
6818         return SDValue();
6819     }
6820
6821     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6822     bool ByteShift = ShiftEltBits > 64;
6823     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6824                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6825     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6826
6827     // Normalize the scale for byte shifts to still produce an i64 element
6828     // type.
6829     Scale = ByteShift ? Scale / 2 : Scale;
6830
6831     // We need to round trip through the appropriate type for the shift.
6832     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6833     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6834     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6835            "Illegal integer vector type");
6836     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6837
6838     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6839                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6840     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6841   };
6842
6843   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6844   // keep doubling the size of the integer elements up to that. We can
6845   // then shift the elements of the integer vector by whole multiples of
6846   // their width within the elements of the larger integer vector. Test each
6847   // multiple to see if we can find a match with the moved element indices
6848   // and that the shifted in elements are all zeroable.
6849   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6850     for (int Shift = 1; Shift != Scale; ++Shift)
6851       for (bool Left : {true, false})
6852         if (CheckZeros(Shift, Scale, Left))
6853           for (SDValue V : {V1, V2})
6854             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6855               return Match;
6856
6857   // no match
6858   return SDValue();
6859 }
6860
6861 /// \brief Lower a vector shuffle as a zero or any extension.
6862 ///
6863 /// Given a specific number of elements, element bit width, and extension
6864 /// stride, produce either a zero or any extension based on the available
6865 /// features of the subtarget.
6866 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6867     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6868     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6869   assert(Scale > 1 && "Need a scale to extend.");
6870   int NumElements = VT.getVectorNumElements();
6871   int EltBits = VT.getScalarSizeInBits();
6872   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6873          "Only 8, 16, and 32 bit elements can be extended.");
6874   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6875
6876   // Found a valid zext mask! Try various lowering strategies based on the
6877   // input type and available ISA extensions.
6878   if (Subtarget->hasSSE41()) {
6879     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6880                                  NumElements / Scale);
6881     return DAG.getNode(ISD::BITCAST, DL, VT,
6882                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6883   }
6884
6885   // For any extends we can cheat for larger element sizes and use shuffle
6886   // instructions that can fold with a load and/or copy.
6887   if (AnyExt && EltBits == 32) {
6888     int PSHUFDMask[4] = {0, -1, 1, -1};
6889     return DAG.getNode(
6890         ISD::BITCAST, DL, VT,
6891         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6892                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6893                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6894   }
6895   if (AnyExt && EltBits == 16 && Scale > 2) {
6896     int PSHUFDMask[4] = {0, -1, 0, -1};
6897     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6898                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6899                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6900     int PSHUFHWMask[4] = {1, -1, -1, -1};
6901     return DAG.getNode(
6902         ISD::BITCAST, DL, VT,
6903         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6904                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6905                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6906   }
6907
6908   // If this would require more than 2 unpack instructions to expand, use
6909   // pshufb when available. We can only use more than 2 unpack instructions
6910   // when zero extending i8 elements which also makes it easier to use pshufb.
6911   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6912     assert(NumElements == 16 && "Unexpected byte vector width!");
6913     SDValue PSHUFBMask[16];
6914     for (int i = 0; i < 16; ++i)
6915       PSHUFBMask[i] =
6916           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6917     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6918     return DAG.getNode(ISD::BITCAST, DL, VT,
6919                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6920                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6921                                                MVT::v16i8, PSHUFBMask)));
6922   }
6923
6924   // Otherwise emit a sequence of unpacks.
6925   do {
6926     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6927     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6928                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6929     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6930     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6931     Scale /= 2;
6932     EltBits *= 2;
6933     NumElements /= 2;
6934   } while (Scale > 1);
6935   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6936 }
6937
6938 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6939 ///
6940 /// This routine will try to do everything in its power to cleverly lower
6941 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6942 /// check for the profitability of this lowering,  it tries to aggressively
6943 /// match this pattern. It will use all of the micro-architectural details it
6944 /// can to emit an efficient lowering. It handles both blends with all-zero
6945 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6946 /// masking out later).
6947 ///
6948 /// The reason we have dedicated lowering for zext-style shuffles is that they
6949 /// are both incredibly common and often quite performance sensitive.
6950 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6951     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6952     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6953   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6954
6955   int Bits = VT.getSizeInBits();
6956   int NumElements = VT.getVectorNumElements();
6957   assert(VT.getScalarSizeInBits() <= 32 &&
6958          "Exceeds 32-bit integer zero extension limit");
6959   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6960
6961   // Define a helper function to check a particular ext-scale and lower to it if
6962   // valid.
6963   auto Lower = [&](int Scale) -> SDValue {
6964     SDValue InputV;
6965     bool AnyExt = true;
6966     for (int i = 0; i < NumElements; ++i) {
6967       if (Mask[i] == -1)
6968         continue; // Valid anywhere but doesn't tell us anything.
6969       if (i % Scale != 0) {
6970         // Each of the extended elements need to be zeroable.
6971         if (!Zeroable[i])
6972           return SDValue();
6973
6974         // We no longer are in the anyext case.
6975         AnyExt = false;
6976         continue;
6977       }
6978
6979       // Each of the base elements needs to be consecutive indices into the
6980       // same input vector.
6981       SDValue V = Mask[i] < NumElements ? V1 : V2;
6982       if (!InputV)
6983         InputV = V;
6984       else if (InputV != V)
6985         return SDValue(); // Flip-flopping inputs.
6986
6987       if (Mask[i] % NumElements != i / Scale)
6988         return SDValue(); // Non-consecutive strided elements.
6989     }
6990
6991     // If we fail to find an input, we have a zero-shuffle which should always
6992     // have already been handled.
6993     // FIXME: Maybe handle this here in case during blending we end up with one?
6994     if (!InputV)
6995       return SDValue();
6996
6997     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6998         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6999   };
7000
7001   // The widest scale possible for extending is to a 64-bit integer.
7002   assert(Bits % 64 == 0 &&
7003          "The number of bits in a vector must be divisible by 64 on x86!");
7004   int NumExtElements = Bits / 64;
7005
7006   // Each iteration, try extending the elements half as much, but into twice as
7007   // many elements.
7008   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7009     assert(NumElements % NumExtElements == 0 &&
7010            "The input vector size must be divisible by the extended size.");
7011     if (SDValue V = Lower(NumElements / NumExtElements))
7012       return V;
7013   }
7014
7015   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7016   if (Bits != 128)
7017     return SDValue();
7018
7019   // Returns one of the source operands if the shuffle can be reduced to a
7020   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7021   auto CanZExtLowHalf = [&]() {
7022     for (int i = NumElements / 2; i != NumElements; ++i)
7023       if (!Zeroable[i])
7024         return SDValue();
7025     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7026       return V1;
7027     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7028       return V2;
7029     return SDValue();
7030   };
7031
7032   if (SDValue V = CanZExtLowHalf()) {
7033     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
7034     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7035     return DAG.getNode(ISD::BITCAST, DL, VT, V);
7036   }
7037
7038   // No viable ext lowering found.
7039   return SDValue();
7040 }
7041
7042 /// \brief Try to get a scalar value for a specific element of a vector.
7043 ///
7044 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7045 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7046                                               SelectionDAG &DAG) {
7047   MVT VT = V.getSimpleValueType();
7048   MVT EltVT = VT.getVectorElementType();
7049   while (V.getOpcode() == ISD::BITCAST)
7050     V = V.getOperand(0);
7051   // If the bitcasts shift the element size, we can't extract an equivalent
7052   // element from it.
7053   MVT NewVT = V.getSimpleValueType();
7054   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7055     return SDValue();
7056
7057   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7058       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7059     // Ensure the scalar operand is the same size as the destination.
7060     // FIXME: Add support for scalar truncation where possible.
7061     SDValue S = V.getOperand(Idx);
7062     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7063       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7064   }
7065
7066   return SDValue();
7067 }
7068
7069 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7070 ///
7071 /// This is particularly important because the set of instructions varies
7072 /// significantly based on whether the operand is a load or not.
7073 static bool isShuffleFoldableLoad(SDValue V) {
7074   while (V.getOpcode() == ISD::BITCAST)
7075     V = V.getOperand(0);
7076
7077   return ISD::isNON_EXTLoad(V.getNode());
7078 }
7079
7080 /// \brief Try to lower insertion of a single element into a zero vector.
7081 ///
7082 /// This is a common pattern that we have especially efficient patterns to lower
7083 /// across all subtarget feature sets.
7084 static SDValue lowerVectorShuffleAsElementInsertion(
7085     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7086     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7087   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7088   MVT ExtVT = VT;
7089   MVT EltVT = VT.getVectorElementType();
7090
7091   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7092                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7093                 Mask.begin();
7094   bool IsV1Zeroable = true;
7095   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7096     if (i != V2Index && !Zeroable[i]) {
7097       IsV1Zeroable = false;
7098       break;
7099     }
7100
7101   // Check for a single input from a SCALAR_TO_VECTOR node.
7102   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7103   // all the smarts here sunk into that routine. However, the current
7104   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7105   // vector shuffle lowering is dead.
7106   if (SDValue V2S = getScalarValueForVectorElement(
7107           V2, Mask[V2Index] - Mask.size(), DAG)) {
7108     // We need to zext the scalar if it is smaller than an i32.
7109     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7110     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7111       // Using zext to expand a narrow element won't work for non-zero
7112       // insertions.
7113       if (!IsV1Zeroable)
7114         return SDValue();
7115
7116       // Zero-extend directly to i32.
7117       ExtVT = MVT::v4i32;
7118       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7119     }
7120     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7121   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7122              EltVT == MVT::i16) {
7123     // Either not inserting from the low element of the input or the input
7124     // element size is too small to use VZEXT_MOVL to clear the high bits.
7125     return SDValue();
7126   }
7127
7128   if (!IsV1Zeroable) {
7129     // If V1 can't be treated as a zero vector we have fewer options to lower
7130     // this. We can't support integer vectors or non-zero targets cheaply, and
7131     // the V1 elements can't be permuted in any way.
7132     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7133     if (!VT.isFloatingPoint() || V2Index != 0)
7134       return SDValue();
7135     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7136     V1Mask[V2Index] = -1;
7137     if (!isNoopShuffleMask(V1Mask))
7138       return SDValue();
7139     // This is essentially a special case blend operation, but if we have
7140     // general purpose blend operations, they are always faster. Bail and let
7141     // the rest of the lowering handle these as blends.
7142     if (Subtarget->hasSSE41())
7143       return SDValue();
7144
7145     // Otherwise, use MOVSD or MOVSS.
7146     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7147            "Only two types of floating point element types to handle!");
7148     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7149                        ExtVT, V1, V2);
7150   }
7151
7152   // This lowering only works for the low element with floating point vectors.
7153   if (VT.isFloatingPoint() && V2Index != 0)
7154     return SDValue();
7155
7156   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7157   if (ExtVT != VT)
7158     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7159
7160   if (V2Index != 0) {
7161     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7162     // the desired position. Otherwise it is more efficient to do a vector
7163     // shift left. We know that we can do a vector shift left because all
7164     // the inputs are zero.
7165     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7166       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7167       V2Shuffle[V2Index] = 0;
7168       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7169     } else {
7170       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7171       V2 = DAG.getNode(
7172           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7173           DAG.getConstant(
7174               V2Index * EltVT.getSizeInBits()/8, DL,
7175               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7176       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7177     }
7178   }
7179   return V2;
7180 }
7181
7182 /// \brief Try to lower broadcast of a single element.
7183 ///
7184 /// For convenience, this code also bundles all of the subtarget feature set
7185 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7186 /// a convenient way to factor it out.
7187 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7188                                              ArrayRef<int> Mask,
7189                                              const X86Subtarget *Subtarget,
7190                                              SelectionDAG &DAG) {
7191   if (!Subtarget->hasAVX())
7192     return SDValue();
7193   if (VT.isInteger() && !Subtarget->hasAVX2())
7194     return SDValue();
7195
7196   // Check that the mask is a broadcast.
7197   int BroadcastIdx = -1;
7198   for (int M : Mask)
7199     if (M >= 0 && BroadcastIdx == -1)
7200       BroadcastIdx = M;
7201     else if (M >= 0 && M != BroadcastIdx)
7202       return SDValue();
7203
7204   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7205                                             "a sorted mask where the broadcast "
7206                                             "comes from V1.");
7207
7208   // Go up the chain of (vector) values to find a scalar load that we can
7209   // combine with the broadcast.
7210   for (;;) {
7211     switch (V.getOpcode()) {
7212     case ISD::CONCAT_VECTORS: {
7213       int OperandSize = Mask.size() / V.getNumOperands();
7214       V = V.getOperand(BroadcastIdx / OperandSize);
7215       BroadcastIdx %= OperandSize;
7216       continue;
7217     }
7218
7219     case ISD::INSERT_SUBVECTOR: {
7220       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7221       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7222       if (!ConstantIdx)
7223         break;
7224
7225       int BeginIdx = (int)ConstantIdx->getZExtValue();
7226       int EndIdx =
7227           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7228       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7229         BroadcastIdx -= BeginIdx;
7230         V = VInner;
7231       } else {
7232         V = VOuter;
7233       }
7234       continue;
7235     }
7236     }
7237     break;
7238   }
7239
7240   // Check if this is a broadcast of a scalar. We special case lowering
7241   // for scalars so that we can more effectively fold with loads.
7242   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7243       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7244     V = V.getOperand(BroadcastIdx);
7245
7246     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7247     // Only AVX2 has register broadcasts.
7248     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7249       return SDValue();
7250   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7251     // We can't broadcast from a vector register without AVX2, and we can only
7252     // broadcast from the zero-element of a vector register.
7253     return SDValue();
7254   }
7255
7256   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7257 }
7258
7259 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7260 // INSERTPS when the V1 elements are already in the correct locations
7261 // because otherwise we can just always use two SHUFPS instructions which
7262 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7263 // perform INSERTPS if a single V1 element is out of place and all V2
7264 // elements are zeroable.
7265 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7266                                             ArrayRef<int> Mask,
7267                                             SelectionDAG &DAG) {
7268   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7269   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7270   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7271   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7272
7273   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7274
7275   unsigned ZMask = 0;
7276   int V1DstIndex = -1;
7277   int V2DstIndex = -1;
7278   bool V1UsedInPlace = false;
7279
7280   for (int i = 0; i < 4; ++i) {
7281     // Synthesize a zero mask from the zeroable elements (includes undefs).
7282     if (Zeroable[i]) {
7283       ZMask |= 1 << i;
7284       continue;
7285     }
7286
7287     // Flag if we use any V1 inputs in place.
7288     if (i == Mask[i]) {
7289       V1UsedInPlace = true;
7290       continue;
7291     }
7292
7293     // We can only insert a single non-zeroable element.
7294     if (V1DstIndex != -1 || V2DstIndex != -1)
7295       return SDValue();
7296
7297     if (Mask[i] < 4) {
7298       // V1 input out of place for insertion.
7299       V1DstIndex = i;
7300     } else {
7301       // V2 input for insertion.
7302       V2DstIndex = i;
7303     }
7304   }
7305
7306   // Don't bother if we have no (non-zeroable) element for insertion.
7307   if (V1DstIndex == -1 && V2DstIndex == -1)
7308     return SDValue();
7309
7310   // Determine element insertion src/dst indices. The src index is from the
7311   // start of the inserted vector, not the start of the concatenated vector.
7312   unsigned V2SrcIndex = 0;
7313   if (V1DstIndex != -1) {
7314     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7315     // and don't use the original V2 at all.
7316     V2SrcIndex = Mask[V1DstIndex];
7317     V2DstIndex = V1DstIndex;
7318     V2 = V1;
7319   } else {
7320     V2SrcIndex = Mask[V2DstIndex] - 4;
7321   }
7322
7323   // If no V1 inputs are used in place, then the result is created only from
7324   // the zero mask and the V2 insertion - so remove V1 dependency.
7325   if (!V1UsedInPlace)
7326     V1 = DAG.getUNDEF(MVT::v4f32);
7327
7328   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7329   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7330
7331   // Insert the V2 element into the desired position.
7332   SDLoc DL(Op);
7333   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7334                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7335 }
7336
7337 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7338 /// UNPCK instruction.
7339 ///
7340 /// This specifically targets cases where we end up with alternating between
7341 /// the two inputs, and so can permute them into something that feeds a single
7342 /// UNPCK instruction. Note that this routine only targets integer vectors
7343 /// because for floating point vectors we have a generalized SHUFPS lowering
7344 /// strategy that handles everything that doesn't *exactly* match an unpack,
7345 /// making this clever lowering unnecessary.
7346 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7347                                           SDValue V2, ArrayRef<int> Mask,
7348                                           SelectionDAG &DAG) {
7349   assert(!VT.isFloatingPoint() &&
7350          "This routine only supports integer vectors.");
7351   assert(!isSingleInputShuffleMask(Mask) &&
7352          "This routine should only be used when blending two inputs.");
7353   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7354
7355   int Size = Mask.size();
7356
7357   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7358     return M >= 0 && M % Size < Size / 2;
7359   });
7360   int NumHiInputs = std::count_if(
7361       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7362
7363   bool UnpackLo = NumLoInputs >= NumHiInputs;
7364
7365   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7366     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7367     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7368
7369     for (int i = 0; i < Size; ++i) {
7370       if (Mask[i] < 0)
7371         continue;
7372
7373       // Each element of the unpack contains Scale elements from this mask.
7374       int UnpackIdx = i / Scale;
7375
7376       // We only handle the case where V1 feeds the first slots of the unpack.
7377       // We rely on canonicalization to ensure this is the case.
7378       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7379         return SDValue();
7380
7381       // Setup the mask for this input. The indexing is tricky as we have to
7382       // handle the unpack stride.
7383       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7384       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7385           Mask[i] % Size;
7386     }
7387
7388     // If we will have to shuffle both inputs to use the unpack, check whether
7389     // we can just unpack first and shuffle the result. If so, skip this unpack.
7390     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7391         !isNoopShuffleMask(V2Mask))
7392       return SDValue();
7393
7394     // Shuffle the inputs into place.
7395     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7396     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7397
7398     // Cast the inputs to the type we will use to unpack them.
7399     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7400     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7401
7402     // Unpack the inputs and cast the result back to the desired type.
7403     return DAG.getNode(ISD::BITCAST, DL, VT,
7404                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7405                                    DL, UnpackVT, V1, V2));
7406   };
7407
7408   // We try each unpack from the largest to the smallest to try and find one
7409   // that fits this mask.
7410   int OrigNumElements = VT.getVectorNumElements();
7411   int OrigScalarSize = VT.getScalarSizeInBits();
7412   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7413     int Scale = ScalarSize / OrigScalarSize;
7414     int NumElements = OrigNumElements / Scale;
7415     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7416     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7417       return Unpack;
7418   }
7419
7420   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7421   // initial unpack.
7422   if (NumLoInputs == 0 || NumHiInputs == 0) {
7423     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7424            "We have to have *some* inputs!");
7425     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7426
7427     // FIXME: We could consider the total complexity of the permute of each
7428     // possible unpacking. Or at the least we should consider how many
7429     // half-crossings are created.
7430     // FIXME: We could consider commuting the unpacks.
7431
7432     SmallVector<int, 32> PermMask;
7433     PermMask.assign(Size, -1);
7434     for (int i = 0; i < Size; ++i) {
7435       if (Mask[i] < 0)
7436         continue;
7437
7438       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7439
7440       PermMask[i] =
7441           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7442     }
7443     return DAG.getVectorShuffle(
7444         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7445                             DL, VT, V1, V2),
7446         DAG.getUNDEF(VT), PermMask);
7447   }
7448
7449   return SDValue();
7450 }
7451
7452 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7453 ///
7454 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7455 /// support for floating point shuffles but not integer shuffles. These
7456 /// instructions will incur a domain crossing penalty on some chips though so
7457 /// it is better to avoid lowering through this for integer vectors where
7458 /// possible.
7459 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7460                                        const X86Subtarget *Subtarget,
7461                                        SelectionDAG &DAG) {
7462   SDLoc DL(Op);
7463   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7464   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7465   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7466   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7467   ArrayRef<int> Mask = SVOp->getMask();
7468   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7469
7470   if (isSingleInputShuffleMask(Mask)) {
7471     // Use low duplicate instructions for masks that match their pattern.
7472     if (Subtarget->hasSSE3())
7473       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7474         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7475
7476     // Straight shuffle of a single input vector. Simulate this by using the
7477     // single input as both of the "inputs" to this instruction..
7478     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7479
7480     if (Subtarget->hasAVX()) {
7481       // If we have AVX, we can use VPERMILPS which will allow folding a load
7482       // into the shuffle.
7483       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7484                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7485     }
7486
7487     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7488                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7489   }
7490   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7491   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7492
7493   // If we have a single input, insert that into V1 if we can do so cheaply.
7494   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7495     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7496             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7497       return Insertion;
7498     // Try inverting the insertion since for v2 masks it is easy to do and we
7499     // can't reliably sort the mask one way or the other.
7500     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7501                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7502     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7503             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7504       return Insertion;
7505   }
7506
7507   // Try to use one of the special instruction patterns to handle two common
7508   // blend patterns if a zero-blend above didn't work.
7509   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7510       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7511     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7512       // We can either use a special instruction to load over the low double or
7513       // to move just the low double.
7514       return DAG.getNode(
7515           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7516           DL, MVT::v2f64, V2,
7517           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7518
7519   if (Subtarget->hasSSE41())
7520     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7521                                                   Subtarget, DAG))
7522       return Blend;
7523
7524   // Use dedicated unpack instructions for masks that match their pattern.
7525   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7526     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7527   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7528     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7529
7530   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7531   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7532                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7533 }
7534
7535 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7536 ///
7537 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7538 /// the integer unit to minimize domain crossing penalties. However, for blends
7539 /// it falls back to the floating point shuffle operation with appropriate bit
7540 /// casting.
7541 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7542                                        const X86Subtarget *Subtarget,
7543                                        SelectionDAG &DAG) {
7544   SDLoc DL(Op);
7545   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7546   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7547   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7548   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7549   ArrayRef<int> Mask = SVOp->getMask();
7550   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7551
7552   if (isSingleInputShuffleMask(Mask)) {
7553     // Check for being able to broadcast a single element.
7554     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7555                                                           Mask, Subtarget, DAG))
7556       return Broadcast;
7557
7558     // Straight shuffle of a single input vector. For everything from SSE2
7559     // onward this has a single fast instruction with no scary immediates.
7560     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7561     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7562     int WidenedMask[4] = {
7563         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7564         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7565     return DAG.getNode(
7566         ISD::BITCAST, DL, MVT::v2i64,
7567         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7568                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7569   }
7570   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7571   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7572   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7573   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7574
7575   // If we have a blend of two PACKUS operations an the blend aligns with the
7576   // low and half halves, we can just merge the PACKUS operations. This is
7577   // particularly important as it lets us merge shuffles that this routine itself
7578   // creates.
7579   auto GetPackNode = [](SDValue V) {
7580     while (V.getOpcode() == ISD::BITCAST)
7581       V = V.getOperand(0);
7582
7583     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7584   };
7585   if (SDValue V1Pack = GetPackNode(V1))
7586     if (SDValue V2Pack = GetPackNode(V2))
7587       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7588                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7589                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7590                                                   : V1Pack.getOperand(1),
7591                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7592                                                   : V2Pack.getOperand(1)));
7593
7594   // Try to use shift instructions.
7595   if (SDValue Shift =
7596           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7597     return Shift;
7598
7599   // When loading a scalar and then shuffling it into a vector we can often do
7600   // the insertion cheaply.
7601   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7602           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7603     return Insertion;
7604   // Try inverting the insertion since for v2 masks it is easy to do and we
7605   // can't reliably sort the mask one way or the other.
7606   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7607   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7608           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7609     return Insertion;
7610
7611   // We have different paths for blend lowering, but they all must use the
7612   // *exact* same predicate.
7613   bool IsBlendSupported = Subtarget->hasSSE41();
7614   if (IsBlendSupported)
7615     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7616                                                   Subtarget, DAG))
7617       return Blend;
7618
7619   // Use dedicated unpack instructions for masks that match their pattern.
7620   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7621     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7622   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7623     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7624
7625   // Try to use byte rotation instructions.
7626   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7627   if (Subtarget->hasSSSE3())
7628     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7629             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7630       return Rotate;
7631
7632   // If we have direct support for blends, we should lower by decomposing into
7633   // a permute. That will be faster than the domain cross.
7634   if (IsBlendSupported)
7635     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7636                                                       Mask, DAG);
7637
7638   // We implement this with SHUFPD which is pretty lame because it will likely
7639   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7640   // However, all the alternatives are still more cycles and newer chips don't
7641   // have this problem. It would be really nice if x86 had better shuffles here.
7642   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7643   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7644   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7645                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7646 }
7647
7648 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7649 ///
7650 /// This is used to disable more specialized lowerings when the shufps lowering
7651 /// will happen to be efficient.
7652 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7653   // This routine only handles 128-bit shufps.
7654   assert(Mask.size() == 4 && "Unsupported mask size!");
7655
7656   // To lower with a single SHUFPS we need to have the low half and high half
7657   // each requiring a single input.
7658   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7659     return false;
7660   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7661     return false;
7662
7663   return true;
7664 }
7665
7666 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7667 ///
7668 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7669 /// It makes no assumptions about whether this is the *best* lowering, it simply
7670 /// uses it.
7671 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7672                                             ArrayRef<int> Mask, SDValue V1,
7673                                             SDValue V2, SelectionDAG &DAG) {
7674   SDValue LowV = V1, HighV = V2;
7675   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7676
7677   int NumV2Elements =
7678       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7679
7680   if (NumV2Elements == 1) {
7681     int V2Index =
7682         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7683         Mask.begin();
7684
7685     // Compute the index adjacent to V2Index and in the same half by toggling
7686     // the low bit.
7687     int V2AdjIndex = V2Index ^ 1;
7688
7689     if (Mask[V2AdjIndex] == -1) {
7690       // Handles all the cases where we have a single V2 element and an undef.
7691       // This will only ever happen in the high lanes because we commute the
7692       // vector otherwise.
7693       if (V2Index < 2)
7694         std::swap(LowV, HighV);
7695       NewMask[V2Index] -= 4;
7696     } else {
7697       // Handle the case where the V2 element ends up adjacent to a V1 element.
7698       // To make this work, blend them together as the first step.
7699       int V1Index = V2AdjIndex;
7700       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7701       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7702                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7703
7704       // Now proceed to reconstruct the final blend as we have the necessary
7705       // high or low half formed.
7706       if (V2Index < 2) {
7707         LowV = V2;
7708         HighV = V1;
7709       } else {
7710         HighV = V2;
7711       }
7712       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7713       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7714     }
7715   } else if (NumV2Elements == 2) {
7716     if (Mask[0] < 4 && Mask[1] < 4) {
7717       // Handle the easy case where we have V1 in the low lanes and V2 in the
7718       // high lanes.
7719       NewMask[2] -= 4;
7720       NewMask[3] -= 4;
7721     } else if (Mask[2] < 4 && Mask[3] < 4) {
7722       // We also handle the reversed case because this utility may get called
7723       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7724       // arrange things in the right direction.
7725       NewMask[0] -= 4;
7726       NewMask[1] -= 4;
7727       HighV = V1;
7728       LowV = V2;
7729     } else {
7730       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7731       // trying to place elements directly, just blend them and set up the final
7732       // shuffle to place them.
7733
7734       // The first two blend mask elements are for V1, the second two are for
7735       // V2.
7736       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7737                           Mask[2] < 4 ? Mask[2] : Mask[3],
7738                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7739                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7740       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7741                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7742
7743       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7744       // a blend.
7745       LowV = HighV = V1;
7746       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7747       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7748       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7749       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7750     }
7751   }
7752   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7753                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7754 }
7755
7756 /// \brief Lower 4-lane 32-bit floating point shuffles.
7757 ///
7758 /// Uses instructions exclusively from the floating point unit to minimize
7759 /// domain crossing penalties, as these are sufficient to implement all v4f32
7760 /// shuffles.
7761 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7762                                        const X86Subtarget *Subtarget,
7763                                        SelectionDAG &DAG) {
7764   SDLoc DL(Op);
7765   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7766   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7767   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7768   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7769   ArrayRef<int> Mask = SVOp->getMask();
7770   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7771
7772   int NumV2Elements =
7773       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7774
7775   if (NumV2Elements == 0) {
7776     // Check for being able to broadcast a single element.
7777     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7778                                                           Mask, Subtarget, DAG))
7779       return Broadcast;
7780
7781     // Use even/odd duplicate instructions for masks that match their pattern.
7782     if (Subtarget->hasSSE3()) {
7783       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7784         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7785       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7786         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7787     }
7788
7789     if (Subtarget->hasAVX()) {
7790       // If we have AVX, we can use VPERMILPS which will allow folding a load
7791       // into the shuffle.
7792       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7793                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7794     }
7795
7796     // Otherwise, use a straight shuffle of a single input vector. We pass the
7797     // input vector to both operands to simulate this with a SHUFPS.
7798     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7799                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7800   }
7801
7802   // There are special ways we can lower some single-element blends. However, we
7803   // have custom ways we can lower more complex single-element blends below that
7804   // we defer to if both this and BLENDPS fail to match, so restrict this to
7805   // when the V2 input is targeting element 0 of the mask -- that is the fast
7806   // case here.
7807   if (NumV2Elements == 1 && Mask[0] >= 4)
7808     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7809                                                          Mask, Subtarget, DAG))
7810       return V;
7811
7812   if (Subtarget->hasSSE41()) {
7813     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7814                                                   Subtarget, DAG))
7815       return Blend;
7816
7817     // Use INSERTPS if we can complete the shuffle efficiently.
7818     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7819       return V;
7820
7821     if (!isSingleSHUFPSMask(Mask))
7822       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7823               DL, MVT::v4f32, V1, V2, Mask, DAG))
7824         return BlendPerm;
7825   }
7826
7827   // Use dedicated unpack instructions for masks that match their pattern.
7828   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7829     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7830   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7831     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7832   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7833     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7834   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7835     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7836
7837   // Otherwise fall back to a SHUFPS lowering strategy.
7838   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7839 }
7840
7841 /// \brief Lower 4-lane i32 vector shuffles.
7842 ///
7843 /// We try to handle these with integer-domain shuffles where we can, but for
7844 /// blends we use the floating point domain blend instructions.
7845 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7846                                        const X86Subtarget *Subtarget,
7847                                        SelectionDAG &DAG) {
7848   SDLoc DL(Op);
7849   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7850   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7851   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7852   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7853   ArrayRef<int> Mask = SVOp->getMask();
7854   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7855
7856   // Whenever we can lower this as a zext, that instruction is strictly faster
7857   // than any alternative. It also allows us to fold memory operands into the
7858   // shuffle in many cases.
7859   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7860                                                          Mask, Subtarget, DAG))
7861     return ZExt;
7862
7863   int NumV2Elements =
7864       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7865
7866   if (NumV2Elements == 0) {
7867     // Check for being able to broadcast a single element.
7868     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7869                                                           Mask, Subtarget, DAG))
7870       return Broadcast;
7871
7872     // Straight shuffle of a single input vector. For everything from SSE2
7873     // onward this has a single fast instruction with no scary immediates.
7874     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7875     // but we aren't actually going to use the UNPCK instruction because doing
7876     // so prevents folding a load into this instruction or making a copy.
7877     const int UnpackLoMask[] = {0, 0, 1, 1};
7878     const int UnpackHiMask[] = {2, 2, 3, 3};
7879     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7880       Mask = UnpackLoMask;
7881     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7882       Mask = UnpackHiMask;
7883
7884     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7885                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7886   }
7887
7888   // Try to use shift instructions.
7889   if (SDValue Shift =
7890           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7891     return Shift;
7892
7893   // There are special ways we can lower some single-element blends.
7894   if (NumV2Elements == 1)
7895     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7896                                                          Mask, Subtarget, DAG))
7897       return V;
7898
7899   // We have different paths for blend lowering, but they all must use the
7900   // *exact* same predicate.
7901   bool IsBlendSupported = Subtarget->hasSSE41();
7902   if (IsBlendSupported)
7903     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7904                                                   Subtarget, DAG))
7905       return Blend;
7906
7907   if (SDValue Masked =
7908           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7909     return Masked;
7910
7911   // Use dedicated unpack instructions for masks that match their pattern.
7912   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7913     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7914   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7915     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7916   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7917     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7918   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7919     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7920
7921   // Try to use byte rotation instructions.
7922   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7923   if (Subtarget->hasSSSE3())
7924     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7925             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7926       return Rotate;
7927
7928   // If we have direct support for blends, we should lower by decomposing into
7929   // a permute. That will be faster than the domain cross.
7930   if (IsBlendSupported)
7931     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7932                                                       Mask, DAG);
7933
7934   // Try to lower by permuting the inputs into an unpack instruction.
7935   if (SDValue Unpack =
7936           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7937     return Unpack;
7938
7939   // We implement this with SHUFPS because it can blend from two vectors.
7940   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7941   // up the inputs, bypassing domain shift penalties that we would encur if we
7942   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7943   // relevant.
7944   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7945                      DAG.getVectorShuffle(
7946                          MVT::v4f32, DL,
7947                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7948                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7949 }
7950
7951 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7952 /// shuffle lowering, and the most complex part.
7953 ///
7954 /// The lowering strategy is to try to form pairs of input lanes which are
7955 /// targeted at the same half of the final vector, and then use a dword shuffle
7956 /// to place them onto the right half, and finally unpack the paired lanes into
7957 /// their final position.
7958 ///
7959 /// The exact breakdown of how to form these dword pairs and align them on the
7960 /// correct sides is really tricky. See the comments within the function for
7961 /// more of the details.
7962 ///
7963 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7964 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7965 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7966 /// vector, form the analogous 128-bit 8-element Mask.
7967 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7968     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7969     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7970   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7971   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7972
7973   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7974   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7975   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7976
7977   SmallVector<int, 4> LoInputs;
7978   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7979                [](int M) { return M >= 0; });
7980   std::sort(LoInputs.begin(), LoInputs.end());
7981   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7982   SmallVector<int, 4> HiInputs;
7983   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7984                [](int M) { return M >= 0; });
7985   std::sort(HiInputs.begin(), HiInputs.end());
7986   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7987   int NumLToL =
7988       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7989   int NumHToL = LoInputs.size() - NumLToL;
7990   int NumLToH =
7991       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7992   int NumHToH = HiInputs.size() - NumLToH;
7993   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7994   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7995   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7996   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7997
7998   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7999   // such inputs we can swap two of the dwords across the half mark and end up
8000   // with <=2 inputs to each half in each half. Once there, we can fall through
8001   // to the generic code below. For example:
8002   //
8003   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8004   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8005   //
8006   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8007   // and an existing 2-into-2 on the other half. In this case we may have to
8008   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8009   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8010   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8011   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8012   // half than the one we target for fixing) will be fixed when we re-enter this
8013   // path. We will also combine away any sequence of PSHUFD instructions that
8014   // result into a single instruction. Here is an example of the tricky case:
8015   //
8016   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8017   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8018   //
8019   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8020   //
8021   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8022   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8023   //
8024   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8025   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8026   //
8027   // The result is fine to be handled by the generic logic.
8028   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8029                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8030                           int AOffset, int BOffset) {
8031     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8032            "Must call this with A having 3 or 1 inputs from the A half.");
8033     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8034            "Must call this with B having 1 or 3 inputs from the B half.");
8035     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8036            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8037
8038     // Compute the index of dword with only one word among the three inputs in
8039     // a half by taking the sum of the half with three inputs and subtracting
8040     // the sum of the actual three inputs. The difference is the remaining
8041     // slot.
8042     int ADWord, BDWord;
8043     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8044     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8045     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8046     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8047     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8048     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8049     int TripleNonInputIdx =
8050         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8051     TripleDWord = TripleNonInputIdx / 2;
8052
8053     // We use xor with one to compute the adjacent DWord to whichever one the
8054     // OneInput is in.
8055     OneInputDWord = (OneInput / 2) ^ 1;
8056
8057     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8058     // and BToA inputs. If there is also such a problem with the BToB and AToB
8059     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8060     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8061     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8062     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8063       // Compute how many inputs will be flipped by swapping these DWords. We
8064       // need
8065       // to balance this to ensure we don't form a 3-1 shuffle in the other
8066       // half.
8067       int NumFlippedAToBInputs =
8068           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8069           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8070       int NumFlippedBToBInputs =
8071           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8072           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8073       if ((NumFlippedAToBInputs == 1 &&
8074            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8075           (NumFlippedBToBInputs == 1 &&
8076            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8077         // We choose whether to fix the A half or B half based on whether that
8078         // half has zero flipped inputs. At zero, we may not be able to fix it
8079         // with that half. We also bias towards fixing the B half because that
8080         // will more commonly be the high half, and we have to bias one way.
8081         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8082                                                        ArrayRef<int> Inputs) {
8083           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8084           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8085                                          PinnedIdx ^ 1) != Inputs.end();
8086           // Determine whether the free index is in the flipped dword or the
8087           // unflipped dword based on where the pinned index is. We use this bit
8088           // in an xor to conditionally select the adjacent dword.
8089           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8090           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8091                                              FixFreeIdx) != Inputs.end();
8092           if (IsFixIdxInput == IsFixFreeIdxInput)
8093             FixFreeIdx += 1;
8094           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8095                                         FixFreeIdx) != Inputs.end();
8096           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8097                  "We need to be changing the number of flipped inputs!");
8098           int PSHUFHalfMask[] = {0, 1, 2, 3};
8099           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8100           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8101                           MVT::v8i16, V,
8102                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8103
8104           for (int &M : Mask)
8105             if (M != -1 && M == FixIdx)
8106               M = FixFreeIdx;
8107             else if (M != -1 && M == FixFreeIdx)
8108               M = FixIdx;
8109         };
8110         if (NumFlippedBToBInputs != 0) {
8111           int BPinnedIdx =
8112               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8113           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8114         } else {
8115           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8116           int APinnedIdx =
8117               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8118           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8119         }
8120       }
8121     }
8122
8123     int PSHUFDMask[] = {0, 1, 2, 3};
8124     PSHUFDMask[ADWord] = BDWord;
8125     PSHUFDMask[BDWord] = ADWord;
8126     V = DAG.getNode(ISD::BITCAST, DL, VT,
8127                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8128                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8129                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8130                                                            DAG)));
8131
8132     // Adjust the mask to match the new locations of A and B.
8133     for (int &M : Mask)
8134       if (M != -1 && M/2 == ADWord)
8135         M = 2 * BDWord + M % 2;
8136       else if (M != -1 && M/2 == BDWord)
8137         M = 2 * ADWord + M % 2;
8138
8139     // Recurse back into this routine to re-compute state now that this isn't
8140     // a 3 and 1 problem.
8141     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8142                                                      DAG);
8143   };
8144   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8145     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8146   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8147     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8148
8149   // At this point there are at most two inputs to the low and high halves from
8150   // each half. That means the inputs can always be grouped into dwords and
8151   // those dwords can then be moved to the correct half with a dword shuffle.
8152   // We use at most one low and one high word shuffle to collect these paired
8153   // inputs into dwords, and finally a dword shuffle to place them.
8154   int PSHUFLMask[4] = {-1, -1, -1, -1};
8155   int PSHUFHMask[4] = {-1, -1, -1, -1};
8156   int PSHUFDMask[4] = {-1, -1, -1, -1};
8157
8158   // First fix the masks for all the inputs that are staying in their
8159   // original halves. This will then dictate the targets of the cross-half
8160   // shuffles.
8161   auto fixInPlaceInputs =
8162       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8163                     MutableArrayRef<int> SourceHalfMask,
8164                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8165     if (InPlaceInputs.empty())
8166       return;
8167     if (InPlaceInputs.size() == 1) {
8168       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8169           InPlaceInputs[0] - HalfOffset;
8170       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8171       return;
8172     }
8173     if (IncomingInputs.empty()) {
8174       // Just fix all of the in place inputs.
8175       for (int Input : InPlaceInputs) {
8176         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8177         PSHUFDMask[Input / 2] = Input / 2;
8178       }
8179       return;
8180     }
8181
8182     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8183     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8184         InPlaceInputs[0] - HalfOffset;
8185     // Put the second input next to the first so that they are packed into
8186     // a dword. We find the adjacent index by toggling the low bit.
8187     int AdjIndex = InPlaceInputs[0] ^ 1;
8188     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8189     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8190     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8191   };
8192   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8193   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8194
8195   // Now gather the cross-half inputs and place them into a free dword of
8196   // their target half.
8197   // FIXME: This operation could almost certainly be simplified dramatically to
8198   // look more like the 3-1 fixing operation.
8199   auto moveInputsToRightHalf = [&PSHUFDMask](
8200       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8201       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8202       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8203       int DestOffset) {
8204     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8205       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8206     };
8207     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8208                                                int Word) {
8209       int LowWord = Word & ~1;
8210       int HighWord = Word | 1;
8211       return isWordClobbered(SourceHalfMask, LowWord) ||
8212              isWordClobbered(SourceHalfMask, HighWord);
8213     };
8214
8215     if (IncomingInputs.empty())
8216       return;
8217
8218     if (ExistingInputs.empty()) {
8219       // Map any dwords with inputs from them into the right half.
8220       for (int Input : IncomingInputs) {
8221         // If the source half mask maps over the inputs, turn those into
8222         // swaps and use the swapped lane.
8223         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8224           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8225             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8226                 Input - SourceOffset;
8227             // We have to swap the uses in our half mask in one sweep.
8228             for (int &M : HalfMask)
8229               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8230                 M = Input;
8231               else if (M == Input)
8232                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8233           } else {
8234             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8235                        Input - SourceOffset &&
8236                    "Previous placement doesn't match!");
8237           }
8238           // Note that this correctly re-maps both when we do a swap and when
8239           // we observe the other side of the swap above. We rely on that to
8240           // avoid swapping the members of the input list directly.
8241           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8242         }
8243
8244         // Map the input's dword into the correct half.
8245         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8246           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8247         else
8248           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8249                      Input / 2 &&
8250                  "Previous placement doesn't match!");
8251       }
8252
8253       // And just directly shift any other-half mask elements to be same-half
8254       // as we will have mirrored the dword containing the element into the
8255       // same position within that half.
8256       for (int &M : HalfMask)
8257         if (M >= SourceOffset && M < SourceOffset + 4) {
8258           M = M - SourceOffset + DestOffset;
8259           assert(M >= 0 && "This should never wrap below zero!");
8260         }
8261       return;
8262     }
8263
8264     // Ensure we have the input in a viable dword of its current half. This
8265     // is particularly tricky because the original position may be clobbered
8266     // by inputs being moved and *staying* in that half.
8267     if (IncomingInputs.size() == 1) {
8268       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8269         int InputFixed = std::find(std::begin(SourceHalfMask),
8270                                    std::end(SourceHalfMask), -1) -
8271                          std::begin(SourceHalfMask) + SourceOffset;
8272         SourceHalfMask[InputFixed - SourceOffset] =
8273             IncomingInputs[0] - SourceOffset;
8274         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8275                      InputFixed);
8276         IncomingInputs[0] = InputFixed;
8277       }
8278     } else if (IncomingInputs.size() == 2) {
8279       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8280           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8281         // We have two non-adjacent or clobbered inputs we need to extract from
8282         // the source half. To do this, we need to map them into some adjacent
8283         // dword slot in the source mask.
8284         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8285                               IncomingInputs[1] - SourceOffset};
8286
8287         // If there is a free slot in the source half mask adjacent to one of
8288         // the inputs, place the other input in it. We use (Index XOR 1) to
8289         // compute an adjacent index.
8290         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8291             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8292           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8293           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8294           InputsFixed[1] = InputsFixed[0] ^ 1;
8295         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8296                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8297           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8298           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8299           InputsFixed[0] = InputsFixed[1] ^ 1;
8300         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8301                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8302           // The two inputs are in the same DWord but it is clobbered and the
8303           // adjacent DWord isn't used at all. Move both inputs to the free
8304           // slot.
8305           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8306           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8307           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8308           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8309         } else {
8310           // The only way we hit this point is if there is no clobbering
8311           // (because there are no off-half inputs to this half) and there is no
8312           // free slot adjacent to one of the inputs. In this case, we have to
8313           // swap an input with a non-input.
8314           for (int i = 0; i < 4; ++i)
8315             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8316                    "We can't handle any clobbers here!");
8317           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8318                  "Cannot have adjacent inputs here!");
8319
8320           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8321           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8322
8323           // We also have to update the final source mask in this case because
8324           // it may need to undo the above swap.
8325           for (int &M : FinalSourceHalfMask)
8326             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8327               M = InputsFixed[1] + SourceOffset;
8328             else if (M == InputsFixed[1] + SourceOffset)
8329               M = (InputsFixed[0] ^ 1) + SourceOffset;
8330
8331           InputsFixed[1] = InputsFixed[0] ^ 1;
8332         }
8333
8334         // Point everything at the fixed inputs.
8335         for (int &M : HalfMask)
8336           if (M == IncomingInputs[0])
8337             M = InputsFixed[0] + SourceOffset;
8338           else if (M == IncomingInputs[1])
8339             M = InputsFixed[1] + SourceOffset;
8340
8341         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8342         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8343       }
8344     } else {
8345       llvm_unreachable("Unhandled input size!");
8346     }
8347
8348     // Now hoist the DWord down to the right half.
8349     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8350     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8351     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8352     for (int &M : HalfMask)
8353       for (int Input : IncomingInputs)
8354         if (M == Input)
8355           M = FreeDWord * 2 + Input % 2;
8356   };
8357   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8358                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8359   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8360                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8361
8362   // Now enact all the shuffles we've computed to move the inputs into their
8363   // target half.
8364   if (!isNoopShuffleMask(PSHUFLMask))
8365     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8366                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8367   if (!isNoopShuffleMask(PSHUFHMask))
8368     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8369                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8370   if (!isNoopShuffleMask(PSHUFDMask))
8371     V = DAG.getNode(ISD::BITCAST, DL, VT,
8372                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8373                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8374                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8375                                                            DAG)));
8376
8377   // At this point, each half should contain all its inputs, and we can then
8378   // just shuffle them into their final position.
8379   assert(std::count_if(LoMask.begin(), LoMask.end(),
8380                        [](int M) { return M >= 4; }) == 0 &&
8381          "Failed to lift all the high half inputs to the low mask!");
8382   assert(std::count_if(HiMask.begin(), HiMask.end(),
8383                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8384          "Failed to lift all the low half inputs to the high mask!");
8385
8386   // Do a half shuffle for the low mask.
8387   if (!isNoopShuffleMask(LoMask))
8388     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8389                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8390
8391   // Do a half shuffle with the high mask after shifting its values down.
8392   for (int &M : HiMask)
8393     if (M >= 0)
8394       M -= 4;
8395   if (!isNoopShuffleMask(HiMask))
8396     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8397                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8398
8399   return V;
8400 }
8401
8402 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8403 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8404                                           SDValue V2, ArrayRef<int> Mask,
8405                                           SelectionDAG &DAG, bool &V1InUse,
8406                                           bool &V2InUse) {
8407   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8408   SDValue V1Mask[16];
8409   SDValue V2Mask[16];
8410   V1InUse = false;
8411   V2InUse = false;
8412
8413   int Size = Mask.size();
8414   int Scale = 16 / Size;
8415   for (int i = 0; i < 16; ++i) {
8416     if (Mask[i / Scale] == -1) {
8417       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8418     } else {
8419       const int ZeroMask = 0x80;
8420       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8421                                           : ZeroMask;
8422       int V2Idx = Mask[i / Scale] < Size
8423                       ? ZeroMask
8424                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8425       if (Zeroable[i / Scale])
8426         V1Idx = V2Idx = ZeroMask;
8427       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8428       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8429       V1InUse |= (ZeroMask != V1Idx);
8430       V2InUse |= (ZeroMask != V2Idx);
8431     }
8432   }
8433
8434   if (V1InUse)
8435     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8436                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8437                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8438   if (V2InUse)
8439     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8440                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8441                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8442
8443   // If we need shuffled inputs from both, blend the two.
8444   SDValue V;
8445   if (V1InUse && V2InUse)
8446     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8447   else
8448     V = V1InUse ? V1 : V2;
8449
8450   // Cast the result back to the correct type.
8451   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8452 }
8453
8454 /// \brief Generic lowering of 8-lane i16 shuffles.
8455 ///
8456 /// This handles both single-input shuffles and combined shuffle/blends with
8457 /// two inputs. The single input shuffles are immediately delegated to
8458 /// a dedicated lowering routine.
8459 ///
8460 /// The blends are lowered in one of three fundamental ways. If there are few
8461 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8462 /// of the input is significantly cheaper when lowered as an interleaving of
8463 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8464 /// halves of the inputs separately (making them have relatively few inputs)
8465 /// and then concatenate them.
8466 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8467                                        const X86Subtarget *Subtarget,
8468                                        SelectionDAG &DAG) {
8469   SDLoc DL(Op);
8470   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8471   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8472   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8473   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8474   ArrayRef<int> OrigMask = SVOp->getMask();
8475   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8476                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8477   MutableArrayRef<int> Mask(MaskStorage);
8478
8479   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8480
8481   // Whenever we can lower this as a zext, that instruction is strictly faster
8482   // than any alternative.
8483   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8484           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8485     return ZExt;
8486
8487   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8488   (void)isV1;
8489   auto isV2 = [](int M) { return M >= 8; };
8490
8491   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8492
8493   if (NumV2Inputs == 0) {
8494     // Check for being able to broadcast a single element.
8495     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8496                                                           Mask, Subtarget, DAG))
8497       return Broadcast;
8498
8499     // Try to use shift instructions.
8500     if (SDValue Shift =
8501             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8502       return Shift;
8503
8504     // Use dedicated unpack instructions for masks that match their pattern.
8505     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8506       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8507     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8508       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8509
8510     // Try to use byte rotation instructions.
8511     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8512                                                         Mask, Subtarget, DAG))
8513       return Rotate;
8514
8515     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8516                                                      Subtarget, DAG);
8517   }
8518
8519   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8520          "All single-input shuffles should be canonicalized to be V1-input "
8521          "shuffles.");
8522
8523   // Try to use shift instructions.
8524   if (SDValue Shift =
8525           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8526     return Shift;
8527
8528   // There are special ways we can lower some single-element blends.
8529   if (NumV2Inputs == 1)
8530     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8531                                                          Mask, Subtarget, DAG))
8532       return V;
8533
8534   // We have different paths for blend lowering, but they all must use the
8535   // *exact* same predicate.
8536   bool IsBlendSupported = Subtarget->hasSSE41();
8537   if (IsBlendSupported)
8538     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8539                                                   Subtarget, DAG))
8540       return Blend;
8541
8542   if (SDValue Masked =
8543           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8544     return Masked;
8545
8546   // Use dedicated unpack instructions for masks that match their pattern.
8547   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8548     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8549   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8550     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8551
8552   // Try to use byte rotation instructions.
8553   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8554           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8555     return Rotate;
8556
8557   if (SDValue BitBlend =
8558           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8559     return BitBlend;
8560
8561   if (SDValue Unpack =
8562           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8563     return Unpack;
8564
8565   // If we can't directly blend but can use PSHUFB, that will be better as it
8566   // can both shuffle and set up the inefficient blend.
8567   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8568     bool V1InUse, V2InUse;
8569     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8570                                       V1InUse, V2InUse);
8571   }
8572
8573   // We can always bit-blend if we have to so the fallback strategy is to
8574   // decompose into single-input permutes and blends.
8575   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8576                                                       Mask, DAG);
8577 }
8578
8579 /// \brief Check whether a compaction lowering can be done by dropping even
8580 /// elements and compute how many times even elements must be dropped.
8581 ///
8582 /// This handles shuffles which take every Nth element where N is a power of
8583 /// two. Example shuffle masks:
8584 ///
8585 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8586 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8587 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8588 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8589 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8590 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8591 ///
8592 /// Any of these lanes can of course be undef.
8593 ///
8594 /// This routine only supports N <= 3.
8595 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8596 /// for larger N.
8597 ///
8598 /// \returns N above, or the number of times even elements must be dropped if
8599 /// there is such a number. Otherwise returns zero.
8600 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8601   // Figure out whether we're looping over two inputs or just one.
8602   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8603
8604   // The modulus for the shuffle vector entries is based on whether this is
8605   // a single input or not.
8606   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8607   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8608          "We should only be called with masks with a power-of-2 size!");
8609
8610   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8611
8612   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8613   // and 2^3 simultaneously. This is because we may have ambiguity with
8614   // partially undef inputs.
8615   bool ViableForN[3] = {true, true, true};
8616
8617   for (int i = 0, e = Mask.size(); i < e; ++i) {
8618     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8619     // want.
8620     if (Mask[i] == -1)
8621       continue;
8622
8623     bool IsAnyViable = false;
8624     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8625       if (ViableForN[j]) {
8626         uint64_t N = j + 1;
8627
8628         // The shuffle mask must be equal to (i * 2^N) % M.
8629         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8630           IsAnyViable = true;
8631         else
8632           ViableForN[j] = false;
8633       }
8634     // Early exit if we exhaust the possible powers of two.
8635     if (!IsAnyViable)
8636       break;
8637   }
8638
8639   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8640     if (ViableForN[j])
8641       return j + 1;
8642
8643   // Return 0 as there is no viable power of two.
8644   return 0;
8645 }
8646
8647 /// \brief Generic lowering of v16i8 shuffles.
8648 ///
8649 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8650 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8651 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8652 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8653 /// back together.
8654 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8655                                        const X86Subtarget *Subtarget,
8656                                        SelectionDAG &DAG) {
8657   SDLoc DL(Op);
8658   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8659   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8660   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8661   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8662   ArrayRef<int> Mask = SVOp->getMask();
8663   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8664
8665   // Try to use shift instructions.
8666   if (SDValue Shift =
8667           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8668     return Shift;
8669
8670   // Try to use byte rotation instructions.
8671   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8672           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8673     return Rotate;
8674
8675   // Try to use a zext lowering.
8676   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8677           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8678     return ZExt;
8679
8680   int NumV2Elements =
8681       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8682
8683   // For single-input shuffles, there are some nicer lowering tricks we can use.
8684   if (NumV2Elements == 0) {
8685     // Check for being able to broadcast a single element.
8686     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8687                                                           Mask, Subtarget, DAG))
8688       return Broadcast;
8689
8690     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8691     // Notably, this handles splat and partial-splat shuffles more efficiently.
8692     // However, it only makes sense if the pre-duplication shuffle simplifies
8693     // things significantly. Currently, this means we need to be able to
8694     // express the pre-duplication shuffle as an i16 shuffle.
8695     //
8696     // FIXME: We should check for other patterns which can be widened into an
8697     // i16 shuffle as well.
8698     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8699       for (int i = 0; i < 16; i += 2)
8700         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8701           return false;
8702
8703       return true;
8704     };
8705     auto tryToWidenViaDuplication = [&]() -> SDValue {
8706       if (!canWidenViaDuplication(Mask))
8707         return SDValue();
8708       SmallVector<int, 4> LoInputs;
8709       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8710                    [](int M) { return M >= 0 && M < 8; });
8711       std::sort(LoInputs.begin(), LoInputs.end());
8712       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8713                      LoInputs.end());
8714       SmallVector<int, 4> HiInputs;
8715       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8716                    [](int M) { return M >= 8; });
8717       std::sort(HiInputs.begin(), HiInputs.end());
8718       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8719                      HiInputs.end());
8720
8721       bool TargetLo = LoInputs.size() >= HiInputs.size();
8722       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8723       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8724
8725       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8726       SmallDenseMap<int, int, 8> LaneMap;
8727       for (int I : InPlaceInputs) {
8728         PreDupI16Shuffle[I/2] = I/2;
8729         LaneMap[I] = I;
8730       }
8731       int j = TargetLo ? 0 : 4, je = j + 4;
8732       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8733         // Check if j is already a shuffle of this input. This happens when
8734         // there are two adjacent bytes after we move the low one.
8735         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8736           // If we haven't yet mapped the input, search for a slot into which
8737           // we can map it.
8738           while (j < je && PreDupI16Shuffle[j] != -1)
8739             ++j;
8740
8741           if (j == je)
8742             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8743             return SDValue();
8744
8745           // Map this input with the i16 shuffle.
8746           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8747         }
8748
8749         // Update the lane map based on the mapping we ended up with.
8750         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8751       }
8752       V1 = DAG.getNode(
8753           ISD::BITCAST, DL, MVT::v16i8,
8754           DAG.getVectorShuffle(MVT::v8i16, DL,
8755                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8756                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8757
8758       // Unpack the bytes to form the i16s that will be shuffled into place.
8759       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8760                        MVT::v16i8, V1, V1);
8761
8762       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8763       for (int i = 0; i < 16; ++i)
8764         if (Mask[i] != -1) {
8765           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8766           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8767           if (PostDupI16Shuffle[i / 2] == -1)
8768             PostDupI16Shuffle[i / 2] = MappedMask;
8769           else
8770             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8771                    "Conflicting entrties in the original shuffle!");
8772         }
8773       return DAG.getNode(
8774           ISD::BITCAST, DL, MVT::v16i8,
8775           DAG.getVectorShuffle(MVT::v8i16, DL,
8776                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8777                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8778     };
8779     if (SDValue V = tryToWidenViaDuplication())
8780       return V;
8781   }
8782
8783   // Use dedicated unpack instructions for masks that match their pattern.
8784   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8785                                          0, 16, 1, 17, 2, 18, 3, 19,
8786                                          // High half.
8787                                          4, 20, 5, 21, 6, 22, 7, 23}))
8788     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8789   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8790                                          8, 24, 9, 25, 10, 26, 11, 27,
8791                                          // High half.
8792                                          12, 28, 13, 29, 14, 30, 15, 31}))
8793     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8794
8795   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8796   // with PSHUFB. It is important to do this before we attempt to generate any
8797   // blends but after all of the single-input lowerings. If the single input
8798   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8799   // want to preserve that and we can DAG combine any longer sequences into
8800   // a PSHUFB in the end. But once we start blending from multiple inputs,
8801   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8802   // and there are *very* few patterns that would actually be faster than the
8803   // PSHUFB approach because of its ability to zero lanes.
8804   //
8805   // FIXME: The only exceptions to the above are blends which are exact
8806   // interleavings with direct instructions supporting them. We currently don't
8807   // handle those well here.
8808   if (Subtarget->hasSSSE3()) {
8809     bool V1InUse = false;
8810     bool V2InUse = false;
8811
8812     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8813                                                 DAG, V1InUse, V2InUse);
8814
8815     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8816     // do so. This avoids using them to handle blends-with-zero which is
8817     // important as a single pshufb is significantly faster for that.
8818     if (V1InUse && V2InUse) {
8819       if (Subtarget->hasSSE41())
8820         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8821                                                       Mask, Subtarget, DAG))
8822           return Blend;
8823
8824       // We can use an unpack to do the blending rather than an or in some
8825       // cases. Even though the or may be (very minorly) more efficient, we
8826       // preference this lowering because there are common cases where part of
8827       // the complexity of the shuffles goes away when we do the final blend as
8828       // an unpack.
8829       // FIXME: It might be worth trying to detect if the unpack-feeding
8830       // shuffles will both be pshufb, in which case we shouldn't bother with
8831       // this.
8832       if (SDValue Unpack =
8833               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8834         return Unpack;
8835     }
8836
8837     return PSHUFB;
8838   }
8839
8840   // There are special ways we can lower some single-element blends.
8841   if (NumV2Elements == 1)
8842     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8843                                                          Mask, Subtarget, DAG))
8844       return V;
8845
8846   if (SDValue BitBlend =
8847           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8848     return BitBlend;
8849
8850   // Check whether a compaction lowering can be done. This handles shuffles
8851   // which take every Nth element for some even N. See the helper function for
8852   // details.
8853   //
8854   // We special case these as they can be particularly efficiently handled with
8855   // the PACKUSB instruction on x86 and they show up in common patterns of
8856   // rearranging bytes to truncate wide elements.
8857   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8858     // NumEvenDrops is the power of two stride of the elements. Another way of
8859     // thinking about it is that we need to drop the even elements this many
8860     // times to get the original input.
8861     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8862
8863     // First we need to zero all the dropped bytes.
8864     assert(NumEvenDrops <= 3 &&
8865            "No support for dropping even elements more than 3 times.");
8866     // We use the mask type to pick which bytes are preserved based on how many
8867     // elements are dropped.
8868     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8869     SDValue ByteClearMask =
8870         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8871                     DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8872     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8873     if (!IsSingleInput)
8874       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8875
8876     // Now pack things back together.
8877     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8878     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8879     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8880     for (int i = 1; i < NumEvenDrops; ++i) {
8881       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8882       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8883     }
8884
8885     return Result;
8886   }
8887
8888   // Handle multi-input cases by blending single-input shuffles.
8889   if (NumV2Elements > 0)
8890     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8891                                                       Mask, DAG);
8892
8893   // The fallback path for single-input shuffles widens this into two v8i16
8894   // vectors with unpacks, shuffles those, and then pulls them back together
8895   // with a pack.
8896   SDValue V = V1;
8897
8898   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8899   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8900   for (int i = 0; i < 16; ++i)
8901     if (Mask[i] >= 0)
8902       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8903
8904   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8905
8906   SDValue VLoHalf, VHiHalf;
8907   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8908   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8909   // i16s.
8910   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8911                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8912       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8913                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8914     // Use a mask to drop the high bytes.
8915     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8916     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8917                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8918
8919     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8920     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8921
8922     // Squash the masks to point directly into VLoHalf.
8923     for (int &M : LoBlendMask)
8924       if (M >= 0)
8925         M /= 2;
8926     for (int &M : HiBlendMask)
8927       if (M >= 0)
8928         M /= 2;
8929   } else {
8930     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8931     // VHiHalf so that we can blend them as i16s.
8932     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8933                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8934     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8935                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8936   }
8937
8938   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8939   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8940
8941   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8942 }
8943
8944 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8945 ///
8946 /// This routine breaks down the specific type of 128-bit shuffle and
8947 /// dispatches to the lowering routines accordingly.
8948 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8949                                         MVT VT, const X86Subtarget *Subtarget,
8950                                         SelectionDAG &DAG) {
8951   switch (VT.SimpleTy) {
8952   case MVT::v2i64:
8953     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8954   case MVT::v2f64:
8955     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8956   case MVT::v4i32:
8957     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8958   case MVT::v4f32:
8959     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8960   case MVT::v8i16:
8961     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8962   case MVT::v16i8:
8963     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8964
8965   default:
8966     llvm_unreachable("Unimplemented!");
8967   }
8968 }
8969
8970 /// \brief Helper function to test whether a shuffle mask could be
8971 /// simplified by widening the elements being shuffled.
8972 ///
8973 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8974 /// leaves it in an unspecified state.
8975 ///
8976 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8977 /// shuffle masks. The latter have the special property of a '-2' representing
8978 /// a zero-ed lane of a vector.
8979 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8980                                     SmallVectorImpl<int> &WidenedMask) {
8981   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8982     // If both elements are undef, its trivial.
8983     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8984       WidenedMask.push_back(SM_SentinelUndef);
8985       continue;
8986     }
8987
8988     // Check for an undef mask and a mask value properly aligned to fit with
8989     // a pair of values. If we find such a case, use the non-undef mask's value.
8990     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8991       WidenedMask.push_back(Mask[i + 1] / 2);
8992       continue;
8993     }
8994     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8995       WidenedMask.push_back(Mask[i] / 2);
8996       continue;
8997     }
8998
8999     // When zeroing, we need to spread the zeroing across both lanes to widen.
9000     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9001       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9002           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9003         WidenedMask.push_back(SM_SentinelZero);
9004         continue;
9005       }
9006       return false;
9007     }
9008
9009     // Finally check if the two mask values are adjacent and aligned with
9010     // a pair.
9011     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9012       WidenedMask.push_back(Mask[i] / 2);
9013       continue;
9014     }
9015
9016     // Otherwise we can't safely widen the elements used in this shuffle.
9017     return false;
9018   }
9019   assert(WidenedMask.size() == Mask.size() / 2 &&
9020          "Incorrect size of mask after widening the elements!");
9021
9022   return true;
9023 }
9024
9025 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9026 ///
9027 /// This routine just extracts two subvectors, shuffles them independently, and
9028 /// then concatenates them back together. This should work effectively with all
9029 /// AVX vector shuffle types.
9030 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9031                                           SDValue V2, ArrayRef<int> Mask,
9032                                           SelectionDAG &DAG) {
9033   assert(VT.getSizeInBits() >= 256 &&
9034          "Only for 256-bit or wider vector shuffles!");
9035   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9036   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9037
9038   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9039   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9040
9041   int NumElements = VT.getVectorNumElements();
9042   int SplitNumElements = NumElements / 2;
9043   MVT ScalarVT = VT.getScalarType();
9044   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9045
9046   // Rather than splitting build-vectors, just build two narrower build
9047   // vectors. This helps shuffling with splats and zeros.
9048   auto SplitVector = [&](SDValue V) {
9049     while (V.getOpcode() == ISD::BITCAST)
9050       V = V->getOperand(0);
9051
9052     MVT OrigVT = V.getSimpleValueType();
9053     int OrigNumElements = OrigVT.getVectorNumElements();
9054     int OrigSplitNumElements = OrigNumElements / 2;
9055     MVT OrigScalarVT = OrigVT.getScalarType();
9056     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9057
9058     SDValue LoV, HiV;
9059
9060     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9061     if (!BV) {
9062       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9063                         DAG.getIntPtrConstant(0, DL));
9064       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9065                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9066     } else {
9067
9068       SmallVector<SDValue, 16> LoOps, HiOps;
9069       for (int i = 0; i < OrigSplitNumElements; ++i) {
9070         LoOps.push_back(BV->getOperand(i));
9071         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9072       }
9073       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9074       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9075     }
9076     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9077                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9078   };
9079
9080   SDValue LoV1, HiV1, LoV2, HiV2;
9081   std::tie(LoV1, HiV1) = SplitVector(V1);
9082   std::tie(LoV2, HiV2) = SplitVector(V2);
9083
9084   // Now create two 4-way blends of these half-width vectors.
9085   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9086     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9087     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9088     for (int i = 0; i < SplitNumElements; ++i) {
9089       int M = HalfMask[i];
9090       if (M >= NumElements) {
9091         if (M >= NumElements + SplitNumElements)
9092           UseHiV2 = true;
9093         else
9094           UseLoV2 = true;
9095         V2BlendMask.push_back(M - NumElements);
9096         V1BlendMask.push_back(-1);
9097         BlendMask.push_back(SplitNumElements + i);
9098       } else if (M >= 0) {
9099         if (M >= SplitNumElements)
9100           UseHiV1 = true;
9101         else
9102           UseLoV1 = true;
9103         V2BlendMask.push_back(-1);
9104         V1BlendMask.push_back(M);
9105         BlendMask.push_back(i);
9106       } else {
9107         V2BlendMask.push_back(-1);
9108         V1BlendMask.push_back(-1);
9109         BlendMask.push_back(-1);
9110       }
9111     }
9112
9113     // Because the lowering happens after all combining takes place, we need to
9114     // manually combine these blend masks as much as possible so that we create
9115     // a minimal number of high-level vector shuffle nodes.
9116
9117     // First try just blending the halves of V1 or V2.
9118     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9119       return DAG.getUNDEF(SplitVT);
9120     if (!UseLoV2 && !UseHiV2)
9121       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9122     if (!UseLoV1 && !UseHiV1)
9123       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9124
9125     SDValue V1Blend, V2Blend;
9126     if (UseLoV1 && UseHiV1) {
9127       V1Blend =
9128         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9129     } else {
9130       // We only use half of V1 so map the usage down into the final blend mask.
9131       V1Blend = UseLoV1 ? LoV1 : HiV1;
9132       for (int i = 0; i < SplitNumElements; ++i)
9133         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9134           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9135     }
9136     if (UseLoV2 && UseHiV2) {
9137       V2Blend =
9138         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9139     } else {
9140       // We only use half of V2 so map the usage down into the final blend mask.
9141       V2Blend = UseLoV2 ? LoV2 : HiV2;
9142       for (int i = 0; i < SplitNumElements; ++i)
9143         if (BlendMask[i] >= SplitNumElements)
9144           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9145     }
9146     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9147   };
9148   SDValue Lo = HalfBlend(LoMask);
9149   SDValue Hi = HalfBlend(HiMask);
9150   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9151 }
9152
9153 /// \brief Either split a vector in halves or decompose the shuffles and the
9154 /// blend.
9155 ///
9156 /// This is provided as a good fallback for many lowerings of non-single-input
9157 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9158 /// between splitting the shuffle into 128-bit components and stitching those
9159 /// back together vs. extracting the single-input shuffles and blending those
9160 /// results.
9161 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9162                                                 SDValue V2, ArrayRef<int> Mask,
9163                                                 SelectionDAG &DAG) {
9164   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9165                                             "lower single-input shuffles as it "
9166                                             "could then recurse on itself.");
9167   int Size = Mask.size();
9168
9169   // If this can be modeled as a broadcast of two elements followed by a blend,
9170   // prefer that lowering. This is especially important because broadcasts can
9171   // often fold with memory operands.
9172   auto DoBothBroadcast = [&] {
9173     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9174     for (int M : Mask)
9175       if (M >= Size) {
9176         if (V2BroadcastIdx == -1)
9177           V2BroadcastIdx = M - Size;
9178         else if (M - Size != V2BroadcastIdx)
9179           return false;
9180       } else if (M >= 0) {
9181         if (V1BroadcastIdx == -1)
9182           V1BroadcastIdx = M;
9183         else if (M != V1BroadcastIdx)
9184           return false;
9185       }
9186     return true;
9187   };
9188   if (DoBothBroadcast())
9189     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9190                                                       DAG);
9191
9192   // If the inputs all stem from a single 128-bit lane of each input, then we
9193   // split them rather than blending because the split will decompose to
9194   // unusually few instructions.
9195   int LaneCount = VT.getSizeInBits() / 128;
9196   int LaneSize = Size / LaneCount;
9197   SmallBitVector LaneInputs[2];
9198   LaneInputs[0].resize(LaneCount, false);
9199   LaneInputs[1].resize(LaneCount, false);
9200   for (int i = 0; i < Size; ++i)
9201     if (Mask[i] >= 0)
9202       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9203   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9204     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9205
9206   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9207   // that the decomposed single-input shuffles don't end up here.
9208   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9209 }
9210
9211 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9212 /// a permutation and blend of those lanes.
9213 ///
9214 /// This essentially blends the out-of-lane inputs to each lane into the lane
9215 /// from a permuted copy of the vector. This lowering strategy results in four
9216 /// instructions in the worst case for a single-input cross lane shuffle which
9217 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9218 /// of. Special cases for each particular shuffle pattern should be handled
9219 /// prior to trying this lowering.
9220 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9221                                                        SDValue V1, SDValue V2,
9222                                                        ArrayRef<int> Mask,
9223                                                        SelectionDAG &DAG) {
9224   // FIXME: This should probably be generalized for 512-bit vectors as well.
9225   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9226   int LaneSize = Mask.size() / 2;
9227
9228   // If there are only inputs from one 128-bit lane, splitting will in fact be
9229   // less expensive. The flags track whether the given lane contains an element
9230   // that crosses to another lane.
9231   bool LaneCrossing[2] = {false, false};
9232   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9233     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9234       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9235   if (!LaneCrossing[0] || !LaneCrossing[1])
9236     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9237
9238   if (isSingleInputShuffleMask(Mask)) {
9239     SmallVector<int, 32> FlippedBlendMask;
9240     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9241       FlippedBlendMask.push_back(
9242           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9243                                   ? Mask[i]
9244                                   : Mask[i] % LaneSize +
9245                                         (i / LaneSize) * LaneSize + Size));
9246
9247     // Flip the vector, and blend the results which should now be in-lane. The
9248     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9249     // 5 for the high source. The value 3 selects the high half of source 2 and
9250     // the value 2 selects the low half of source 2. We only use source 2 to
9251     // allow folding it into a memory operand.
9252     unsigned PERMMask = 3 | 2 << 4;
9253     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9254                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9255     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9256   }
9257
9258   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9259   // will be handled by the above logic and a blend of the results, much like
9260   // other patterns in AVX.
9261   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9262 }
9263
9264 /// \brief Handle lowering 2-lane 128-bit shuffles.
9265 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9266                                         SDValue V2, ArrayRef<int> Mask,
9267                                         const X86Subtarget *Subtarget,
9268                                         SelectionDAG &DAG) {
9269   // TODO: If minimizing size and one of the inputs is a zero vector and the
9270   // the zero vector has only one use, we could use a VPERM2X128 to save the
9271   // instruction bytes needed to explicitly generate the zero vector.
9272
9273   // Blends are faster and handle all the non-lane-crossing cases.
9274   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9275                                                 Subtarget, DAG))
9276     return Blend;
9277
9278   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9279   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9280
9281   // If either input operand is a zero vector, use VPERM2X128 because its mask
9282   // allows us to replace the zero input with an implicit zero.
9283   if (!IsV1Zero && !IsV2Zero) {
9284     // Check for patterns which can be matched with a single insert of a 128-bit
9285     // subvector.
9286     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9287     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9288       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9289                                    VT.getVectorNumElements() / 2);
9290       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9291                                 DAG.getIntPtrConstant(0, DL));
9292       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9293                                 OnlyUsesV1 ? V1 : V2,
9294                                 DAG.getIntPtrConstant(0, DL));
9295       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9296     }
9297   }
9298
9299   // Otherwise form a 128-bit permutation. After accounting for undefs,
9300   // convert the 64-bit shuffle mask selection values into 128-bit
9301   // selection bits by dividing the indexes by 2 and shifting into positions
9302   // defined by a vperm2*128 instruction's immediate control byte.
9303
9304   // The immediate permute control byte looks like this:
9305   //    [1:0] - select 128 bits from sources for low half of destination
9306   //    [2]   - ignore
9307   //    [3]   - zero low half of destination
9308   //    [5:4] - select 128 bits from sources for high half of destination
9309   //    [6]   - ignore
9310   //    [7]   - zero high half of destination
9311
9312   int MaskLO = Mask[0];
9313   if (MaskLO == SM_SentinelUndef)
9314     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9315
9316   int MaskHI = Mask[2];
9317   if (MaskHI == SM_SentinelUndef)
9318     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9319
9320   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9321
9322   // If either input is a zero vector, replace it with an undef input.
9323   // Shuffle mask values <  4 are selecting elements of V1.
9324   // Shuffle mask values >= 4 are selecting elements of V2.
9325   // Adjust each half of the permute mask by clearing the half that was
9326   // selecting the zero vector and setting the zero mask bit.
9327   if (IsV1Zero) {
9328     V1 = DAG.getUNDEF(VT);
9329     if (MaskLO < 4)
9330       PermMask = (PermMask & 0xf0) | 0x08;
9331     if (MaskHI < 4)
9332       PermMask = (PermMask & 0x0f) | 0x80;
9333   }
9334   if (IsV2Zero) {
9335     V2 = DAG.getUNDEF(VT);
9336     if (MaskLO >= 4)
9337       PermMask = (PermMask & 0xf0) | 0x08;
9338     if (MaskHI >= 4)
9339       PermMask = (PermMask & 0x0f) | 0x80;
9340   }
9341
9342   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9343                      DAG.getConstant(PermMask, DL, MVT::i8));
9344 }
9345
9346 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9347 /// shuffling each lane.
9348 ///
9349 /// This will only succeed when the result of fixing the 128-bit lanes results
9350 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9351 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9352 /// the lane crosses early and then use simpler shuffles within each lane.
9353 ///
9354 /// FIXME: It might be worthwhile at some point to support this without
9355 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9356 /// in x86 only floating point has interesting non-repeating shuffles, and even
9357 /// those are still *marginally* more expensive.
9358 static SDValue lowerVectorShuffleByMerging128BitLanes(
9359     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9360     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9361   assert(!isSingleInputShuffleMask(Mask) &&
9362          "This is only useful with multiple inputs.");
9363
9364   int Size = Mask.size();
9365   int LaneSize = 128 / VT.getScalarSizeInBits();
9366   int NumLanes = Size / LaneSize;
9367   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9368
9369   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9370   // check whether the in-128-bit lane shuffles share a repeating pattern.
9371   SmallVector<int, 4> Lanes;
9372   Lanes.resize(NumLanes, -1);
9373   SmallVector<int, 4> InLaneMask;
9374   InLaneMask.resize(LaneSize, -1);
9375   for (int i = 0; i < Size; ++i) {
9376     if (Mask[i] < 0)
9377       continue;
9378
9379     int j = i / LaneSize;
9380
9381     if (Lanes[j] < 0) {
9382       // First entry we've seen for this lane.
9383       Lanes[j] = Mask[i] / LaneSize;
9384     } else if (Lanes[j] != Mask[i] / LaneSize) {
9385       // This doesn't match the lane selected previously!
9386       return SDValue();
9387     }
9388
9389     // Check that within each lane we have a consistent shuffle mask.
9390     int k = i % LaneSize;
9391     if (InLaneMask[k] < 0) {
9392       InLaneMask[k] = Mask[i] % LaneSize;
9393     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9394       // This doesn't fit a repeating in-lane mask.
9395       return SDValue();
9396     }
9397   }
9398
9399   // First shuffle the lanes into place.
9400   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9401                                 VT.getSizeInBits() / 64);
9402   SmallVector<int, 8> LaneMask;
9403   LaneMask.resize(NumLanes * 2, -1);
9404   for (int i = 0; i < NumLanes; ++i)
9405     if (Lanes[i] >= 0) {
9406       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9407       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9408     }
9409
9410   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9411   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9412   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9413
9414   // Cast it back to the type we actually want.
9415   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9416
9417   // Now do a simple shuffle that isn't lane crossing.
9418   SmallVector<int, 8> NewMask;
9419   NewMask.resize(Size, -1);
9420   for (int i = 0; i < Size; ++i)
9421     if (Mask[i] >= 0)
9422       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9423   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9424          "Must not introduce lane crosses at this point!");
9425
9426   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9427 }
9428
9429 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9430 /// given mask.
9431 ///
9432 /// This returns true if the elements from a particular input are already in the
9433 /// slot required by the given mask and require no permutation.
9434 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9435   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9436   int Size = Mask.size();
9437   for (int i = 0; i < Size; ++i)
9438     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9439       return false;
9440
9441   return true;
9442 }
9443
9444 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9445 ///
9446 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9447 /// isn't available.
9448 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9449                                        const X86Subtarget *Subtarget,
9450                                        SelectionDAG &DAG) {
9451   SDLoc DL(Op);
9452   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9453   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9454   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9455   ArrayRef<int> Mask = SVOp->getMask();
9456   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9457
9458   SmallVector<int, 4> WidenedMask;
9459   if (canWidenShuffleElements(Mask, WidenedMask))
9460     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9461                                     DAG);
9462
9463   if (isSingleInputShuffleMask(Mask)) {
9464     // Check for being able to broadcast a single element.
9465     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9466                                                           Mask, Subtarget, DAG))
9467       return Broadcast;
9468
9469     // Use low duplicate instructions for masks that match their pattern.
9470     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9471       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9472
9473     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9474       // Non-half-crossing single input shuffles can be lowerid with an
9475       // interleaved permutation.
9476       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9477                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9478       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9479                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9480     }
9481
9482     // With AVX2 we have direct support for this permutation.
9483     if (Subtarget->hasAVX2())
9484       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9485                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9486
9487     // Otherwise, fall back.
9488     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9489                                                    DAG);
9490   }
9491
9492   // X86 has dedicated unpack instructions that can handle specific blend
9493   // operations: UNPCKH and UNPCKL.
9494   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9495     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9496   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9497     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9498   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9499     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9500   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9501     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9502
9503   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9504                                                 Subtarget, DAG))
9505     return Blend;
9506
9507   // Check if the blend happens to exactly fit that of SHUFPD.
9508   if ((Mask[0] == -1 || Mask[0] < 2) &&
9509       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9510       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9511       (Mask[3] == -1 || Mask[3] >= 6)) {
9512     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9513                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9514     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9515                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9516   }
9517   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9518       (Mask[1] == -1 || Mask[1] < 2) &&
9519       (Mask[2] == -1 || Mask[2] >= 6) &&
9520       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9521     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9522                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9523     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9524                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9525   }
9526
9527   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9528   // shuffle. However, if we have AVX2 and either inputs are already in place,
9529   // we will be able to shuffle even across lanes the other input in a single
9530   // instruction so skip this pattern.
9531   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9532                                  isShuffleMaskInputInPlace(1, Mask))))
9533     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9534             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9535       return Result;
9536
9537   // If we have AVX2 then we always want to lower with a blend because an v4 we
9538   // can fully permute the elements.
9539   if (Subtarget->hasAVX2())
9540     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9541                                                       Mask, DAG);
9542
9543   // Otherwise fall back on generic lowering.
9544   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9545 }
9546
9547 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9548 ///
9549 /// This routine is only called when we have AVX2 and thus a reasonable
9550 /// instruction set for v4i64 shuffling..
9551 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9552                                        const X86Subtarget *Subtarget,
9553                                        SelectionDAG &DAG) {
9554   SDLoc DL(Op);
9555   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9556   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9557   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9558   ArrayRef<int> Mask = SVOp->getMask();
9559   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9560   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9561
9562   SmallVector<int, 4> WidenedMask;
9563   if (canWidenShuffleElements(Mask, WidenedMask))
9564     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9565                                     DAG);
9566
9567   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9568                                                 Subtarget, DAG))
9569     return Blend;
9570
9571   // Check for being able to broadcast a single element.
9572   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9573                                                         Mask, Subtarget, DAG))
9574     return Broadcast;
9575
9576   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9577   // use lower latency instructions that will operate on both 128-bit lanes.
9578   SmallVector<int, 2> RepeatedMask;
9579   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9580     if (isSingleInputShuffleMask(Mask)) {
9581       int PSHUFDMask[] = {-1, -1, -1, -1};
9582       for (int i = 0; i < 2; ++i)
9583         if (RepeatedMask[i] >= 0) {
9584           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9585           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9586         }
9587       return DAG.getNode(
9588           ISD::BITCAST, DL, MVT::v4i64,
9589           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9590                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9591                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9592     }
9593   }
9594
9595   // AVX2 provides a direct instruction for permuting a single input across
9596   // lanes.
9597   if (isSingleInputShuffleMask(Mask))
9598     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9599                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9600
9601   // Try to use shift instructions.
9602   if (SDValue Shift =
9603           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9604     return Shift;
9605
9606   // Use dedicated unpack instructions for masks that match their pattern.
9607   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9608     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9609   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9610     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9611   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9612     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9613   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9614     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9615
9616   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9617   // shuffle. However, if we have AVX2 and either inputs are already in place,
9618   // we will be able to shuffle even across lanes the other input in a single
9619   // instruction so skip this pattern.
9620   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9621                                  isShuffleMaskInputInPlace(1, Mask))))
9622     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9623             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9624       return Result;
9625
9626   // Otherwise fall back on generic blend lowering.
9627   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9628                                                     Mask, DAG);
9629 }
9630
9631 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9632 ///
9633 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9634 /// isn't available.
9635 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9636                                        const X86Subtarget *Subtarget,
9637                                        SelectionDAG &DAG) {
9638   SDLoc DL(Op);
9639   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9640   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9641   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9642   ArrayRef<int> Mask = SVOp->getMask();
9643   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9644
9645   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9646                                                 Subtarget, DAG))
9647     return Blend;
9648
9649   // Check for being able to broadcast a single element.
9650   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9651                                                         Mask, Subtarget, DAG))
9652     return Broadcast;
9653
9654   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9655   // options to efficiently lower the shuffle.
9656   SmallVector<int, 4> RepeatedMask;
9657   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9658     assert(RepeatedMask.size() == 4 &&
9659            "Repeated masks must be half the mask width!");
9660
9661     // Use even/odd duplicate instructions for masks that match their pattern.
9662     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9663       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9664     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9665       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9666
9667     if (isSingleInputShuffleMask(Mask))
9668       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9669                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9670
9671     // Use dedicated unpack instructions for masks that match their pattern.
9672     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9673       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9674     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9675       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9676     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9677       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9678     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9679       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9680
9681     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9682     // have already handled any direct blends. We also need to squash the
9683     // repeated mask into a simulated v4f32 mask.
9684     for (int i = 0; i < 4; ++i)
9685       if (RepeatedMask[i] >= 8)
9686         RepeatedMask[i] -= 4;
9687     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9688   }
9689
9690   // If we have a single input shuffle with different shuffle patterns in the
9691   // two 128-bit lanes use the variable mask to VPERMILPS.
9692   if (isSingleInputShuffleMask(Mask)) {
9693     SDValue VPermMask[8];
9694     for (int i = 0; i < 8; ++i)
9695       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9696                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9697     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9698       return DAG.getNode(
9699           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9700           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9701
9702     if (Subtarget->hasAVX2())
9703       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9704                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9705                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9706                                                  MVT::v8i32, VPermMask)),
9707                          V1);
9708
9709     // Otherwise, fall back.
9710     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9711                                                    DAG);
9712   }
9713
9714   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9715   // shuffle.
9716   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9717           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9718     return Result;
9719
9720   // If we have AVX2 then we always want to lower with a blend because at v8 we
9721   // can fully permute the elements.
9722   if (Subtarget->hasAVX2())
9723     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9724                                                       Mask, DAG);
9725
9726   // Otherwise fall back on generic lowering.
9727   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9728 }
9729
9730 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9731 ///
9732 /// This routine is only called when we have AVX2 and thus a reasonable
9733 /// instruction set for v8i32 shuffling..
9734 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9735                                        const X86Subtarget *Subtarget,
9736                                        SelectionDAG &DAG) {
9737   SDLoc DL(Op);
9738   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9739   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9740   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9741   ArrayRef<int> Mask = SVOp->getMask();
9742   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9743   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9744
9745   // Whenever we can lower this as a zext, that instruction is strictly faster
9746   // than any alternative. It also allows us to fold memory operands into the
9747   // shuffle in many cases.
9748   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9749                                                          Mask, Subtarget, DAG))
9750     return ZExt;
9751
9752   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9753                                                 Subtarget, DAG))
9754     return Blend;
9755
9756   // Check for being able to broadcast a single element.
9757   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9758                                                         Mask, Subtarget, DAG))
9759     return Broadcast;
9760
9761   // If the shuffle mask is repeated in each 128-bit lane we can use more
9762   // efficient instructions that mirror the shuffles across the two 128-bit
9763   // lanes.
9764   SmallVector<int, 4> RepeatedMask;
9765   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9766     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9767     if (isSingleInputShuffleMask(Mask))
9768       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9769                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9770
9771     // Use dedicated unpack instructions for masks that match their pattern.
9772     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9773       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9774     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9775       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9776     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9777       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9778     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9779       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9780   }
9781
9782   // Try to use shift instructions.
9783   if (SDValue Shift =
9784           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9785     return Shift;
9786
9787   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9788           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9789     return Rotate;
9790
9791   // If the shuffle patterns aren't repeated but it is a single input, directly
9792   // generate a cross-lane VPERMD instruction.
9793   if (isSingleInputShuffleMask(Mask)) {
9794     SDValue VPermMask[8];
9795     for (int i = 0; i < 8; ++i)
9796       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9797                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9798     return DAG.getNode(
9799         X86ISD::VPERMV, DL, MVT::v8i32,
9800         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9801   }
9802
9803   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9804   // shuffle.
9805   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9806           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9807     return Result;
9808
9809   // Otherwise fall back on generic blend lowering.
9810   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9811                                                     Mask, DAG);
9812 }
9813
9814 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9815 ///
9816 /// This routine is only called when we have AVX2 and thus a reasonable
9817 /// instruction set for v16i16 shuffling..
9818 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9819                                         const X86Subtarget *Subtarget,
9820                                         SelectionDAG &DAG) {
9821   SDLoc DL(Op);
9822   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9823   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9824   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9825   ArrayRef<int> Mask = SVOp->getMask();
9826   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9827   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9828
9829   // Whenever we can lower this as a zext, that instruction is strictly faster
9830   // than any alternative. It also allows us to fold memory operands into the
9831   // shuffle in many cases.
9832   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9833                                                          Mask, Subtarget, DAG))
9834     return ZExt;
9835
9836   // Check for being able to broadcast a single element.
9837   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9838                                                         Mask, Subtarget, DAG))
9839     return Broadcast;
9840
9841   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9842                                                 Subtarget, DAG))
9843     return Blend;
9844
9845   // Use dedicated unpack instructions for masks that match their pattern.
9846   if (isShuffleEquivalent(V1, V2, Mask,
9847                           {// First 128-bit lane:
9848                            0, 16, 1, 17, 2, 18, 3, 19,
9849                            // Second 128-bit lane:
9850                            8, 24, 9, 25, 10, 26, 11, 27}))
9851     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9852   if (isShuffleEquivalent(V1, V2, Mask,
9853                           {// First 128-bit lane:
9854                            4, 20, 5, 21, 6, 22, 7, 23,
9855                            // Second 128-bit lane:
9856                            12, 28, 13, 29, 14, 30, 15, 31}))
9857     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9858
9859   // Try to use shift instructions.
9860   if (SDValue Shift =
9861           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9862     return Shift;
9863
9864   // Try to use byte rotation instructions.
9865   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9866           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9867     return Rotate;
9868
9869   if (isSingleInputShuffleMask(Mask)) {
9870     // There are no generalized cross-lane shuffle operations available on i16
9871     // element types.
9872     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9873       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9874                                                      Mask, DAG);
9875
9876     SmallVector<int, 8> RepeatedMask;
9877     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9878       // As this is a single-input shuffle, the repeated mask should be
9879       // a strictly valid v8i16 mask that we can pass through to the v8i16
9880       // lowering to handle even the v16 case.
9881       return lowerV8I16GeneralSingleInputVectorShuffle(
9882           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9883     }
9884
9885     SDValue PSHUFBMask[32];
9886     for (int i = 0; i < 16; ++i) {
9887       if (Mask[i] == -1) {
9888         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9889         continue;
9890       }
9891
9892       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9893       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9894       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9895       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9896     }
9897     return DAG.getNode(
9898         ISD::BITCAST, DL, MVT::v16i16,
9899         DAG.getNode(
9900             X86ISD::PSHUFB, DL, MVT::v32i8,
9901             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9902             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9903   }
9904
9905   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9906   // shuffle.
9907   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9908           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9909     return Result;
9910
9911   // Otherwise fall back on generic lowering.
9912   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9913 }
9914
9915 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9916 ///
9917 /// This routine is only called when we have AVX2 and thus a reasonable
9918 /// instruction set for v32i8 shuffling..
9919 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9920                                        const X86Subtarget *Subtarget,
9921                                        SelectionDAG &DAG) {
9922   SDLoc DL(Op);
9923   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9924   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9925   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9926   ArrayRef<int> Mask = SVOp->getMask();
9927   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9928   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9929
9930   // Whenever we can lower this as a zext, that instruction is strictly faster
9931   // than any alternative. It also allows us to fold memory operands into the
9932   // shuffle in many cases.
9933   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9934                                                          Mask, Subtarget, DAG))
9935     return ZExt;
9936
9937   // Check for being able to broadcast a single element.
9938   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9939                                                         Mask, Subtarget, DAG))
9940     return Broadcast;
9941
9942   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9943                                                 Subtarget, DAG))
9944     return Blend;
9945
9946   // Use dedicated unpack instructions for masks that match their pattern.
9947   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9948   // 256-bit lanes.
9949   if (isShuffleEquivalent(
9950           V1, V2, Mask,
9951           {// First 128-bit lane:
9952            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9953            // Second 128-bit lane:
9954            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9955     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9956   if (isShuffleEquivalent(
9957           V1, V2, Mask,
9958           {// First 128-bit lane:
9959            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9960            // Second 128-bit lane:
9961            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9962     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9963
9964   // Try to use shift instructions.
9965   if (SDValue Shift =
9966           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9967     return Shift;
9968
9969   // Try to use byte rotation instructions.
9970   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9971           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9972     return Rotate;
9973
9974   if (isSingleInputShuffleMask(Mask)) {
9975     // There are no generalized cross-lane shuffle operations available on i8
9976     // element types.
9977     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9978       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9979                                                      Mask, DAG);
9980
9981     SDValue PSHUFBMask[32];
9982     for (int i = 0; i < 32; ++i)
9983       PSHUFBMask[i] =
9984           Mask[i] < 0
9985               ? DAG.getUNDEF(MVT::i8)
9986               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9987                                 MVT::i8);
9988
9989     return DAG.getNode(
9990         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9991         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9992   }
9993
9994   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9995   // shuffle.
9996   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9997           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9998     return Result;
9999
10000   // Otherwise fall back on generic lowering.
10001   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10002 }
10003
10004 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10005 ///
10006 /// This routine either breaks down the specific type of a 256-bit x86 vector
10007 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10008 /// together based on the available instructions.
10009 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10010                                         MVT VT, const X86Subtarget *Subtarget,
10011                                         SelectionDAG &DAG) {
10012   SDLoc DL(Op);
10013   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10014   ArrayRef<int> Mask = SVOp->getMask();
10015
10016   // If we have a single input to the zero element, insert that into V1 if we
10017   // can do so cheaply.
10018   int NumElts = VT.getVectorNumElements();
10019   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10020     return M >= NumElts;
10021   });
10022
10023   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10024     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10025                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10026       return Insertion;
10027
10028   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10029   // check for those subtargets here and avoid much of the subtarget querying in
10030   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10031   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10032   // floating point types there eventually, just immediately cast everything to
10033   // a float and operate entirely in that domain.
10034   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10035     int ElementBits = VT.getScalarSizeInBits();
10036     if (ElementBits < 32)
10037       // No floating point type available, decompose into 128-bit vectors.
10038       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10039
10040     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10041                                 VT.getVectorNumElements());
10042     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10043     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10044     return DAG.getNode(ISD::BITCAST, DL, VT,
10045                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10046   }
10047
10048   switch (VT.SimpleTy) {
10049   case MVT::v4f64:
10050     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10051   case MVT::v4i64:
10052     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10053   case MVT::v8f32:
10054     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10055   case MVT::v8i32:
10056     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10057   case MVT::v16i16:
10058     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10059   case MVT::v32i8:
10060     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10061
10062   default:
10063     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10064   }
10065 }
10066
10067 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10068 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10069                                        const X86Subtarget *Subtarget,
10070                                        SelectionDAG &DAG) {
10071   SDLoc DL(Op);
10072   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10073   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10074   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10075   ArrayRef<int> Mask = SVOp->getMask();
10076   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10077
10078   // X86 has dedicated unpack instructions that can handle specific blend
10079   // operations: UNPCKH and UNPCKL.
10080   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10081     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10082   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10083     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10084
10085   // FIXME: Implement direct support for this type!
10086   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10087 }
10088
10089 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10090 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10091                                        const X86Subtarget *Subtarget,
10092                                        SelectionDAG &DAG) {
10093   SDLoc DL(Op);
10094   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10095   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10096   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10097   ArrayRef<int> Mask = SVOp->getMask();
10098   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10099
10100   // Use dedicated unpack instructions for masks that match their pattern.
10101   if (isShuffleEquivalent(V1, V2, Mask,
10102                           {// First 128-bit lane.
10103                            0, 16, 1, 17, 4, 20, 5, 21,
10104                            // Second 128-bit lane.
10105                            8, 24, 9, 25, 12, 28, 13, 29}))
10106     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10107   if (isShuffleEquivalent(V1, V2, Mask,
10108                           {// First 128-bit lane.
10109                            2, 18, 3, 19, 6, 22, 7, 23,
10110                            // Second 128-bit lane.
10111                            10, 26, 11, 27, 14, 30, 15, 31}))
10112     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10113
10114   // FIXME: Implement direct support for this type!
10115   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10116 }
10117
10118 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10119 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10120                                        const X86Subtarget *Subtarget,
10121                                        SelectionDAG &DAG) {
10122   SDLoc DL(Op);
10123   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10124   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10125   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10126   ArrayRef<int> Mask = SVOp->getMask();
10127   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10128
10129   // X86 has dedicated unpack instructions that can handle specific blend
10130   // operations: UNPCKH and UNPCKL.
10131   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10132     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10133   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10134     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10135
10136   // FIXME: Implement direct support for this type!
10137   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10138 }
10139
10140 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10141 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10142                                        const X86Subtarget *Subtarget,
10143                                        SelectionDAG &DAG) {
10144   SDLoc DL(Op);
10145   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10146   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10147   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10148   ArrayRef<int> Mask = SVOp->getMask();
10149   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10150
10151   // Use dedicated unpack instructions for masks that match their pattern.
10152   if (isShuffleEquivalent(V1, V2, Mask,
10153                           {// First 128-bit lane.
10154                            0, 16, 1, 17, 4, 20, 5, 21,
10155                            // Second 128-bit lane.
10156                            8, 24, 9, 25, 12, 28, 13, 29}))
10157     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10158   if (isShuffleEquivalent(V1, V2, Mask,
10159                           {// First 128-bit lane.
10160                            2, 18, 3, 19, 6, 22, 7, 23,
10161                            // Second 128-bit lane.
10162                            10, 26, 11, 27, 14, 30, 15, 31}))
10163     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10164
10165   // FIXME: Implement direct support for this type!
10166   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10167 }
10168
10169 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10170 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10171                                         const X86Subtarget *Subtarget,
10172                                         SelectionDAG &DAG) {
10173   SDLoc DL(Op);
10174   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10175   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10176   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10177   ArrayRef<int> Mask = SVOp->getMask();
10178   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10179   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10180
10181   // FIXME: Implement direct support for this type!
10182   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10183 }
10184
10185 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10186 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10187                                        const X86Subtarget *Subtarget,
10188                                        SelectionDAG &DAG) {
10189   SDLoc DL(Op);
10190   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10191   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10192   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10193   ArrayRef<int> Mask = SVOp->getMask();
10194   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10195   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10196
10197   // FIXME: Implement direct support for this type!
10198   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10199 }
10200
10201 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10202 ///
10203 /// This routine either breaks down the specific type of a 512-bit x86 vector
10204 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10205 /// together based on the available instructions.
10206 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10207                                         MVT VT, const X86Subtarget *Subtarget,
10208                                         SelectionDAG &DAG) {
10209   SDLoc DL(Op);
10210   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10211   ArrayRef<int> Mask = SVOp->getMask();
10212   assert(Subtarget->hasAVX512() &&
10213          "Cannot lower 512-bit vectors w/ basic ISA!");
10214
10215   // Check for being able to broadcast a single element.
10216   if (SDValue Broadcast =
10217           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10218     return Broadcast;
10219
10220   // Dispatch to each element type for lowering. If we don't have supprot for
10221   // specific element type shuffles at 512 bits, immediately split them and
10222   // lower them. Each lowering routine of a given type is allowed to assume that
10223   // the requisite ISA extensions for that element type are available.
10224   switch (VT.SimpleTy) {
10225   case MVT::v8f64:
10226     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10227   case MVT::v16f32:
10228     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10229   case MVT::v8i64:
10230     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10231   case MVT::v16i32:
10232     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10233   case MVT::v32i16:
10234     if (Subtarget->hasBWI())
10235       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10236     break;
10237   case MVT::v64i8:
10238     if (Subtarget->hasBWI())
10239       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10240     break;
10241
10242   default:
10243     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10244   }
10245
10246   // Otherwise fall back on splitting.
10247   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10248 }
10249
10250 /// \brief Top-level lowering for x86 vector shuffles.
10251 ///
10252 /// This handles decomposition, canonicalization, and lowering of all x86
10253 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10254 /// above in helper routines. The canonicalization attempts to widen shuffles
10255 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10256 /// s.t. only one of the two inputs needs to be tested, etc.
10257 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10258                                   SelectionDAG &DAG) {
10259   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10260   ArrayRef<int> Mask = SVOp->getMask();
10261   SDValue V1 = Op.getOperand(0);
10262   SDValue V2 = Op.getOperand(1);
10263   MVT VT = Op.getSimpleValueType();
10264   int NumElements = VT.getVectorNumElements();
10265   SDLoc dl(Op);
10266
10267   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10268
10269   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10270   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10271   if (V1IsUndef && V2IsUndef)
10272     return DAG.getUNDEF(VT);
10273
10274   // When we create a shuffle node we put the UNDEF node to second operand,
10275   // but in some cases the first operand may be transformed to UNDEF.
10276   // In this case we should just commute the node.
10277   if (V1IsUndef)
10278     return DAG.getCommutedVectorShuffle(*SVOp);
10279
10280   // Check for non-undef masks pointing at an undef vector and make the masks
10281   // undef as well. This makes it easier to match the shuffle based solely on
10282   // the mask.
10283   if (V2IsUndef)
10284     for (int M : Mask)
10285       if (M >= NumElements) {
10286         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10287         for (int &M : NewMask)
10288           if (M >= NumElements)
10289             M = -1;
10290         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10291       }
10292
10293   // We actually see shuffles that are entirely re-arrangements of a set of
10294   // zero inputs. This mostly happens while decomposing complex shuffles into
10295   // simple ones. Directly lower these as a buildvector of zeros.
10296   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10297   if (Zeroable.all())
10298     return getZeroVector(VT, Subtarget, DAG, dl);
10299
10300   // Try to collapse shuffles into using a vector type with fewer elements but
10301   // wider element types. We cap this to not form integers or floating point
10302   // elements wider than 64 bits, but it might be interesting to form i128
10303   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10304   SmallVector<int, 16> WidenedMask;
10305   if (VT.getScalarSizeInBits() < 64 &&
10306       canWidenShuffleElements(Mask, WidenedMask)) {
10307     MVT NewEltVT = VT.isFloatingPoint()
10308                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10309                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10310     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10311     // Make sure that the new vector type is legal. For example, v2f64 isn't
10312     // legal on SSE1.
10313     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10314       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10315       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10316       return DAG.getNode(ISD::BITCAST, dl, VT,
10317                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10318     }
10319   }
10320
10321   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10322   for (int M : SVOp->getMask())
10323     if (M < 0)
10324       ++NumUndefElements;
10325     else if (M < NumElements)
10326       ++NumV1Elements;
10327     else
10328       ++NumV2Elements;
10329
10330   // Commute the shuffle as needed such that more elements come from V1 than
10331   // V2. This allows us to match the shuffle pattern strictly on how many
10332   // elements come from V1 without handling the symmetric cases.
10333   if (NumV2Elements > NumV1Elements)
10334     return DAG.getCommutedVectorShuffle(*SVOp);
10335
10336   // When the number of V1 and V2 elements are the same, try to minimize the
10337   // number of uses of V2 in the low half of the vector. When that is tied,
10338   // ensure that the sum of indices for V1 is equal to or lower than the sum
10339   // indices for V2. When those are equal, try to ensure that the number of odd
10340   // indices for V1 is lower than the number of odd indices for V2.
10341   if (NumV1Elements == NumV2Elements) {
10342     int LowV1Elements = 0, LowV2Elements = 0;
10343     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10344       if (M >= NumElements)
10345         ++LowV2Elements;
10346       else if (M >= 0)
10347         ++LowV1Elements;
10348     if (LowV2Elements > LowV1Elements) {
10349       return DAG.getCommutedVectorShuffle(*SVOp);
10350     } else if (LowV2Elements == LowV1Elements) {
10351       int SumV1Indices = 0, SumV2Indices = 0;
10352       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10353         if (SVOp->getMask()[i] >= NumElements)
10354           SumV2Indices += i;
10355         else if (SVOp->getMask()[i] >= 0)
10356           SumV1Indices += i;
10357       if (SumV2Indices < SumV1Indices) {
10358         return DAG.getCommutedVectorShuffle(*SVOp);
10359       } else if (SumV2Indices == SumV1Indices) {
10360         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10361         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10362           if (SVOp->getMask()[i] >= NumElements)
10363             NumV2OddIndices += i % 2;
10364           else if (SVOp->getMask()[i] >= 0)
10365             NumV1OddIndices += i % 2;
10366         if (NumV2OddIndices < NumV1OddIndices)
10367           return DAG.getCommutedVectorShuffle(*SVOp);
10368       }
10369     }
10370   }
10371
10372   // For each vector width, delegate to a specialized lowering routine.
10373   if (VT.getSizeInBits() == 128)
10374     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10375
10376   if (VT.getSizeInBits() == 256)
10377     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10378
10379   // Force AVX-512 vectors to be scalarized for now.
10380   // FIXME: Implement AVX-512 support!
10381   if (VT.getSizeInBits() == 512)
10382     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10383
10384   llvm_unreachable("Unimplemented!");
10385 }
10386
10387 // This function assumes its argument is a BUILD_VECTOR of constants or
10388 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10389 // true.
10390 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10391                                     unsigned &MaskValue) {
10392   MaskValue = 0;
10393   unsigned NumElems = BuildVector->getNumOperands();
10394   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10395   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10396   unsigned NumElemsInLane = NumElems / NumLanes;
10397
10398   // Blend for v16i16 should be symetric for the both lanes.
10399   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10400     SDValue EltCond = BuildVector->getOperand(i);
10401     SDValue SndLaneEltCond =
10402         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10403
10404     int Lane1Cond = -1, Lane2Cond = -1;
10405     if (isa<ConstantSDNode>(EltCond))
10406       Lane1Cond = !isZero(EltCond);
10407     if (isa<ConstantSDNode>(SndLaneEltCond))
10408       Lane2Cond = !isZero(SndLaneEltCond);
10409
10410     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10411       // Lane1Cond != 0, means we want the first argument.
10412       // Lane1Cond == 0, means we want the second argument.
10413       // The encoding of this argument is 0 for the first argument, 1
10414       // for the second. Therefore, invert the condition.
10415       MaskValue |= !Lane1Cond << i;
10416     else if (Lane1Cond < 0)
10417       MaskValue |= !Lane2Cond << i;
10418     else
10419       return false;
10420   }
10421   return true;
10422 }
10423
10424 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10425 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10426                                            const X86Subtarget *Subtarget,
10427                                            SelectionDAG &DAG) {
10428   SDValue Cond = Op.getOperand(0);
10429   SDValue LHS = Op.getOperand(1);
10430   SDValue RHS = Op.getOperand(2);
10431   SDLoc dl(Op);
10432   MVT VT = Op.getSimpleValueType();
10433
10434   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10435     return SDValue();
10436   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10437
10438   // Only non-legal VSELECTs reach this lowering, convert those into generic
10439   // shuffles and re-use the shuffle lowering path for blends.
10440   SmallVector<int, 32> Mask;
10441   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10442     SDValue CondElt = CondBV->getOperand(i);
10443     Mask.push_back(
10444         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10445   }
10446   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10447 }
10448
10449 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10450   // A vselect where all conditions and data are constants can be optimized into
10451   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10452   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10453       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10454       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10455     return SDValue();
10456
10457   // Try to lower this to a blend-style vector shuffle. This can handle all
10458   // constant condition cases.
10459   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10460     return BlendOp;
10461
10462   // Variable blends are only legal from SSE4.1 onward.
10463   if (!Subtarget->hasSSE41())
10464     return SDValue();
10465
10466   // Only some types will be legal on some subtargets. If we can emit a legal
10467   // VSELECT-matching blend, return Op, and but if we need to expand, return
10468   // a null value.
10469   switch (Op.getSimpleValueType().SimpleTy) {
10470   default:
10471     // Most of the vector types have blends past SSE4.1.
10472     return Op;
10473
10474   case MVT::v32i8:
10475     // The byte blends for AVX vectors were introduced only in AVX2.
10476     if (Subtarget->hasAVX2())
10477       return Op;
10478
10479     return SDValue();
10480
10481   case MVT::v8i16:
10482   case MVT::v16i16:
10483     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10484     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10485       return Op;
10486
10487     // FIXME: We should custom lower this by fixing the condition and using i8
10488     // blends.
10489     return SDValue();
10490   }
10491 }
10492
10493 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10494   MVT VT = Op.getSimpleValueType();
10495   SDLoc dl(Op);
10496
10497   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10498     return SDValue();
10499
10500   if (VT.getSizeInBits() == 8) {
10501     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10502                                   Op.getOperand(0), Op.getOperand(1));
10503     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10504                                   DAG.getValueType(VT));
10505     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10506   }
10507
10508   if (VT.getSizeInBits() == 16) {
10509     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10510     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10511     if (Idx == 0)
10512       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10513                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10514                                      DAG.getNode(ISD::BITCAST, dl,
10515                                                  MVT::v4i32,
10516                                                  Op.getOperand(0)),
10517                                      Op.getOperand(1)));
10518     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10519                                   Op.getOperand(0), Op.getOperand(1));
10520     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10521                                   DAG.getValueType(VT));
10522     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10523   }
10524
10525   if (VT == MVT::f32) {
10526     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10527     // the result back to FR32 register. It's only worth matching if the
10528     // result has a single use which is a store or a bitcast to i32.  And in
10529     // the case of a store, it's not worth it if the index is a constant 0,
10530     // because a MOVSSmr can be used instead, which is smaller and faster.
10531     if (!Op.hasOneUse())
10532       return SDValue();
10533     SDNode *User = *Op.getNode()->use_begin();
10534     if ((User->getOpcode() != ISD::STORE ||
10535          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10536           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10537         (User->getOpcode() != ISD::BITCAST ||
10538          User->getValueType(0) != MVT::i32))
10539       return SDValue();
10540     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10541                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10542                                               Op.getOperand(0)),
10543                                               Op.getOperand(1));
10544     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10545   }
10546
10547   if (VT == MVT::i32 || VT == MVT::i64) {
10548     // ExtractPS/pextrq works with constant index.
10549     if (isa<ConstantSDNode>(Op.getOperand(1)))
10550       return Op;
10551   }
10552   return SDValue();
10553 }
10554
10555 /// Extract one bit from mask vector, like v16i1 or v8i1.
10556 /// AVX-512 feature.
10557 SDValue
10558 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10559   SDValue Vec = Op.getOperand(0);
10560   SDLoc dl(Vec);
10561   MVT VecVT = Vec.getSimpleValueType();
10562   SDValue Idx = Op.getOperand(1);
10563   MVT EltVT = Op.getSimpleValueType();
10564
10565   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10566   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10567          "Unexpected vector type in ExtractBitFromMaskVector");
10568
10569   // variable index can't be handled in mask registers,
10570   // extend vector to VR512
10571   if (!isa<ConstantSDNode>(Idx)) {
10572     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10573     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10574     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10575                               ExtVT.getVectorElementType(), Ext, Idx);
10576     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10577   }
10578
10579   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10580   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10581   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10582     rc = getRegClassFor(MVT::v16i1);
10583   unsigned MaxSift = rc->getSize()*8 - 1;
10584   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10585                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10586   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10587                     DAG.getConstant(MaxSift, dl, MVT::i8));
10588   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10589                        DAG.getIntPtrConstant(0, dl));
10590 }
10591
10592 SDValue
10593 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10594                                            SelectionDAG &DAG) const {
10595   SDLoc dl(Op);
10596   SDValue Vec = Op.getOperand(0);
10597   MVT VecVT = Vec.getSimpleValueType();
10598   SDValue Idx = Op.getOperand(1);
10599
10600   if (Op.getSimpleValueType() == MVT::i1)
10601     return ExtractBitFromMaskVector(Op, DAG);
10602
10603   if (!isa<ConstantSDNode>(Idx)) {
10604     if (VecVT.is512BitVector() ||
10605         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10606          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10607
10608       MVT MaskEltVT =
10609         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10610       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10611                                     MaskEltVT.getSizeInBits());
10612
10613       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10614       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10615                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10616                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10617       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10618       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10619                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10620     }
10621     return SDValue();
10622   }
10623
10624   // If this is a 256-bit vector result, first extract the 128-bit vector and
10625   // then extract the element from the 128-bit vector.
10626   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10627
10628     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10629     // Get the 128-bit vector.
10630     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10631     MVT EltVT = VecVT.getVectorElementType();
10632
10633     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10634
10635     //if (IdxVal >= NumElems/2)
10636     //  IdxVal -= NumElems/2;
10637     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10638     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10639                        DAG.getConstant(IdxVal, dl, MVT::i32));
10640   }
10641
10642   assert(VecVT.is128BitVector() && "Unexpected vector length");
10643
10644   if (Subtarget->hasSSE41()) {
10645     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10646     if (Res.getNode())
10647       return Res;
10648   }
10649
10650   MVT VT = Op.getSimpleValueType();
10651   // TODO: handle v16i8.
10652   if (VT.getSizeInBits() == 16) {
10653     SDValue Vec = Op.getOperand(0);
10654     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10655     if (Idx == 0)
10656       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10657                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10658                                      DAG.getNode(ISD::BITCAST, dl,
10659                                                  MVT::v4i32, Vec),
10660                                      Op.getOperand(1)));
10661     // Transform it so it match pextrw which produces a 32-bit result.
10662     MVT EltVT = MVT::i32;
10663     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10664                                   Op.getOperand(0), Op.getOperand(1));
10665     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10666                                   DAG.getValueType(VT));
10667     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10668   }
10669
10670   if (VT.getSizeInBits() == 32) {
10671     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10672     if (Idx == 0)
10673       return Op;
10674
10675     // SHUFPS the element to the lowest double word, then movss.
10676     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10677     MVT VVT = Op.getOperand(0).getSimpleValueType();
10678     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10679                                        DAG.getUNDEF(VVT), Mask);
10680     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10681                        DAG.getIntPtrConstant(0, dl));
10682   }
10683
10684   if (VT.getSizeInBits() == 64) {
10685     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10686     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10687     //        to match extract_elt for f64.
10688     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10689     if (Idx == 0)
10690       return Op;
10691
10692     // UNPCKHPD the element to the lowest double word, then movsd.
10693     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10694     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10695     int Mask[2] = { 1, -1 };
10696     MVT VVT = Op.getOperand(0).getSimpleValueType();
10697     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10698                                        DAG.getUNDEF(VVT), Mask);
10699     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10700                        DAG.getIntPtrConstant(0, dl));
10701   }
10702
10703   return SDValue();
10704 }
10705
10706 /// Insert one bit to mask vector, like v16i1 or v8i1.
10707 /// AVX-512 feature.
10708 SDValue
10709 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10710   SDLoc dl(Op);
10711   SDValue Vec = Op.getOperand(0);
10712   SDValue Elt = Op.getOperand(1);
10713   SDValue Idx = Op.getOperand(2);
10714   MVT VecVT = Vec.getSimpleValueType();
10715
10716   if (!isa<ConstantSDNode>(Idx)) {
10717     // Non constant index. Extend source and destination,
10718     // insert element and then truncate the result.
10719     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10720     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10721     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10722       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10723       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10724     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10725   }
10726
10727   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10728   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10729   if (IdxVal)
10730     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10731                            DAG.getConstant(IdxVal, dl, MVT::i8));
10732   if (Vec.getOpcode() == ISD::UNDEF)
10733     return EltInVec;
10734   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10735 }
10736
10737 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10738                                                   SelectionDAG &DAG) const {
10739   MVT VT = Op.getSimpleValueType();
10740   MVT EltVT = VT.getVectorElementType();
10741
10742   if (EltVT == MVT::i1)
10743     return InsertBitToMaskVector(Op, DAG);
10744
10745   SDLoc dl(Op);
10746   SDValue N0 = Op.getOperand(0);
10747   SDValue N1 = Op.getOperand(1);
10748   SDValue N2 = Op.getOperand(2);
10749   if (!isa<ConstantSDNode>(N2))
10750     return SDValue();
10751   auto *N2C = cast<ConstantSDNode>(N2);
10752   unsigned IdxVal = N2C->getZExtValue();
10753
10754   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10755   // into that, and then insert the subvector back into the result.
10756   if (VT.is256BitVector() || VT.is512BitVector()) {
10757     // With a 256-bit vector, we can insert into the zero element efficiently
10758     // using a blend if we have AVX or AVX2 and the right data type.
10759     if (VT.is256BitVector() && IdxVal == 0) {
10760       // TODO: It is worthwhile to cast integer to floating point and back
10761       // and incur a domain crossing penalty if that's what we'll end up
10762       // doing anyway after extracting to a 128-bit vector.
10763       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10764           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10765         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10766         N2 = DAG.getIntPtrConstant(1, dl);
10767         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10768       }
10769     }
10770
10771     // Get the desired 128-bit vector chunk.
10772     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10773
10774     // Insert the element into the desired chunk.
10775     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10776     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10777
10778     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10779                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10780
10781     // Insert the changed part back into the bigger vector
10782     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10783   }
10784   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10785
10786   if (Subtarget->hasSSE41()) {
10787     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10788       unsigned Opc;
10789       if (VT == MVT::v8i16) {
10790         Opc = X86ISD::PINSRW;
10791       } else {
10792         assert(VT == MVT::v16i8);
10793         Opc = X86ISD::PINSRB;
10794       }
10795
10796       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10797       // argument.
10798       if (N1.getValueType() != MVT::i32)
10799         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10800       if (N2.getValueType() != MVT::i32)
10801         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10802       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10803     }
10804
10805     if (EltVT == MVT::f32) {
10806       // Bits [7:6] of the constant are the source select. This will always be
10807       //   zero here. The DAG Combiner may combine an extract_elt index into
10808       //   these bits. For example (insert (extract, 3), 2) could be matched by
10809       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10810       // Bits [5:4] of the constant are the destination select. This is the
10811       //   value of the incoming immediate.
10812       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10813       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10814
10815       const Function *F = DAG.getMachineFunction().getFunction();
10816       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10817       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10818         // If this is an insertion of 32-bits into the low 32-bits of
10819         // a vector, we prefer to generate a blend with immediate rather
10820         // than an insertps. Blends are simpler operations in hardware and so
10821         // will always have equal or better performance than insertps.
10822         // But if optimizing for size and there's a load folding opportunity,
10823         // generate insertps because blendps does not have a 32-bit memory
10824         // operand form.
10825         N2 = DAG.getIntPtrConstant(1, dl);
10826         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10827         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10828       }
10829       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10830       // Create this as a scalar to vector..
10831       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10832       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10833     }
10834
10835     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10836       // PINSR* works with constant index.
10837       return Op;
10838     }
10839   }
10840
10841   if (EltVT == MVT::i8)
10842     return SDValue();
10843
10844   if (EltVT.getSizeInBits() == 16) {
10845     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10846     // as its second argument.
10847     if (N1.getValueType() != MVT::i32)
10848       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10849     if (N2.getValueType() != MVT::i32)
10850       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10851     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10852   }
10853   return SDValue();
10854 }
10855
10856 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10857   SDLoc dl(Op);
10858   MVT OpVT = Op.getSimpleValueType();
10859
10860   // If this is a 256-bit vector result, first insert into a 128-bit
10861   // vector and then insert into the 256-bit vector.
10862   if (!OpVT.is128BitVector()) {
10863     // Insert into a 128-bit vector.
10864     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10865     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10866                                  OpVT.getVectorNumElements() / SizeFactor);
10867
10868     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10869
10870     // Insert the 128-bit vector.
10871     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10872   }
10873
10874   if (OpVT == MVT::v1i64 &&
10875       Op.getOperand(0).getValueType() == MVT::i64)
10876     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10877
10878   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10879   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10880   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10881                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10882 }
10883
10884 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10885 // a simple subregister reference or explicit instructions to grab
10886 // upper bits of a vector.
10887 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10888                                       SelectionDAG &DAG) {
10889   SDLoc dl(Op);
10890   SDValue In =  Op.getOperand(0);
10891   SDValue Idx = Op.getOperand(1);
10892   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10893   MVT ResVT   = Op.getSimpleValueType();
10894   MVT InVT    = In.getSimpleValueType();
10895
10896   if (Subtarget->hasFp256()) {
10897     if (ResVT.is128BitVector() &&
10898         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10899         isa<ConstantSDNode>(Idx)) {
10900       return Extract128BitVector(In, IdxVal, DAG, dl);
10901     }
10902     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10903         isa<ConstantSDNode>(Idx)) {
10904       return Extract256BitVector(In, IdxVal, DAG, dl);
10905     }
10906   }
10907   return SDValue();
10908 }
10909
10910 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10911 // simple superregister reference or explicit instructions to insert
10912 // the upper bits of a vector.
10913 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10914                                      SelectionDAG &DAG) {
10915   if (!Subtarget->hasAVX())
10916     return SDValue();
10917
10918   SDLoc dl(Op);
10919   SDValue Vec = Op.getOperand(0);
10920   SDValue SubVec = Op.getOperand(1);
10921   SDValue Idx = Op.getOperand(2);
10922
10923   if (!isa<ConstantSDNode>(Idx))
10924     return SDValue();
10925
10926   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10927   MVT OpVT = Op.getSimpleValueType();
10928   MVT SubVecVT = SubVec.getSimpleValueType();
10929
10930   // Fold two 16-byte subvector loads into one 32-byte load:
10931   // (insert_subvector (insert_subvector undef, (load addr), 0),
10932   //                   (load addr + 16), Elts/2)
10933   // --> load32 addr
10934   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10935       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10936       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10937       !Subtarget->isUnalignedMem32Slow()) {
10938     SDValue SubVec2 = Vec.getOperand(1);
10939     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10940       if (Idx2->getZExtValue() == 0) {
10941         SDValue Ops[] = { SubVec2, SubVec };
10942         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10943         if (LD.getNode())
10944           return LD;
10945       }
10946     }
10947   }
10948
10949   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10950       SubVecVT.is128BitVector())
10951     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10952
10953   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10954     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10955
10956   if (OpVT.getVectorElementType() == MVT::i1) {
10957     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10958       return Op;
10959     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10960     SDValue Undef = DAG.getUNDEF(OpVT);
10961     unsigned NumElems = OpVT.getVectorNumElements();
10962     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10963
10964     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10965       // Zero upper bits of the Vec
10966       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10967       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10968
10969       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10970                                  SubVec, ZeroIdx);
10971       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10972       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10973     }
10974     if (IdxVal == 0) {
10975       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10976                                  SubVec, ZeroIdx);
10977       // Zero upper bits of the Vec2
10978       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10979       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10980       // Zero lower bits of the Vec
10981       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10982       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10983       // Merge them together
10984       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10985     }
10986   }
10987   return SDValue();
10988 }
10989
10990 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10991 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10992 // one of the above mentioned nodes. It has to be wrapped because otherwise
10993 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10994 // be used to form addressing mode. These wrapped nodes will be selected
10995 // into MOV32ri.
10996 SDValue
10997 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10998   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10999
11000   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11001   // global base reg.
11002   unsigned char OpFlag = 0;
11003   unsigned WrapperKind = X86ISD::Wrapper;
11004   CodeModel::Model M = DAG.getTarget().getCodeModel();
11005
11006   if (Subtarget->isPICStyleRIPRel() &&
11007       (M == CodeModel::Small || M == CodeModel::Kernel))
11008     WrapperKind = X86ISD::WrapperRIP;
11009   else if (Subtarget->isPICStyleGOT())
11010     OpFlag = X86II::MO_GOTOFF;
11011   else if (Subtarget->isPICStyleStubPIC())
11012     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11013
11014   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
11015                                              CP->getAlignment(),
11016                                              CP->getOffset(), OpFlag);
11017   SDLoc DL(CP);
11018   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11019   // With PIC, the address is actually $g + Offset.
11020   if (OpFlag) {
11021     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11022                          DAG.getNode(X86ISD::GlobalBaseReg,
11023                                      SDLoc(), getPointerTy()),
11024                          Result);
11025   }
11026
11027   return Result;
11028 }
11029
11030 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11031   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11032
11033   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11034   // global base reg.
11035   unsigned char OpFlag = 0;
11036   unsigned WrapperKind = X86ISD::Wrapper;
11037   CodeModel::Model M = DAG.getTarget().getCodeModel();
11038
11039   if (Subtarget->isPICStyleRIPRel() &&
11040       (M == CodeModel::Small || M == CodeModel::Kernel))
11041     WrapperKind = X86ISD::WrapperRIP;
11042   else if (Subtarget->isPICStyleGOT())
11043     OpFlag = X86II::MO_GOTOFF;
11044   else if (Subtarget->isPICStyleStubPIC())
11045     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11046
11047   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11048                                           OpFlag);
11049   SDLoc DL(JT);
11050   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11051
11052   // With PIC, the address is actually $g + Offset.
11053   if (OpFlag)
11054     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11055                          DAG.getNode(X86ISD::GlobalBaseReg,
11056                                      SDLoc(), getPointerTy()),
11057                          Result);
11058
11059   return Result;
11060 }
11061
11062 SDValue
11063 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11064   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11065
11066   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11067   // global base reg.
11068   unsigned char OpFlag = 0;
11069   unsigned WrapperKind = X86ISD::Wrapper;
11070   CodeModel::Model M = DAG.getTarget().getCodeModel();
11071
11072   if (Subtarget->isPICStyleRIPRel() &&
11073       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11074     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11075       OpFlag = X86II::MO_GOTPCREL;
11076     WrapperKind = X86ISD::WrapperRIP;
11077   } else if (Subtarget->isPICStyleGOT()) {
11078     OpFlag = X86II::MO_GOT;
11079   } else if (Subtarget->isPICStyleStubPIC()) {
11080     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11081   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11082     OpFlag = X86II::MO_DARWIN_NONLAZY;
11083   }
11084
11085   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11086
11087   SDLoc DL(Op);
11088   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11089
11090   // With PIC, the address is actually $g + Offset.
11091   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11092       !Subtarget->is64Bit()) {
11093     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11094                          DAG.getNode(X86ISD::GlobalBaseReg,
11095                                      SDLoc(), getPointerTy()),
11096                          Result);
11097   }
11098
11099   // For symbols that require a load from a stub to get the address, emit the
11100   // load.
11101   if (isGlobalStubReference(OpFlag))
11102     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11103                          MachinePointerInfo::getGOT(), false, false, false, 0);
11104
11105   return Result;
11106 }
11107
11108 SDValue
11109 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11110   // Create the TargetBlockAddressAddress node.
11111   unsigned char OpFlags =
11112     Subtarget->ClassifyBlockAddressReference();
11113   CodeModel::Model M = DAG.getTarget().getCodeModel();
11114   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11115   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11116   SDLoc dl(Op);
11117   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11118                                              OpFlags);
11119
11120   if (Subtarget->isPICStyleRIPRel() &&
11121       (M == CodeModel::Small || M == CodeModel::Kernel))
11122     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11123   else
11124     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11125
11126   // With PIC, the address is actually $g + Offset.
11127   if (isGlobalRelativeToPICBase(OpFlags)) {
11128     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11129                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11130                          Result);
11131   }
11132
11133   return Result;
11134 }
11135
11136 SDValue
11137 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11138                                       int64_t Offset, SelectionDAG &DAG) const {
11139   // Create the TargetGlobalAddress node, folding in the constant
11140   // offset if it is legal.
11141   unsigned char OpFlags =
11142       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11143   CodeModel::Model M = DAG.getTarget().getCodeModel();
11144   SDValue Result;
11145   if (OpFlags == X86II::MO_NO_FLAG &&
11146       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11147     // A direct static reference to a global.
11148     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11149     Offset = 0;
11150   } else {
11151     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11152   }
11153
11154   if (Subtarget->isPICStyleRIPRel() &&
11155       (M == CodeModel::Small || M == CodeModel::Kernel))
11156     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11157   else
11158     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11159
11160   // With PIC, the address is actually $g + Offset.
11161   if (isGlobalRelativeToPICBase(OpFlags)) {
11162     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11163                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11164                          Result);
11165   }
11166
11167   // For globals that require a load from a stub to get the address, emit the
11168   // load.
11169   if (isGlobalStubReference(OpFlags))
11170     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11171                          MachinePointerInfo::getGOT(), false, false, false, 0);
11172
11173   // If there was a non-zero offset that we didn't fold, create an explicit
11174   // addition for it.
11175   if (Offset != 0)
11176     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11177                          DAG.getConstant(Offset, dl, getPointerTy()));
11178
11179   return Result;
11180 }
11181
11182 SDValue
11183 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11184   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11185   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11186   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11187 }
11188
11189 static SDValue
11190 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11191            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11192            unsigned char OperandFlags, bool LocalDynamic = false) {
11193   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11194   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11195   SDLoc dl(GA);
11196   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11197                                            GA->getValueType(0),
11198                                            GA->getOffset(),
11199                                            OperandFlags);
11200
11201   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11202                                            : X86ISD::TLSADDR;
11203
11204   if (InFlag) {
11205     SDValue Ops[] = { Chain,  TGA, *InFlag };
11206     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11207   } else {
11208     SDValue Ops[]  = { Chain, TGA };
11209     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11210   }
11211
11212   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11213   MFI->setAdjustsStack(true);
11214   MFI->setHasCalls(true);
11215
11216   SDValue Flag = Chain.getValue(1);
11217   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11218 }
11219
11220 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11221 static SDValue
11222 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11223                                 const EVT PtrVT) {
11224   SDValue InFlag;
11225   SDLoc dl(GA);  // ? function entry point might be better
11226   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11227                                    DAG.getNode(X86ISD::GlobalBaseReg,
11228                                                SDLoc(), PtrVT), InFlag);
11229   InFlag = Chain.getValue(1);
11230
11231   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11232 }
11233
11234 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11235 static SDValue
11236 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11237                                 const EVT PtrVT) {
11238   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11239                     X86::RAX, X86II::MO_TLSGD);
11240 }
11241
11242 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11243                                            SelectionDAG &DAG,
11244                                            const EVT PtrVT,
11245                                            bool is64Bit) {
11246   SDLoc dl(GA);
11247
11248   // Get the start address of the TLS block for this module.
11249   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11250       .getInfo<X86MachineFunctionInfo>();
11251   MFI->incNumLocalDynamicTLSAccesses();
11252
11253   SDValue Base;
11254   if (is64Bit) {
11255     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11256                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11257   } else {
11258     SDValue InFlag;
11259     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11260         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11261     InFlag = Chain.getValue(1);
11262     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11263                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11264   }
11265
11266   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11267   // of Base.
11268
11269   // Build x@dtpoff.
11270   unsigned char OperandFlags = X86II::MO_DTPOFF;
11271   unsigned WrapperKind = X86ISD::Wrapper;
11272   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11273                                            GA->getValueType(0),
11274                                            GA->getOffset(), OperandFlags);
11275   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11276
11277   // Add x@dtpoff with the base.
11278   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11279 }
11280
11281 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11282 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11283                                    const EVT PtrVT, TLSModel::Model model,
11284                                    bool is64Bit, bool isPIC) {
11285   SDLoc dl(GA);
11286
11287   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11288   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11289                                                          is64Bit ? 257 : 256));
11290
11291   SDValue ThreadPointer =
11292       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11293                   MachinePointerInfo(Ptr), false, false, false, 0);
11294
11295   unsigned char OperandFlags = 0;
11296   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11297   // initialexec.
11298   unsigned WrapperKind = X86ISD::Wrapper;
11299   if (model == TLSModel::LocalExec) {
11300     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11301   } else if (model == TLSModel::InitialExec) {
11302     if (is64Bit) {
11303       OperandFlags = X86II::MO_GOTTPOFF;
11304       WrapperKind = X86ISD::WrapperRIP;
11305     } else {
11306       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11307     }
11308   } else {
11309     llvm_unreachable("Unexpected model");
11310   }
11311
11312   // emit "addl x@ntpoff,%eax" (local exec)
11313   // or "addl x@indntpoff,%eax" (initial exec)
11314   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11315   SDValue TGA =
11316       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11317                                  GA->getOffset(), OperandFlags);
11318   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11319
11320   if (model == TLSModel::InitialExec) {
11321     if (isPIC && !is64Bit) {
11322       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11323                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11324                            Offset);
11325     }
11326
11327     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11328                          MachinePointerInfo::getGOT(), false, false, false, 0);
11329   }
11330
11331   // The address of the thread local variable is the add of the thread
11332   // pointer with the offset of the variable.
11333   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11334 }
11335
11336 SDValue
11337 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11338
11339   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11340   const GlobalValue *GV = GA->getGlobal();
11341
11342   if (Subtarget->isTargetELF()) {
11343     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11344     switch (model) {
11345       case TLSModel::GeneralDynamic:
11346         if (Subtarget->is64Bit())
11347           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11348         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11349       case TLSModel::LocalDynamic:
11350         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11351                                            Subtarget->is64Bit());
11352       case TLSModel::InitialExec:
11353       case TLSModel::LocalExec:
11354         return LowerToTLSExecModel(
11355             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11356             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11357     }
11358     llvm_unreachable("Unknown TLS model.");
11359   }
11360
11361   if (Subtarget->isTargetDarwin()) {
11362     // Darwin only has one model of TLS.  Lower to that.
11363     unsigned char OpFlag = 0;
11364     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11365                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11366
11367     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11368     // global base reg.
11369     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11370                  !Subtarget->is64Bit();
11371     if (PIC32)
11372       OpFlag = X86II::MO_TLVP_PIC_BASE;
11373     else
11374       OpFlag = X86II::MO_TLVP;
11375     SDLoc DL(Op);
11376     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11377                                                 GA->getValueType(0),
11378                                                 GA->getOffset(), OpFlag);
11379     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11380
11381     // With PIC32, the address is actually $g + Offset.
11382     if (PIC32)
11383       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11384                            DAG.getNode(X86ISD::GlobalBaseReg,
11385                                        SDLoc(), getPointerTy()),
11386                            Offset);
11387
11388     // Lowering the machine isd will make sure everything is in the right
11389     // location.
11390     SDValue Chain = DAG.getEntryNode();
11391     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11392     SDValue Args[] = { Chain, Offset };
11393     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11394
11395     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11396     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11397     MFI->setAdjustsStack(true);
11398
11399     // And our return value (tls address) is in the standard call return value
11400     // location.
11401     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11402     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11403                               Chain.getValue(1));
11404   }
11405
11406   if (Subtarget->isTargetKnownWindowsMSVC() ||
11407       Subtarget->isTargetWindowsGNU()) {
11408     // Just use the implicit TLS architecture
11409     // Need to generate someting similar to:
11410     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11411     //                                  ; from TEB
11412     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11413     //   mov     rcx, qword [rdx+rcx*8]
11414     //   mov     eax, .tls$:tlsvar
11415     //   [rax+rcx] contains the address
11416     // Windows 64bit: gs:0x58
11417     // Windows 32bit: fs:__tls_array
11418
11419     SDLoc dl(GA);
11420     SDValue Chain = DAG.getEntryNode();
11421
11422     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11423     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11424     // use its literal value of 0x2C.
11425     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11426                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11427                                                              256)
11428                                         : Type::getInt32PtrTy(*DAG.getContext(),
11429                                                               257));
11430
11431     SDValue TlsArray =
11432         Subtarget->is64Bit()
11433             ? DAG.getIntPtrConstant(0x58, dl)
11434             : (Subtarget->isTargetWindowsGNU()
11435                    ? DAG.getIntPtrConstant(0x2C, dl)
11436                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11437
11438     SDValue ThreadPointer =
11439         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11440                     MachinePointerInfo(Ptr), false, false, false, 0);
11441
11442     SDValue res;
11443     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11444       res = ThreadPointer;
11445     } else {
11446       // Load the _tls_index variable
11447       SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11448       if (Subtarget->is64Bit())
11449         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, IDX,
11450                              MachinePointerInfo(), MVT::i32, false, false,
11451                              false, 0);
11452       else
11453         IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11454                           false, false, false, 0);
11455
11456       SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11457                                       getPointerTy());
11458       IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11459
11460       res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11461     }
11462
11463     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11464                       false, false, false, 0);
11465
11466     // Get the offset of start of .tls section
11467     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11468                                              GA->getValueType(0),
11469                                              GA->getOffset(), X86II::MO_SECREL);
11470     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11471
11472     // The address of the thread local variable is the add of the thread
11473     // pointer with the offset of the variable.
11474     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11475   }
11476
11477   llvm_unreachable("TLS not implemented for this target.");
11478 }
11479
11480 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11481 /// and take a 2 x i32 value to shift plus a shift amount.
11482 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11483   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11484   MVT VT = Op.getSimpleValueType();
11485   unsigned VTBits = VT.getSizeInBits();
11486   SDLoc dl(Op);
11487   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11488   SDValue ShOpLo = Op.getOperand(0);
11489   SDValue ShOpHi = Op.getOperand(1);
11490   SDValue ShAmt  = Op.getOperand(2);
11491   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11492   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11493   // during isel.
11494   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11495                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11496   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11497                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11498                        : DAG.getConstant(0, dl, VT);
11499
11500   SDValue Tmp2, Tmp3;
11501   if (Op.getOpcode() == ISD::SHL_PARTS) {
11502     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11503     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11504   } else {
11505     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11506     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11507   }
11508
11509   // If the shift amount is larger or equal than the width of a part we can't
11510   // rely on the results of shld/shrd. Insert a test and select the appropriate
11511   // values for large shift amounts.
11512   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11513                                 DAG.getConstant(VTBits, dl, MVT::i8));
11514   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11515                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11516
11517   SDValue Hi, Lo;
11518   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11519   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11520   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11521
11522   if (Op.getOpcode() == ISD::SHL_PARTS) {
11523     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11524     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11525   } else {
11526     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11527     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11528   }
11529
11530   SDValue Ops[2] = { Lo, Hi };
11531   return DAG.getMergeValues(Ops, dl);
11532 }
11533
11534 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11535                                            SelectionDAG &DAG) const {
11536   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11537   SDLoc dl(Op);
11538
11539   if (SrcVT.isVector()) {
11540     if (SrcVT.getVectorElementType() == MVT::i1) {
11541       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11542       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11543                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11544                                      Op.getOperand(0)));
11545     }
11546     return SDValue();
11547   }
11548
11549   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11550          "Unknown SINT_TO_FP to lower!");
11551
11552   // These are really Legal; return the operand so the caller accepts it as
11553   // Legal.
11554   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11555     return Op;
11556   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11557       Subtarget->is64Bit()) {
11558     return Op;
11559   }
11560
11561   unsigned Size = SrcVT.getSizeInBits()/8;
11562   MachineFunction &MF = DAG.getMachineFunction();
11563   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11564   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11565   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11566                                StackSlot,
11567                                MachinePointerInfo::getFixedStack(SSFI),
11568                                false, false, 0);
11569   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11570 }
11571
11572 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11573                                      SDValue StackSlot,
11574                                      SelectionDAG &DAG) const {
11575   // Build the FILD
11576   SDLoc DL(Op);
11577   SDVTList Tys;
11578   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11579   if (useSSE)
11580     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11581   else
11582     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11583
11584   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11585
11586   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11587   MachineMemOperand *MMO;
11588   if (FI) {
11589     int SSFI = FI->getIndex();
11590     MMO =
11591       DAG.getMachineFunction()
11592       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11593                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11594   } else {
11595     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11596     StackSlot = StackSlot.getOperand(1);
11597   }
11598   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11599   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11600                                            X86ISD::FILD, DL,
11601                                            Tys, Ops, SrcVT, MMO);
11602
11603   if (useSSE) {
11604     Chain = Result.getValue(1);
11605     SDValue InFlag = Result.getValue(2);
11606
11607     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11608     // shouldn't be necessary except that RFP cannot be live across
11609     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11610     MachineFunction &MF = DAG.getMachineFunction();
11611     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11612     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11613     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11614     Tys = DAG.getVTList(MVT::Other);
11615     SDValue Ops[] = {
11616       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11617     };
11618     MachineMemOperand *MMO =
11619       DAG.getMachineFunction()
11620       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11621                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11622
11623     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11624                                     Ops, Op.getValueType(), MMO);
11625     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11626                          MachinePointerInfo::getFixedStack(SSFI),
11627                          false, false, false, 0);
11628   }
11629
11630   return Result;
11631 }
11632
11633 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11634 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11635                                                SelectionDAG &DAG) const {
11636   // This algorithm is not obvious. Here it is what we're trying to output:
11637   /*
11638      movq       %rax,  %xmm0
11639      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11640      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11641      #ifdef __SSE3__
11642        haddpd   %xmm0, %xmm0
11643      #else
11644        pshufd   $0x4e, %xmm0, %xmm1
11645        addpd    %xmm1, %xmm0
11646      #endif
11647   */
11648
11649   SDLoc dl(Op);
11650   LLVMContext *Context = DAG.getContext();
11651
11652   // Build some magic constants.
11653   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11654   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11655   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11656
11657   SmallVector<Constant*,2> CV1;
11658   CV1.push_back(
11659     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11660                                       APInt(64, 0x4330000000000000ULL))));
11661   CV1.push_back(
11662     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11663                                       APInt(64, 0x4530000000000000ULL))));
11664   Constant *C1 = ConstantVector::get(CV1);
11665   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11666
11667   // Load the 64-bit value into an XMM register.
11668   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11669                             Op.getOperand(0));
11670   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11671                               MachinePointerInfo::getConstantPool(),
11672                               false, false, false, 16);
11673   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11674                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11675                               CLod0);
11676
11677   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11678                               MachinePointerInfo::getConstantPool(),
11679                               false, false, false, 16);
11680   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11681   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11682   SDValue Result;
11683
11684   if (Subtarget->hasSSE3()) {
11685     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11686     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11687   } else {
11688     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11689     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11690                                            S2F, 0x4E, DAG);
11691     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11692                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11693                          Sub);
11694   }
11695
11696   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11697                      DAG.getIntPtrConstant(0, dl));
11698 }
11699
11700 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11701 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11702                                                SelectionDAG &DAG) const {
11703   SDLoc dl(Op);
11704   // FP constant to bias correct the final result.
11705   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11706                                    MVT::f64);
11707
11708   // Load the 32-bit value into an XMM register.
11709   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11710                              Op.getOperand(0));
11711
11712   // Zero out the upper parts of the register.
11713   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11714
11715   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11716                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11717                      DAG.getIntPtrConstant(0, dl));
11718
11719   // Or the load with the bias.
11720   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11721                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11722                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11723                                                    MVT::v2f64, Load)),
11724                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11725                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11726                                                    MVT::v2f64, Bias)));
11727   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11728                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11729                    DAG.getIntPtrConstant(0, dl));
11730
11731   // Subtract the bias.
11732   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11733
11734   // Handle final rounding.
11735   EVT DestVT = Op.getValueType();
11736
11737   if (DestVT.bitsLT(MVT::f64))
11738     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11739                        DAG.getIntPtrConstant(0, dl));
11740   if (DestVT.bitsGT(MVT::f64))
11741     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11742
11743   // Handle final rounding.
11744   return Sub;
11745 }
11746
11747 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11748                                      const X86Subtarget &Subtarget) {
11749   // The algorithm is the following:
11750   // #ifdef __SSE4_1__
11751   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11752   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11753   //                                 (uint4) 0x53000000, 0xaa);
11754   // #else
11755   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11756   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11757   // #endif
11758   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11759   //     return (float4) lo + fhi;
11760
11761   SDLoc DL(Op);
11762   SDValue V = Op->getOperand(0);
11763   EVT VecIntVT = V.getValueType();
11764   bool Is128 = VecIntVT == MVT::v4i32;
11765   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11766   // If we convert to something else than the supported type, e.g., to v4f64,
11767   // abort early.
11768   if (VecFloatVT != Op->getValueType(0))
11769     return SDValue();
11770
11771   unsigned NumElts = VecIntVT.getVectorNumElements();
11772   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11773          "Unsupported custom type");
11774   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11775
11776   // In the #idef/#else code, we have in common:
11777   // - The vector of constants:
11778   // -- 0x4b000000
11779   // -- 0x53000000
11780   // - A shift:
11781   // -- v >> 16
11782
11783   // Create the splat vector for 0x4b000000.
11784   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11785   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11786                            CstLow, CstLow, CstLow, CstLow};
11787   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11788                                   makeArrayRef(&CstLowArray[0], NumElts));
11789   // Create the splat vector for 0x53000000.
11790   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11791   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11792                             CstHigh, CstHigh, CstHigh, CstHigh};
11793   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11794                                    makeArrayRef(&CstHighArray[0], NumElts));
11795
11796   // Create the right shift.
11797   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11798   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11799                              CstShift, CstShift, CstShift, CstShift};
11800   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11801                                     makeArrayRef(&CstShiftArray[0], NumElts));
11802   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11803
11804   SDValue Low, High;
11805   if (Subtarget.hasSSE41()) {
11806     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11807     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11808     SDValue VecCstLowBitcast =
11809         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11810     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11811     // Low will be bitcasted right away, so do not bother bitcasting back to its
11812     // original type.
11813     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11814                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11815     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11816     //                                 (uint4) 0x53000000, 0xaa);
11817     SDValue VecCstHighBitcast =
11818         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11819     SDValue VecShiftBitcast =
11820         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11821     // High will be bitcasted right away, so do not bother bitcasting back to
11822     // its original type.
11823     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11824                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11825   } else {
11826     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11827     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11828                                      CstMask, CstMask, CstMask);
11829     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11830     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11831     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11832
11833     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11834     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11835   }
11836
11837   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11838   SDValue CstFAdd = DAG.getConstantFP(
11839       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11840   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11841                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11842   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11843                                    makeArrayRef(&CstFAddArray[0], NumElts));
11844
11845   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11846   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11847   SDValue FHigh =
11848       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11849   //     return (float4) lo + fhi;
11850   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11851   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11852 }
11853
11854 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11855                                                SelectionDAG &DAG) const {
11856   SDValue N0 = Op.getOperand(0);
11857   MVT SVT = N0.getSimpleValueType();
11858   SDLoc dl(Op);
11859
11860   switch (SVT.SimpleTy) {
11861   default:
11862     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11863   case MVT::v4i8:
11864   case MVT::v4i16:
11865   case MVT::v8i8:
11866   case MVT::v8i16: {
11867     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11868     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11869                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11870   }
11871   case MVT::v4i32:
11872   case MVT::v8i32:
11873     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11874   case MVT::v16i8:
11875   case MVT::v16i16:
11876     if (Subtarget->hasAVX512())
11877       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11878                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11879   }
11880   llvm_unreachable(nullptr);
11881 }
11882
11883 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11884                                            SelectionDAG &DAG) const {
11885   SDValue N0 = Op.getOperand(0);
11886   SDLoc dl(Op);
11887
11888   if (Op.getValueType().isVector())
11889     return lowerUINT_TO_FP_vec(Op, DAG);
11890
11891   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11892   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11893   // the optimization here.
11894   if (DAG.SignBitIsZero(N0))
11895     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11896
11897   MVT SrcVT = N0.getSimpleValueType();
11898   MVT DstVT = Op.getSimpleValueType();
11899   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11900     return LowerUINT_TO_FP_i64(Op, DAG);
11901   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11902     return LowerUINT_TO_FP_i32(Op, DAG);
11903   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11904     return SDValue();
11905
11906   // Make a 64-bit buffer, and use it to build an FILD.
11907   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11908   if (SrcVT == MVT::i32) {
11909     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11910     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11911                                      getPointerTy(), StackSlot, WordOff);
11912     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11913                                   StackSlot, MachinePointerInfo(),
11914                                   false, false, 0);
11915     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11916                                   OffsetSlot, MachinePointerInfo(),
11917                                   false, false, 0);
11918     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11919     return Fild;
11920   }
11921
11922   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11923   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11924                                StackSlot, MachinePointerInfo(),
11925                                false, false, 0);
11926   // For i64 source, we need to add the appropriate power of 2 if the input
11927   // was negative.  This is the same as the optimization in
11928   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11929   // we must be careful to do the computation in x87 extended precision, not
11930   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11931   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11932   MachineMemOperand *MMO =
11933     DAG.getMachineFunction()
11934     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11935                           MachineMemOperand::MOLoad, 8, 8);
11936
11937   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11938   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11939   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11940                                          MVT::i64, MMO);
11941
11942   APInt FF(32, 0x5F800000ULL);
11943
11944   // Check whether the sign bit is set.
11945   SDValue SignSet = DAG.getSetCC(dl,
11946                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11947                                  Op.getOperand(0),
11948                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11949
11950   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11951   SDValue FudgePtr = DAG.getConstantPool(
11952                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11953                                          getPointerTy());
11954
11955   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11956   SDValue Zero = DAG.getIntPtrConstant(0, dl);
11957   SDValue Four = DAG.getIntPtrConstant(4, dl);
11958   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11959                                Zero, Four);
11960   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11961
11962   // Load the value out, extending it from f32 to f80.
11963   // FIXME: Avoid the extend by constructing the right constant pool?
11964   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11965                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11966                                  MVT::f32, false, false, false, 4);
11967   // Extend everything to 80 bits to force it to be done on x87.
11968   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11969   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11970                      DAG.getIntPtrConstant(0, dl));
11971 }
11972
11973 std::pair<SDValue,SDValue>
11974 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11975                                     bool IsSigned, bool IsReplace) const {
11976   SDLoc DL(Op);
11977
11978   EVT DstTy = Op.getValueType();
11979
11980   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11981     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11982     DstTy = MVT::i64;
11983   }
11984
11985   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11986          DstTy.getSimpleVT() >= MVT::i16 &&
11987          "Unknown FP_TO_INT to lower!");
11988
11989   // These are really Legal.
11990   if (DstTy == MVT::i32 &&
11991       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11992     return std::make_pair(SDValue(), SDValue());
11993   if (Subtarget->is64Bit() &&
11994       DstTy == MVT::i64 &&
11995       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11996     return std::make_pair(SDValue(), SDValue());
11997
11998   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11999   // stack slot, or into the FTOL runtime function.
12000   MachineFunction &MF = DAG.getMachineFunction();
12001   unsigned MemSize = DstTy.getSizeInBits()/8;
12002   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12003   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12004
12005   unsigned Opc;
12006   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12007     Opc = X86ISD::WIN_FTOL;
12008   else
12009     switch (DstTy.getSimpleVT().SimpleTy) {
12010     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12011     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12012     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12013     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12014     }
12015
12016   SDValue Chain = DAG.getEntryNode();
12017   SDValue Value = Op.getOperand(0);
12018   EVT TheVT = Op.getOperand(0).getValueType();
12019   // FIXME This causes a redundant load/store if the SSE-class value is already
12020   // in memory, such as if it is on the callstack.
12021   if (isScalarFPTypeInSSEReg(TheVT)) {
12022     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12023     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12024                          MachinePointerInfo::getFixedStack(SSFI),
12025                          false, false, 0);
12026     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12027     SDValue Ops[] = {
12028       Chain, StackSlot, DAG.getValueType(TheVT)
12029     };
12030
12031     MachineMemOperand *MMO =
12032       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12033                               MachineMemOperand::MOLoad, MemSize, MemSize);
12034     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12035     Chain = Value.getValue(1);
12036     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12037     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12038   }
12039
12040   MachineMemOperand *MMO =
12041     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12042                             MachineMemOperand::MOStore, MemSize, MemSize);
12043
12044   if (Opc != X86ISD::WIN_FTOL) {
12045     // Build the FP_TO_INT*_IN_MEM
12046     SDValue Ops[] = { Chain, Value, StackSlot };
12047     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12048                                            Ops, DstTy, MMO);
12049     return std::make_pair(FIST, StackSlot);
12050   } else {
12051     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12052       DAG.getVTList(MVT::Other, MVT::Glue),
12053       Chain, Value);
12054     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12055       MVT::i32, ftol.getValue(1));
12056     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12057       MVT::i32, eax.getValue(2));
12058     SDValue Ops[] = { eax, edx };
12059     SDValue pair = IsReplace
12060       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12061       : DAG.getMergeValues(Ops, DL);
12062     return std::make_pair(pair, SDValue());
12063   }
12064 }
12065
12066 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12067                               const X86Subtarget *Subtarget) {
12068   MVT VT = Op->getSimpleValueType(0);
12069   SDValue In = Op->getOperand(0);
12070   MVT InVT = In.getSimpleValueType();
12071   SDLoc dl(Op);
12072
12073   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12074     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12075
12076   // Optimize vectors in AVX mode:
12077   //
12078   //   v8i16 -> v8i32
12079   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12080   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12081   //   Concat upper and lower parts.
12082   //
12083   //   v4i32 -> v4i64
12084   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12085   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12086   //   Concat upper and lower parts.
12087   //
12088
12089   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12090       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12091       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12092     return SDValue();
12093
12094   if (Subtarget->hasInt256())
12095     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12096
12097   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12098   SDValue Undef = DAG.getUNDEF(InVT);
12099   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12100   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12101   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12102
12103   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12104                              VT.getVectorNumElements()/2);
12105
12106   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12107   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12108
12109   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12110 }
12111
12112 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12113                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12114   MVT VT = Op->getSimpleValueType(0);
12115   SDValue In = Op->getOperand(0);
12116   MVT InVT = In.getSimpleValueType();
12117   SDLoc DL(Op);
12118   unsigned int NumElts = VT.getVectorNumElements();
12119   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12120     return SDValue();
12121
12122   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12123     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12124
12125   assert(InVT.getVectorElementType() == MVT::i1);
12126   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12127   SDValue One =
12128    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12129   SDValue Zero =
12130    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12131
12132   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12133   if (VT.is512BitVector())
12134     return V;
12135   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12136 }
12137
12138 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12139                                SelectionDAG &DAG) {
12140   if (Subtarget->hasFp256()) {
12141     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12142     if (Res.getNode())
12143       return Res;
12144   }
12145
12146   return SDValue();
12147 }
12148
12149 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12150                                 SelectionDAG &DAG) {
12151   SDLoc DL(Op);
12152   MVT VT = Op.getSimpleValueType();
12153   SDValue In = Op.getOperand(0);
12154   MVT SVT = In.getSimpleValueType();
12155
12156   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12157     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12158
12159   if (Subtarget->hasFp256()) {
12160     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12161     if (Res.getNode())
12162       return Res;
12163   }
12164
12165   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12166          VT.getVectorNumElements() != SVT.getVectorNumElements());
12167   return SDValue();
12168 }
12169
12170 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12171   SDLoc DL(Op);
12172   MVT VT = Op.getSimpleValueType();
12173   SDValue In = Op.getOperand(0);
12174   MVT InVT = In.getSimpleValueType();
12175
12176   if (VT == MVT::i1) {
12177     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12178            "Invalid scalar TRUNCATE operation");
12179     if (InVT.getSizeInBits() >= 32)
12180       return SDValue();
12181     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12182     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12183   }
12184   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12185          "Invalid TRUNCATE operation");
12186
12187   // move vector to mask - truncate solution for SKX
12188   if (VT.getVectorElementType() == MVT::i1) {
12189     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12190         Subtarget->hasBWI())
12191       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12192     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12193         && InVT.getScalarSizeInBits() <= 16 &&
12194         Subtarget->hasBWI() && Subtarget->hasVLX())
12195       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12196     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12197         Subtarget->hasDQI())
12198       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12199     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12200         && InVT.getScalarSizeInBits() >= 32 &&
12201         Subtarget->hasDQI() && Subtarget->hasVLX())
12202       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12203   }
12204   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12205     if (VT.getVectorElementType().getSizeInBits() >=8)
12206       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12207
12208     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12209     unsigned NumElts = InVT.getVectorNumElements();
12210     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12211     if (InVT.getSizeInBits() < 512) {
12212       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12213       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12214       InVT = ExtVT;
12215     }
12216
12217     SDValue OneV =
12218      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12219     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12220     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12221   }
12222
12223   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12224     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12225     if (Subtarget->hasInt256()) {
12226       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12227       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12228       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12229                                 ShufMask);
12230       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12231                          DAG.getIntPtrConstant(0, DL));
12232     }
12233
12234     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12235                                DAG.getIntPtrConstant(0, DL));
12236     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12237                                DAG.getIntPtrConstant(2, DL));
12238     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12239     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12240     static const int ShufMask[] = {0, 2, 4, 6};
12241     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12242   }
12243
12244   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12245     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12246     if (Subtarget->hasInt256()) {
12247       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12248
12249       SmallVector<SDValue,32> pshufbMask;
12250       for (unsigned i = 0; i < 2; ++i) {
12251         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12252         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12253         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12254         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12255         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12256         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12257         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12258         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12259         for (unsigned j = 0; j < 8; ++j)
12260           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12261       }
12262       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12263       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12264       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12265
12266       static const int ShufMask[] = {0,  2,  -1,  -1};
12267       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12268                                 &ShufMask[0]);
12269       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12270                        DAG.getIntPtrConstant(0, DL));
12271       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12272     }
12273
12274     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12275                                DAG.getIntPtrConstant(0, DL));
12276
12277     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12278                                DAG.getIntPtrConstant(4, DL));
12279
12280     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12281     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12282
12283     // The PSHUFB mask:
12284     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12285                                    -1, -1, -1, -1, -1, -1, -1, -1};
12286
12287     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12288     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12289     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12290
12291     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12292     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12293
12294     // The MOVLHPS Mask:
12295     static const int ShufMask2[] = {0, 1, 4, 5};
12296     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12297     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12298   }
12299
12300   // Handle truncation of V256 to V128 using shuffles.
12301   if (!VT.is128BitVector() || !InVT.is256BitVector())
12302     return SDValue();
12303
12304   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12305
12306   unsigned NumElems = VT.getVectorNumElements();
12307   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12308
12309   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12310   // Prepare truncation shuffle mask
12311   for (unsigned i = 0; i != NumElems; ++i)
12312     MaskVec[i] = i * 2;
12313   SDValue V = DAG.getVectorShuffle(NVT, DL,
12314                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12315                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12316   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12317                      DAG.getIntPtrConstant(0, DL));
12318 }
12319
12320 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12321                                            SelectionDAG &DAG) const {
12322   assert(!Op.getSimpleValueType().isVector());
12323
12324   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12325     /*IsSigned=*/ true, /*IsReplace=*/ false);
12326   SDValue FIST = Vals.first, StackSlot = Vals.second;
12327   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12328   if (!FIST.getNode()) return Op;
12329
12330   if (StackSlot.getNode())
12331     // Load the result.
12332     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12333                        FIST, StackSlot, MachinePointerInfo(),
12334                        false, false, false, 0);
12335
12336   // The node is the result.
12337   return FIST;
12338 }
12339
12340 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12341                                            SelectionDAG &DAG) const {
12342   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12343     /*IsSigned=*/ false, /*IsReplace=*/ false);
12344   SDValue FIST = Vals.first, StackSlot = Vals.second;
12345   assert(FIST.getNode() && "Unexpected failure");
12346
12347   if (StackSlot.getNode())
12348     // Load the result.
12349     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12350                        FIST, StackSlot, MachinePointerInfo(),
12351                        false, false, false, 0);
12352
12353   // The node is the result.
12354   return FIST;
12355 }
12356
12357 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12358   SDLoc DL(Op);
12359   MVT VT = Op.getSimpleValueType();
12360   SDValue In = Op.getOperand(0);
12361   MVT SVT = In.getSimpleValueType();
12362
12363   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12364
12365   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12366                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12367                                  In, DAG.getUNDEF(SVT)));
12368 }
12369
12370 /// The only differences between FABS and FNEG are the mask and the logic op.
12371 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12372 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12373   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12374          "Wrong opcode for lowering FABS or FNEG.");
12375
12376   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12377
12378   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12379   // into an FNABS. We'll lower the FABS after that if it is still in use.
12380   if (IsFABS)
12381     for (SDNode *User : Op->uses())
12382       if (User->getOpcode() == ISD::FNEG)
12383         return Op;
12384
12385   SDValue Op0 = Op.getOperand(0);
12386   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12387
12388   SDLoc dl(Op);
12389   MVT VT = Op.getSimpleValueType();
12390   // Assume scalar op for initialization; update for vector if needed.
12391   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12392   // generate a 16-byte vector constant and logic op even for the scalar case.
12393   // Using a 16-byte mask allows folding the load of the mask with
12394   // the logic op, so it can save (~4 bytes) on code size.
12395   MVT EltVT = VT;
12396   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12397   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12398   // decide if we should generate a 16-byte constant mask when we only need 4 or
12399   // 8 bytes for the scalar case.
12400   if (VT.isVector()) {
12401     EltVT = VT.getVectorElementType();
12402     NumElts = VT.getVectorNumElements();
12403   }
12404
12405   unsigned EltBits = EltVT.getSizeInBits();
12406   LLVMContext *Context = DAG.getContext();
12407   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12408   APInt MaskElt =
12409     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12410   Constant *C = ConstantInt::get(*Context, MaskElt);
12411   C = ConstantVector::getSplat(NumElts, C);
12412   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12413   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12414   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12415   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12416                              MachinePointerInfo::getConstantPool(),
12417                              false, false, false, Alignment);
12418
12419   if (VT.isVector()) {
12420     // For a vector, cast operands to a vector type, perform the logic op,
12421     // and cast the result back to the original value type.
12422     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12423     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12424     SDValue Operand = IsFNABS ?
12425       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12426       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12427     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12428     return DAG.getNode(ISD::BITCAST, dl, VT,
12429                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12430   }
12431
12432   // If not vector, then scalar.
12433   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12434   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12435   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12436 }
12437
12438 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12440   LLVMContext *Context = DAG.getContext();
12441   SDValue Op0 = Op.getOperand(0);
12442   SDValue Op1 = Op.getOperand(1);
12443   SDLoc dl(Op);
12444   MVT VT = Op.getSimpleValueType();
12445   MVT SrcVT = Op1.getSimpleValueType();
12446
12447   // If second operand is smaller, extend it first.
12448   if (SrcVT.bitsLT(VT)) {
12449     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12450     SrcVT = VT;
12451   }
12452   // And if it is bigger, shrink it first.
12453   if (SrcVT.bitsGT(VT)) {
12454     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12455     SrcVT = VT;
12456   }
12457
12458   // At this point the operands and the result should have the same
12459   // type, and that won't be f80 since that is not custom lowered.
12460
12461   const fltSemantics &Sem =
12462       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12463   const unsigned SizeInBits = VT.getSizeInBits();
12464
12465   SmallVector<Constant *, 4> CV(
12466       VT == MVT::f64 ? 2 : 4,
12467       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12468
12469   // First, clear all bits but the sign bit from the second operand (sign).
12470   CV[0] = ConstantFP::get(*Context,
12471                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12472   Constant *C = ConstantVector::get(CV);
12473   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12474   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12475                               MachinePointerInfo::getConstantPool(),
12476                               false, false, false, 16);
12477   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12478
12479   // Next, clear the sign bit from the first operand (magnitude).
12480   // If it's a constant, we can clear it here.
12481   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12482     APFloat APF = Op0CN->getValueAPF();
12483     // If the magnitude is a positive zero, the sign bit alone is enough.
12484     if (APF.isPosZero())
12485       return SignBit;
12486     APF.clearSign();
12487     CV[0] = ConstantFP::get(*Context, APF);
12488   } else {
12489     CV[0] = ConstantFP::get(
12490         *Context,
12491         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12492   }
12493   C = ConstantVector::get(CV);
12494   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12495   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12496                             MachinePointerInfo::getConstantPool(),
12497                             false, false, false, 16);
12498   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12499   if (!isa<ConstantFPSDNode>(Op0))
12500     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12501
12502   // OR the magnitude value with the sign bit.
12503   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12504 }
12505
12506 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12507   SDValue N0 = Op.getOperand(0);
12508   SDLoc dl(Op);
12509   MVT VT = Op.getSimpleValueType();
12510
12511   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12512   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12513                                   DAG.getConstant(1, dl, VT));
12514   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12515 }
12516
12517 // Check whether an OR'd tree is PTEST-able.
12518 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12519                                       SelectionDAG &DAG) {
12520   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12521
12522   if (!Subtarget->hasSSE41())
12523     return SDValue();
12524
12525   if (!Op->hasOneUse())
12526     return SDValue();
12527
12528   SDNode *N = Op.getNode();
12529   SDLoc DL(N);
12530
12531   SmallVector<SDValue, 8> Opnds;
12532   DenseMap<SDValue, unsigned> VecInMap;
12533   SmallVector<SDValue, 8> VecIns;
12534   EVT VT = MVT::Other;
12535
12536   // Recognize a special case where a vector is casted into wide integer to
12537   // test all 0s.
12538   Opnds.push_back(N->getOperand(0));
12539   Opnds.push_back(N->getOperand(1));
12540
12541   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12542     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12543     // BFS traverse all OR'd operands.
12544     if (I->getOpcode() == ISD::OR) {
12545       Opnds.push_back(I->getOperand(0));
12546       Opnds.push_back(I->getOperand(1));
12547       // Re-evaluate the number of nodes to be traversed.
12548       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12549       continue;
12550     }
12551
12552     // Quit if a non-EXTRACT_VECTOR_ELT
12553     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12554       return SDValue();
12555
12556     // Quit if without a constant index.
12557     SDValue Idx = I->getOperand(1);
12558     if (!isa<ConstantSDNode>(Idx))
12559       return SDValue();
12560
12561     SDValue ExtractedFromVec = I->getOperand(0);
12562     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12563     if (M == VecInMap.end()) {
12564       VT = ExtractedFromVec.getValueType();
12565       // Quit if not 128/256-bit vector.
12566       if (!VT.is128BitVector() && !VT.is256BitVector())
12567         return SDValue();
12568       // Quit if not the same type.
12569       if (VecInMap.begin() != VecInMap.end() &&
12570           VT != VecInMap.begin()->first.getValueType())
12571         return SDValue();
12572       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12573       VecIns.push_back(ExtractedFromVec);
12574     }
12575     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12576   }
12577
12578   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12579          "Not extracted from 128-/256-bit vector.");
12580
12581   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12582
12583   for (DenseMap<SDValue, unsigned>::const_iterator
12584         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12585     // Quit if not all elements are used.
12586     if (I->second != FullMask)
12587       return SDValue();
12588   }
12589
12590   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12591
12592   // Cast all vectors into TestVT for PTEST.
12593   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12594     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12595
12596   // If more than one full vectors are evaluated, OR them first before PTEST.
12597   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12598     // Each iteration will OR 2 nodes and append the result until there is only
12599     // 1 node left, i.e. the final OR'd value of all vectors.
12600     SDValue LHS = VecIns[Slot];
12601     SDValue RHS = VecIns[Slot + 1];
12602     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12603   }
12604
12605   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12606                      VecIns.back(), VecIns.back());
12607 }
12608
12609 /// \brief return true if \c Op has a use that doesn't just read flags.
12610 static bool hasNonFlagsUse(SDValue Op) {
12611   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12612        ++UI) {
12613     SDNode *User = *UI;
12614     unsigned UOpNo = UI.getOperandNo();
12615     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12616       // Look pass truncate.
12617       UOpNo = User->use_begin().getOperandNo();
12618       User = *User->use_begin();
12619     }
12620
12621     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12622         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12623       return true;
12624   }
12625   return false;
12626 }
12627
12628 /// Emit nodes that will be selected as "test Op0,Op0", or something
12629 /// equivalent.
12630 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12631                                     SelectionDAG &DAG) const {
12632   if (Op.getValueType() == MVT::i1) {
12633     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12634     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12635                        DAG.getConstant(0, dl, MVT::i8));
12636   }
12637   // CF and OF aren't always set the way we want. Determine which
12638   // of these we need.
12639   bool NeedCF = false;
12640   bool NeedOF = false;
12641   switch (X86CC) {
12642   default: break;
12643   case X86::COND_A: case X86::COND_AE:
12644   case X86::COND_B: case X86::COND_BE:
12645     NeedCF = true;
12646     break;
12647   case X86::COND_G: case X86::COND_GE:
12648   case X86::COND_L: case X86::COND_LE:
12649   case X86::COND_O: case X86::COND_NO: {
12650     // Check if we really need to set the
12651     // Overflow flag. If NoSignedWrap is present
12652     // that is not actually needed.
12653     switch (Op->getOpcode()) {
12654     case ISD::ADD:
12655     case ISD::SUB:
12656     case ISD::MUL:
12657     case ISD::SHL: {
12658       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12659       if (BinNode->Flags.hasNoSignedWrap())
12660         break;
12661     }
12662     default:
12663       NeedOF = true;
12664       break;
12665     }
12666     break;
12667   }
12668   }
12669   // See if we can use the EFLAGS value from the operand instead of
12670   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12671   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12672   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12673     // Emit a CMP with 0, which is the TEST pattern.
12674     //if (Op.getValueType() == MVT::i1)
12675     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12676     //                     DAG.getConstant(0, MVT::i1));
12677     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12678                        DAG.getConstant(0, dl, Op.getValueType()));
12679   }
12680   unsigned Opcode = 0;
12681   unsigned NumOperands = 0;
12682
12683   // Truncate operations may prevent the merge of the SETCC instruction
12684   // and the arithmetic instruction before it. Attempt to truncate the operands
12685   // of the arithmetic instruction and use a reduced bit-width instruction.
12686   bool NeedTruncation = false;
12687   SDValue ArithOp = Op;
12688   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12689     SDValue Arith = Op->getOperand(0);
12690     // Both the trunc and the arithmetic op need to have one user each.
12691     if (Arith->hasOneUse())
12692       switch (Arith.getOpcode()) {
12693         default: break;
12694         case ISD::ADD:
12695         case ISD::SUB:
12696         case ISD::AND:
12697         case ISD::OR:
12698         case ISD::XOR: {
12699           NeedTruncation = true;
12700           ArithOp = Arith;
12701         }
12702       }
12703   }
12704
12705   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12706   // which may be the result of a CAST.  We use the variable 'Op', which is the
12707   // non-casted variable when we check for possible users.
12708   switch (ArithOp.getOpcode()) {
12709   case ISD::ADD:
12710     // Due to an isel shortcoming, be conservative if this add is likely to be
12711     // selected as part of a load-modify-store instruction. When the root node
12712     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12713     // uses of other nodes in the match, such as the ADD in this case. This
12714     // leads to the ADD being left around and reselected, with the result being
12715     // two adds in the output.  Alas, even if none our users are stores, that
12716     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12717     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12718     // climbing the DAG back to the root, and it doesn't seem to be worth the
12719     // effort.
12720     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12721          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12722       if (UI->getOpcode() != ISD::CopyToReg &&
12723           UI->getOpcode() != ISD::SETCC &&
12724           UI->getOpcode() != ISD::STORE)
12725         goto default_case;
12726
12727     if (ConstantSDNode *C =
12728         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12729       // An add of one will be selected as an INC.
12730       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12731         Opcode = X86ISD::INC;
12732         NumOperands = 1;
12733         break;
12734       }
12735
12736       // An add of negative one (subtract of one) will be selected as a DEC.
12737       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12738         Opcode = X86ISD::DEC;
12739         NumOperands = 1;
12740         break;
12741       }
12742     }
12743
12744     // Otherwise use a regular EFLAGS-setting add.
12745     Opcode = X86ISD::ADD;
12746     NumOperands = 2;
12747     break;
12748   case ISD::SHL:
12749   case ISD::SRL:
12750     // If we have a constant logical shift that's only used in a comparison
12751     // against zero turn it into an equivalent AND. This allows turning it into
12752     // a TEST instruction later.
12753     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12754         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12755       EVT VT = Op.getValueType();
12756       unsigned BitWidth = VT.getSizeInBits();
12757       unsigned ShAmt = Op->getConstantOperandVal(1);
12758       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12759         break;
12760       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12761                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12762                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12763       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12764         break;
12765       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12766                                 DAG.getConstant(Mask, dl, VT));
12767       DAG.ReplaceAllUsesWith(Op, New);
12768       Op = New;
12769     }
12770     break;
12771
12772   case ISD::AND:
12773     // If the primary and result isn't used, don't bother using X86ISD::AND,
12774     // because a TEST instruction will be better.
12775     if (!hasNonFlagsUse(Op))
12776       break;
12777     // FALL THROUGH
12778   case ISD::SUB:
12779   case ISD::OR:
12780   case ISD::XOR:
12781     // Due to the ISEL shortcoming noted above, be conservative if this op is
12782     // likely to be selected as part of a load-modify-store instruction.
12783     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12784            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12785       if (UI->getOpcode() == ISD::STORE)
12786         goto default_case;
12787
12788     // Otherwise use a regular EFLAGS-setting instruction.
12789     switch (ArithOp.getOpcode()) {
12790     default: llvm_unreachable("unexpected operator!");
12791     case ISD::SUB: Opcode = X86ISD::SUB; break;
12792     case ISD::XOR: Opcode = X86ISD::XOR; break;
12793     case ISD::AND: Opcode = X86ISD::AND; break;
12794     case ISD::OR: {
12795       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12796         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12797         if (EFLAGS.getNode())
12798           return EFLAGS;
12799       }
12800       Opcode = X86ISD::OR;
12801       break;
12802     }
12803     }
12804
12805     NumOperands = 2;
12806     break;
12807   case X86ISD::ADD:
12808   case X86ISD::SUB:
12809   case X86ISD::INC:
12810   case X86ISD::DEC:
12811   case X86ISD::OR:
12812   case X86ISD::XOR:
12813   case X86ISD::AND:
12814     return SDValue(Op.getNode(), 1);
12815   default:
12816   default_case:
12817     break;
12818   }
12819
12820   // If we found that truncation is beneficial, perform the truncation and
12821   // update 'Op'.
12822   if (NeedTruncation) {
12823     EVT VT = Op.getValueType();
12824     SDValue WideVal = Op->getOperand(0);
12825     EVT WideVT = WideVal.getValueType();
12826     unsigned ConvertedOp = 0;
12827     // Use a target machine opcode to prevent further DAGCombine
12828     // optimizations that may separate the arithmetic operations
12829     // from the setcc node.
12830     switch (WideVal.getOpcode()) {
12831       default: break;
12832       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12833       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12834       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12835       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12836       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12837     }
12838
12839     if (ConvertedOp) {
12840       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12841       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12842         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12843         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12844         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12845       }
12846     }
12847   }
12848
12849   if (Opcode == 0)
12850     // Emit a CMP with 0, which is the TEST pattern.
12851     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12852                        DAG.getConstant(0, dl, Op.getValueType()));
12853
12854   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12855   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12856
12857   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12858   DAG.ReplaceAllUsesWith(Op, New);
12859   return SDValue(New.getNode(), 1);
12860 }
12861
12862 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12863 /// equivalent.
12864 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12865                                    SDLoc dl, SelectionDAG &DAG) const {
12866   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12867     if (C->getAPIntValue() == 0)
12868       return EmitTest(Op0, X86CC, dl, DAG);
12869
12870      if (Op0.getValueType() == MVT::i1)
12871        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12872   }
12873
12874   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12875        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12876     // Do the comparison at i32 if it's smaller, besides the Atom case.
12877     // This avoids subregister aliasing issues. Keep the smaller reference
12878     // if we're optimizing for size, however, as that'll allow better folding
12879     // of memory operations.
12880     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12881         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12882             Attribute::MinSize) &&
12883         !Subtarget->isAtom()) {
12884       unsigned ExtendOp =
12885           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12886       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12887       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12888     }
12889     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12890     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12891     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12892                               Op0, Op1);
12893     return SDValue(Sub.getNode(), 1);
12894   }
12895   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12896 }
12897
12898 /// Convert a comparison if required by the subtarget.
12899 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12900                                                  SelectionDAG &DAG) const {
12901   // If the subtarget does not support the FUCOMI instruction, floating-point
12902   // comparisons have to be converted.
12903   if (Subtarget->hasCMov() ||
12904       Cmp.getOpcode() != X86ISD::CMP ||
12905       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12906       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12907     return Cmp;
12908
12909   // The instruction selector will select an FUCOM instruction instead of
12910   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12911   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12912   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12913   SDLoc dl(Cmp);
12914   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12915   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12916   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12917                             DAG.getConstant(8, dl, MVT::i8));
12918   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12919   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12920 }
12921
12922 /// The minimum architected relative accuracy is 2^-12. We need one
12923 /// Newton-Raphson step to have a good float result (24 bits of precision).
12924 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12925                                             DAGCombinerInfo &DCI,
12926                                             unsigned &RefinementSteps,
12927                                             bool &UseOneConstNR) const {
12928   // FIXME: We should use instruction latency models to calculate the cost of
12929   // each potential sequence, but this is very hard to do reliably because
12930   // at least Intel's Core* chips have variable timing based on the number of
12931   // significant digits in the divisor and/or sqrt operand.
12932   if (!Subtarget->useSqrtEst())
12933     return SDValue();
12934
12935   EVT VT = Op.getValueType();
12936
12937   // SSE1 has rsqrtss and rsqrtps.
12938   // TODO: Add support for AVX512 (v16f32).
12939   // It is likely not profitable to do this for f64 because a double-precision
12940   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12941   // instructions: convert to single, rsqrtss, convert back to double, refine
12942   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12943   // along with FMA, this could be a throughput win.
12944   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12945       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12946     RefinementSteps = 1;
12947     UseOneConstNR = false;
12948     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12949   }
12950   return SDValue();
12951 }
12952
12953 /// The minimum architected relative accuracy is 2^-12. We need one
12954 /// Newton-Raphson step to have a good float result (24 bits of precision).
12955 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12956                                             DAGCombinerInfo &DCI,
12957                                             unsigned &RefinementSteps) const {
12958   // FIXME: We should use instruction latency models to calculate the cost of
12959   // each potential sequence, but this is very hard to do reliably because
12960   // at least Intel's Core* chips have variable timing based on the number of
12961   // significant digits in the divisor.
12962   if (!Subtarget->useReciprocalEst())
12963     return SDValue();
12964
12965   EVT VT = Op.getValueType();
12966
12967   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12968   // TODO: Add support for AVX512 (v16f32).
12969   // It is likely not profitable to do this for f64 because a double-precision
12970   // reciprocal estimate with refinement on x86 prior to FMA requires
12971   // 15 instructions: convert to single, rcpss, convert back to double, refine
12972   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12973   // along with FMA, this could be a throughput win.
12974   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12975       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12976     RefinementSteps = ReciprocalEstimateRefinementSteps;
12977     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12978   }
12979   return SDValue();
12980 }
12981
12982 /// If we have at least two divisions that use the same divisor, convert to
12983 /// multplication by a reciprocal. This may need to be adjusted for a given
12984 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12985 /// This is because we still need one division to calculate the reciprocal and
12986 /// then we need two multiplies by that reciprocal as replacements for the
12987 /// original divisions.
12988 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12989   return NumUsers > 1;
12990 }
12991
12992 static bool isAllOnes(SDValue V) {
12993   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12994   return C && C->isAllOnesValue();
12995 }
12996
12997 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12998 /// if it's possible.
12999 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13000                                      SDLoc dl, SelectionDAG &DAG) const {
13001   SDValue Op0 = And.getOperand(0);
13002   SDValue Op1 = And.getOperand(1);
13003   if (Op0.getOpcode() == ISD::TRUNCATE)
13004     Op0 = Op0.getOperand(0);
13005   if (Op1.getOpcode() == ISD::TRUNCATE)
13006     Op1 = Op1.getOperand(0);
13007
13008   SDValue LHS, RHS;
13009   if (Op1.getOpcode() == ISD::SHL)
13010     std::swap(Op0, Op1);
13011   if (Op0.getOpcode() == ISD::SHL) {
13012     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13013       if (And00C->getZExtValue() == 1) {
13014         // If we looked past a truncate, check that it's only truncating away
13015         // known zeros.
13016         unsigned BitWidth = Op0.getValueSizeInBits();
13017         unsigned AndBitWidth = And.getValueSizeInBits();
13018         if (BitWidth > AndBitWidth) {
13019           APInt Zeros, Ones;
13020           DAG.computeKnownBits(Op0, Zeros, Ones);
13021           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13022             return SDValue();
13023         }
13024         LHS = Op1;
13025         RHS = Op0.getOperand(1);
13026       }
13027   } else if (Op1.getOpcode() == ISD::Constant) {
13028     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13029     uint64_t AndRHSVal = AndRHS->getZExtValue();
13030     SDValue AndLHS = Op0;
13031
13032     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13033       LHS = AndLHS.getOperand(0);
13034       RHS = AndLHS.getOperand(1);
13035     }
13036
13037     // Use BT if the immediate can't be encoded in a TEST instruction.
13038     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13039       LHS = AndLHS;
13040       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13041     }
13042   }
13043
13044   if (LHS.getNode()) {
13045     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13046     // instruction.  Since the shift amount is in-range-or-undefined, we know
13047     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13048     // the encoding for the i16 version is larger than the i32 version.
13049     // Also promote i16 to i32 for performance / code size reason.
13050     if (LHS.getValueType() == MVT::i8 ||
13051         LHS.getValueType() == MVT::i16)
13052       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13053
13054     // If the operand types disagree, extend the shift amount to match.  Since
13055     // BT ignores high bits (like shifts) we can use anyextend.
13056     if (LHS.getValueType() != RHS.getValueType())
13057       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13058
13059     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13060     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13061     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13062                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13063   }
13064
13065   return SDValue();
13066 }
13067
13068 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13069 /// mask CMPs.
13070 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13071                               SDValue &Op1) {
13072   unsigned SSECC;
13073   bool Swap = false;
13074
13075   // SSE Condition code mapping:
13076   //  0 - EQ
13077   //  1 - LT
13078   //  2 - LE
13079   //  3 - UNORD
13080   //  4 - NEQ
13081   //  5 - NLT
13082   //  6 - NLE
13083   //  7 - ORD
13084   switch (SetCCOpcode) {
13085   default: llvm_unreachable("Unexpected SETCC condition");
13086   case ISD::SETOEQ:
13087   case ISD::SETEQ:  SSECC = 0; break;
13088   case ISD::SETOGT:
13089   case ISD::SETGT:  Swap = true; // Fallthrough
13090   case ISD::SETLT:
13091   case ISD::SETOLT: SSECC = 1; break;
13092   case ISD::SETOGE:
13093   case ISD::SETGE:  Swap = true; // Fallthrough
13094   case ISD::SETLE:
13095   case ISD::SETOLE: SSECC = 2; break;
13096   case ISD::SETUO:  SSECC = 3; break;
13097   case ISD::SETUNE:
13098   case ISD::SETNE:  SSECC = 4; break;
13099   case ISD::SETULE: Swap = true; // Fallthrough
13100   case ISD::SETUGE: SSECC = 5; break;
13101   case ISD::SETULT: Swap = true; // Fallthrough
13102   case ISD::SETUGT: SSECC = 6; break;
13103   case ISD::SETO:   SSECC = 7; break;
13104   case ISD::SETUEQ:
13105   case ISD::SETONE: SSECC = 8; break;
13106   }
13107   if (Swap)
13108     std::swap(Op0, Op1);
13109
13110   return SSECC;
13111 }
13112
13113 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13114 // ones, and then concatenate the result back.
13115 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13116   MVT VT = Op.getSimpleValueType();
13117
13118   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13119          "Unsupported value type for operation");
13120
13121   unsigned NumElems = VT.getVectorNumElements();
13122   SDLoc dl(Op);
13123   SDValue CC = Op.getOperand(2);
13124
13125   // Extract the LHS vectors
13126   SDValue LHS = Op.getOperand(0);
13127   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13128   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13129
13130   // Extract the RHS vectors
13131   SDValue RHS = Op.getOperand(1);
13132   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13133   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13134
13135   // Issue the operation on the smaller types and concatenate the result back
13136   MVT EltVT = VT.getVectorElementType();
13137   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13138   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13139                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13140                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13141 }
13142
13143 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13144   SDValue Op0 = Op.getOperand(0);
13145   SDValue Op1 = Op.getOperand(1);
13146   SDValue CC = Op.getOperand(2);
13147   MVT VT = Op.getSimpleValueType();
13148   SDLoc dl(Op);
13149
13150   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13151          "Unexpected type for boolean compare operation");
13152   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13153   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13154                                DAG.getConstant(-1, dl, VT));
13155   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13156                                DAG.getConstant(-1, dl, VT));
13157   switch (SetCCOpcode) {
13158   default: llvm_unreachable("Unexpected SETCC condition");
13159   case ISD::SETNE:
13160     // (x != y) -> ~(x ^ y)
13161     return DAG.getNode(ISD::XOR, dl, VT,
13162                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13163                        DAG.getConstant(-1, dl, VT));
13164   case ISD::SETEQ:
13165     // (x == y) -> (x ^ y)
13166     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13167   case ISD::SETUGT:
13168   case ISD::SETGT:
13169     // (x > y) -> (x & ~y)
13170     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13171   case ISD::SETULT:
13172   case ISD::SETLT:
13173     // (x < y) -> (~x & y)
13174     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13175   case ISD::SETULE:
13176   case ISD::SETLE:
13177     // (x <= y) -> (~x | y)
13178     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13179   case ISD::SETUGE:
13180   case ISD::SETGE:
13181     // (x >=y) -> (x | ~y)
13182     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13183   }
13184 }
13185
13186 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13187                                      const X86Subtarget *Subtarget) {
13188   SDValue Op0 = Op.getOperand(0);
13189   SDValue Op1 = Op.getOperand(1);
13190   SDValue CC = Op.getOperand(2);
13191   MVT VT = Op.getSimpleValueType();
13192   SDLoc dl(Op);
13193
13194   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13195          Op.getValueType().getScalarType() == MVT::i1 &&
13196          "Cannot set masked compare for this operation");
13197
13198   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13199   unsigned  Opc = 0;
13200   bool Unsigned = false;
13201   bool Swap = false;
13202   unsigned SSECC;
13203   switch (SetCCOpcode) {
13204   default: llvm_unreachable("Unexpected SETCC condition");
13205   case ISD::SETNE:  SSECC = 4; break;
13206   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13207   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13208   case ISD::SETLT:  Swap = true; //fall-through
13209   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13210   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13211   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13212   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13213   case ISD::SETULE: Unsigned = true; //fall-through
13214   case ISD::SETLE:  SSECC = 2; break;
13215   }
13216
13217   if (Swap)
13218     std::swap(Op0, Op1);
13219   if (Opc)
13220     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13221   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13222   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13223                      DAG.getConstant(SSECC, dl, MVT::i8));
13224 }
13225
13226 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13227 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13228 /// return an empty value.
13229 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13230 {
13231   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13232   if (!BV)
13233     return SDValue();
13234
13235   MVT VT = Op1.getSimpleValueType();
13236   MVT EVT = VT.getVectorElementType();
13237   unsigned n = VT.getVectorNumElements();
13238   SmallVector<SDValue, 8> ULTOp1;
13239
13240   for (unsigned i = 0; i < n; ++i) {
13241     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13242     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13243       return SDValue();
13244
13245     // Avoid underflow.
13246     APInt Val = Elt->getAPIntValue();
13247     if (Val == 0)
13248       return SDValue();
13249
13250     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13251   }
13252
13253   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13254 }
13255
13256 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13257                            SelectionDAG &DAG) {
13258   SDValue Op0 = Op.getOperand(0);
13259   SDValue Op1 = Op.getOperand(1);
13260   SDValue CC = Op.getOperand(2);
13261   MVT VT = Op.getSimpleValueType();
13262   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13263   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13264   SDLoc dl(Op);
13265
13266   if (isFP) {
13267 #ifndef NDEBUG
13268     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13269     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13270 #endif
13271
13272     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13273     unsigned Opc = X86ISD::CMPP;
13274     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13275       assert(VT.getVectorNumElements() <= 16);
13276       Opc = X86ISD::CMPM;
13277     }
13278     // In the two special cases we can't handle, emit two comparisons.
13279     if (SSECC == 8) {
13280       unsigned CC0, CC1;
13281       unsigned CombineOpc;
13282       if (SetCCOpcode == ISD::SETUEQ) {
13283         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13284       } else {
13285         assert(SetCCOpcode == ISD::SETONE);
13286         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13287       }
13288
13289       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13290                                  DAG.getConstant(CC0, dl, MVT::i8));
13291       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13292                                  DAG.getConstant(CC1, dl, MVT::i8));
13293       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13294     }
13295     // Handle all other FP comparisons here.
13296     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13297                        DAG.getConstant(SSECC, dl, MVT::i8));
13298   }
13299
13300   // Break 256-bit integer vector compare into smaller ones.
13301   if (VT.is256BitVector() && !Subtarget->hasInt256())
13302     return Lower256IntVSETCC(Op, DAG);
13303
13304   EVT OpVT = Op1.getValueType();
13305   if (OpVT.getVectorElementType() == MVT::i1)
13306     return LowerBoolVSETCC_AVX512(Op, DAG);
13307
13308   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13309   if (Subtarget->hasAVX512()) {
13310     if (Op1.getValueType().is512BitVector() ||
13311         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13312         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13313       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13314
13315     // In AVX-512 architecture setcc returns mask with i1 elements,
13316     // But there is no compare instruction for i8 and i16 elements in KNL.
13317     // We are not talking about 512-bit operands in this case, these
13318     // types are illegal.
13319     if (MaskResult &&
13320         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13321          OpVT.getVectorElementType().getSizeInBits() >= 8))
13322       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13323                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13324   }
13325
13326   // We are handling one of the integer comparisons here.  Since SSE only has
13327   // GT and EQ comparisons for integer, swapping operands and multiple
13328   // operations may be required for some comparisons.
13329   unsigned Opc;
13330   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13331   bool Subus = false;
13332
13333   switch (SetCCOpcode) {
13334   default: llvm_unreachable("Unexpected SETCC condition");
13335   case ISD::SETNE:  Invert = true;
13336   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13337   case ISD::SETLT:  Swap = true;
13338   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13339   case ISD::SETGE:  Swap = true;
13340   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13341                     Invert = true; break;
13342   case ISD::SETULT: Swap = true;
13343   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13344                     FlipSigns = true; break;
13345   case ISD::SETUGE: Swap = true;
13346   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13347                     FlipSigns = true; Invert = true; break;
13348   }
13349
13350   // Special case: Use min/max operations for SETULE/SETUGE
13351   MVT VET = VT.getVectorElementType();
13352   bool hasMinMax =
13353        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13354     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13355
13356   if (hasMinMax) {
13357     switch (SetCCOpcode) {
13358     default: break;
13359     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13360     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13361     }
13362
13363     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13364   }
13365
13366   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13367   if (!MinMax && hasSubus) {
13368     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13369     // Op0 u<= Op1:
13370     //   t = psubus Op0, Op1
13371     //   pcmpeq t, <0..0>
13372     switch (SetCCOpcode) {
13373     default: break;
13374     case ISD::SETULT: {
13375       // If the comparison is against a constant we can turn this into a
13376       // setule.  With psubus, setule does not require a swap.  This is
13377       // beneficial because the constant in the register is no longer
13378       // destructed as the destination so it can be hoisted out of a loop.
13379       // Only do this pre-AVX since vpcmp* is no longer destructive.
13380       if (Subtarget->hasAVX())
13381         break;
13382       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13383       if (ULEOp1.getNode()) {
13384         Op1 = ULEOp1;
13385         Subus = true; Invert = false; Swap = false;
13386       }
13387       break;
13388     }
13389     // Psubus is better than flip-sign because it requires no inversion.
13390     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13391     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13392     }
13393
13394     if (Subus) {
13395       Opc = X86ISD::SUBUS;
13396       FlipSigns = false;
13397     }
13398   }
13399
13400   if (Swap)
13401     std::swap(Op0, Op1);
13402
13403   // Check that the operation in question is available (most are plain SSE2,
13404   // but PCMPGTQ and PCMPEQQ have different requirements).
13405   if (VT == MVT::v2i64) {
13406     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13407       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13408
13409       // First cast everything to the right type.
13410       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13411       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13412
13413       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13414       // bits of the inputs before performing those operations. The lower
13415       // compare is always unsigned.
13416       SDValue SB;
13417       if (FlipSigns) {
13418         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13419       } else {
13420         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13421         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13422         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13423                          Sign, Zero, Sign, Zero);
13424       }
13425       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13426       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13427
13428       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13429       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13430       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13431
13432       // Create masks for only the low parts/high parts of the 64 bit integers.
13433       static const int MaskHi[] = { 1, 1, 3, 3 };
13434       static const int MaskLo[] = { 0, 0, 2, 2 };
13435       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13436       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13437       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13438
13439       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13440       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13441
13442       if (Invert)
13443         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13444
13445       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13446     }
13447
13448     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13449       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13450       // pcmpeqd + pshufd + pand.
13451       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13452
13453       // First cast everything to the right type.
13454       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13455       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13456
13457       // Do the compare.
13458       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13459
13460       // Make sure the lower and upper halves are both all-ones.
13461       static const int Mask[] = { 1, 0, 3, 2 };
13462       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13463       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13464
13465       if (Invert)
13466         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13467
13468       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13469     }
13470   }
13471
13472   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13473   // bits of the inputs before performing those operations.
13474   if (FlipSigns) {
13475     EVT EltVT = VT.getVectorElementType();
13476     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13477                                  VT);
13478     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13479     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13480   }
13481
13482   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13483
13484   // If the logical-not of the result is required, perform that now.
13485   if (Invert)
13486     Result = DAG.getNOT(dl, Result, VT);
13487
13488   if (MinMax)
13489     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13490
13491   if (Subus)
13492     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13493                          getZeroVector(VT, Subtarget, DAG, dl));
13494
13495   return Result;
13496 }
13497
13498 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13499
13500   MVT VT = Op.getSimpleValueType();
13501
13502   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13503
13504   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13505          && "SetCC type must be 8-bit or 1-bit integer");
13506   SDValue Op0 = Op.getOperand(0);
13507   SDValue Op1 = Op.getOperand(1);
13508   SDLoc dl(Op);
13509   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13510
13511   // Optimize to BT if possible.
13512   // Lower (X & (1 << N)) == 0 to BT(X, N).
13513   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13514   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13515   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13516       Op1.getOpcode() == ISD::Constant &&
13517       cast<ConstantSDNode>(Op1)->isNullValue() &&
13518       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13519     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13520     if (NewSetCC.getNode()) {
13521       if (VT == MVT::i1)
13522         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13523       return NewSetCC;
13524     }
13525   }
13526
13527   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13528   // these.
13529   if (Op1.getOpcode() == ISD::Constant &&
13530       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13531        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13532       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13533
13534     // If the input is a setcc, then reuse the input setcc or use a new one with
13535     // the inverted condition.
13536     if (Op0.getOpcode() == X86ISD::SETCC) {
13537       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13538       bool Invert = (CC == ISD::SETNE) ^
13539         cast<ConstantSDNode>(Op1)->isNullValue();
13540       if (!Invert)
13541         return Op0;
13542
13543       CCode = X86::GetOppositeBranchCondition(CCode);
13544       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13545                                   DAG.getConstant(CCode, dl, MVT::i8),
13546                                   Op0.getOperand(1));
13547       if (VT == MVT::i1)
13548         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13549       return SetCC;
13550     }
13551   }
13552   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13553       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13554       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13555
13556     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13557     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13558   }
13559
13560   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13561   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13562   if (X86CC == X86::COND_INVALID)
13563     return SDValue();
13564
13565   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13566   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13567   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13568                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13569   if (VT == MVT::i1)
13570     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13571   return SetCC;
13572 }
13573
13574 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13575 static bool isX86LogicalCmp(SDValue Op) {
13576   unsigned Opc = Op.getNode()->getOpcode();
13577   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13578       Opc == X86ISD::SAHF)
13579     return true;
13580   if (Op.getResNo() == 1 &&
13581       (Opc == X86ISD::ADD ||
13582        Opc == X86ISD::SUB ||
13583        Opc == X86ISD::ADC ||
13584        Opc == X86ISD::SBB ||
13585        Opc == X86ISD::SMUL ||
13586        Opc == X86ISD::UMUL ||
13587        Opc == X86ISD::INC ||
13588        Opc == X86ISD::DEC ||
13589        Opc == X86ISD::OR ||
13590        Opc == X86ISD::XOR ||
13591        Opc == X86ISD::AND))
13592     return true;
13593
13594   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13595     return true;
13596
13597   return false;
13598 }
13599
13600 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13601   if (V.getOpcode() != ISD::TRUNCATE)
13602     return false;
13603
13604   SDValue VOp0 = V.getOperand(0);
13605   unsigned InBits = VOp0.getValueSizeInBits();
13606   unsigned Bits = V.getValueSizeInBits();
13607   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13608 }
13609
13610 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13611   bool addTest = true;
13612   SDValue Cond  = Op.getOperand(0);
13613   SDValue Op1 = Op.getOperand(1);
13614   SDValue Op2 = Op.getOperand(2);
13615   SDLoc DL(Op);
13616   EVT VT = Op1.getValueType();
13617   SDValue CC;
13618
13619   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13620   // are available or VBLENDV if AVX is available.
13621   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13622   if (Cond.getOpcode() == ISD::SETCC &&
13623       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13624        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13625       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13626     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13627     int SSECC = translateX86FSETCC(
13628         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13629
13630     if (SSECC != 8) {
13631       if (Subtarget->hasAVX512()) {
13632         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13633                                   DAG.getConstant(SSECC, DL, MVT::i8));
13634         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13635       }
13636
13637       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13638                                 DAG.getConstant(SSECC, DL, MVT::i8));
13639
13640       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13641       // of 3 logic instructions for size savings and potentially speed.
13642       // Unfortunately, there is no scalar form of VBLENDV.
13643
13644       // If either operand is a constant, don't try this. We can expect to
13645       // optimize away at least one of the logic instructions later in that
13646       // case, so that sequence would be faster than a variable blend.
13647
13648       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13649       // uses XMM0 as the selection register. That may need just as many
13650       // instructions as the AND/ANDN/OR sequence due to register moves, so
13651       // don't bother.
13652
13653       if (Subtarget->hasAVX() &&
13654           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13655
13656         // Convert to vectors, do a VSELECT, and convert back to scalar.
13657         // All of the conversions should be optimized away.
13658
13659         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13660         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13661         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13662         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13663
13664         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13665         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13666
13667         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13668
13669         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13670                            VSel, DAG.getIntPtrConstant(0, DL));
13671       }
13672       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13673       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13674       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13675     }
13676   }
13677
13678     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13679       SDValue Op1Scalar;
13680       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13681         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13682       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13683         Op1Scalar = Op1.getOperand(0);
13684       SDValue Op2Scalar;
13685       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13686         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13687       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13688         Op2Scalar = Op2.getOperand(0);
13689       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13690         SDValue newSelect = DAG.getNode(ISD::SELECT, DL, 
13691                                         Op1Scalar.getValueType(),
13692                                         Cond, Op1Scalar, Op2Scalar);
13693         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13694           return DAG.getNode(ISD::BITCAST, DL, VT, newSelect);
13695         SDValue ExtVec = DAG.getNode(ISD::BITCAST, DL, MVT::v8i1, newSelect);
13696         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13697                            DAG.getIntPtrConstant(0, DL));
13698     }
13699   }
13700
13701   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13702     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13703     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13704                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13705     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13706                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13707     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13708                                     Cond, Op1, Op2);
13709     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13710   }
13711
13712   if (Cond.getOpcode() == ISD::SETCC) {
13713     SDValue NewCond = LowerSETCC(Cond, DAG);
13714     if (NewCond.getNode())
13715       Cond = NewCond;
13716   }
13717
13718   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13719   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13720   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13721   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13722   if (Cond.getOpcode() == X86ISD::SETCC &&
13723       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13724       isZero(Cond.getOperand(1).getOperand(1))) {
13725     SDValue Cmp = Cond.getOperand(1);
13726
13727     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13728
13729     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13730         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13731       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13732
13733       SDValue CmpOp0 = Cmp.getOperand(0);
13734       // Apply further optimizations for special cases
13735       // (select (x != 0), -1, 0) -> neg & sbb
13736       // (select (x == 0), 0, -1) -> neg & sbb
13737       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13738         if (YC->isNullValue() &&
13739             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13740           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13741           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13742                                     DAG.getConstant(0, DL,
13743                                                     CmpOp0.getValueType()),
13744                                     CmpOp0);
13745           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13746                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13747                                     SDValue(Neg.getNode(), 1));
13748           return Res;
13749         }
13750
13751       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13752                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13753       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13754
13755       SDValue Res =   // Res = 0 or -1.
13756         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13757                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13758
13759       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13760         Res = DAG.getNOT(DL, Res, Res.getValueType());
13761
13762       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13763       if (!N2C || !N2C->isNullValue())
13764         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13765       return Res;
13766     }
13767   }
13768
13769   // Look past (and (setcc_carry (cmp ...)), 1).
13770   if (Cond.getOpcode() == ISD::AND &&
13771       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13772     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13773     if (C && C->getAPIntValue() == 1)
13774       Cond = Cond.getOperand(0);
13775   }
13776
13777   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13778   // setting operand in place of the X86ISD::SETCC.
13779   unsigned CondOpcode = Cond.getOpcode();
13780   if (CondOpcode == X86ISD::SETCC ||
13781       CondOpcode == X86ISD::SETCC_CARRY) {
13782     CC = Cond.getOperand(0);
13783
13784     SDValue Cmp = Cond.getOperand(1);
13785     unsigned Opc = Cmp.getOpcode();
13786     MVT VT = Op.getSimpleValueType();
13787
13788     bool IllegalFPCMov = false;
13789     if (VT.isFloatingPoint() && !VT.isVector() &&
13790         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13791       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13792
13793     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13794         Opc == X86ISD::BT) { // FIXME
13795       Cond = Cmp;
13796       addTest = false;
13797     }
13798   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13799              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13800              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13801               Cond.getOperand(0).getValueType() != MVT::i8)) {
13802     SDValue LHS = Cond.getOperand(0);
13803     SDValue RHS = Cond.getOperand(1);
13804     unsigned X86Opcode;
13805     unsigned X86Cond;
13806     SDVTList VTs;
13807     switch (CondOpcode) {
13808     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13809     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13810     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13811     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13812     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13813     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13814     default: llvm_unreachable("unexpected overflowing operator");
13815     }
13816     if (CondOpcode == ISD::UMULO)
13817       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13818                           MVT::i32);
13819     else
13820       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13821
13822     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13823
13824     if (CondOpcode == ISD::UMULO)
13825       Cond = X86Op.getValue(2);
13826     else
13827       Cond = X86Op.getValue(1);
13828
13829     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13830     addTest = false;
13831   }
13832
13833   if (addTest) {
13834     // Look pass the truncate if the high bits are known zero.
13835     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13836         Cond = Cond.getOperand(0);
13837
13838     // We know the result of AND is compared against zero. Try to match
13839     // it to BT.
13840     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13841       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13842       if (NewSetCC.getNode()) {
13843         CC = NewSetCC.getOperand(0);
13844         Cond = NewSetCC.getOperand(1);
13845         addTest = false;
13846       }
13847     }
13848   }
13849
13850   if (addTest) {
13851     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13852     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13853   }
13854
13855   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13856   // a <  b ?  0 : -1 -> RES = setcc_carry
13857   // a >= b ? -1 :  0 -> RES = setcc_carry
13858   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13859   if (Cond.getOpcode() == X86ISD::SUB) {
13860     Cond = ConvertCmpIfNecessary(Cond, DAG);
13861     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13862
13863     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13864         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13865       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13866                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13867                                 Cond);
13868       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13869         return DAG.getNOT(DL, Res, Res.getValueType());
13870       return Res;
13871     }
13872   }
13873
13874   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13875   // widen the cmov and push the truncate through. This avoids introducing a new
13876   // branch during isel and doesn't add any extensions.
13877   if (Op.getValueType() == MVT::i8 &&
13878       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13879     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13880     if (T1.getValueType() == T2.getValueType() &&
13881         // Blacklist CopyFromReg to avoid partial register stalls.
13882         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13883       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13884       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13885       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13886     }
13887   }
13888
13889   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13890   // condition is true.
13891   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13892   SDValue Ops[] = { Op2, Op1, CC, Cond };
13893   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13894 }
13895
13896 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
13897                                        const X86Subtarget *Subtarget,
13898                                        SelectionDAG &DAG) {
13899   MVT VT = Op->getSimpleValueType(0);
13900   SDValue In = Op->getOperand(0);
13901   MVT InVT = In.getSimpleValueType();
13902   MVT VTElt = VT.getVectorElementType();
13903   MVT InVTElt = InVT.getVectorElementType();
13904   SDLoc dl(Op);
13905
13906   // SKX processor
13907   if ((InVTElt == MVT::i1) &&
13908       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13909         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13910
13911        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13912         VTElt.getSizeInBits() <= 16)) ||
13913
13914        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13915         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13916
13917        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13918         VTElt.getSizeInBits() >= 32))))
13919     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13920
13921   unsigned int NumElts = VT.getVectorNumElements();
13922
13923   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13924     return SDValue();
13925
13926   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13927     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13928       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13929     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13930   }
13931
13932   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13933   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13934   SDValue NegOne =
13935    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13936                    ExtVT);
13937   SDValue Zero =
13938    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13939
13940   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13941   if (VT.is512BitVector())
13942     return V;
13943   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13944 }
13945
13946 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
13947                                              const X86Subtarget *Subtarget,
13948                                              SelectionDAG &DAG) {
13949   SDValue In = Op->getOperand(0);
13950   MVT VT = Op->getSimpleValueType(0);
13951   MVT InVT = In.getSimpleValueType();
13952   assert(VT.getSizeInBits() == InVT.getSizeInBits());
13953
13954   MVT InSVT = InVT.getScalarType();
13955   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
13956
13957   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13958     return SDValue();
13959   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
13960     return SDValue();
13961
13962   SDLoc dl(Op);
13963
13964   // SSE41 targets can use the pmovsx* instructions directly.
13965   if (Subtarget->hasSSE41())
13966     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13967
13968   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
13969   SDValue Curr = In;
13970   MVT CurrVT = InVT;
13971
13972   // As SRAI is only available on i16/i32 types, we expand only up to i32
13973   // and handle i64 separately.
13974   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
13975     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
13976     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
13977     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
13978     Curr = DAG.getNode(ISD::BITCAST, dl, CurrVT, Curr);
13979   }
13980
13981   SDValue SignExt = Curr;
13982   if (CurrVT != InVT) {
13983     unsigned SignExtShift =
13984         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
13985     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
13986                           DAG.getConstant(SignExtShift, dl, MVT::i8));
13987   }
13988
13989   if (CurrVT == VT)
13990     return SignExt;
13991
13992   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
13993     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
13994                                DAG.getConstant(31, dl, MVT::i8));
13995     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
13996     return DAG.getNode(ISD::BITCAST, dl, VT, Ext);
13997   }
13998
13999   return SDValue();
14000 }
14001
14002 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14003                                 SelectionDAG &DAG) {
14004   MVT VT = Op->getSimpleValueType(0);
14005   SDValue In = Op->getOperand(0);
14006   MVT InVT = In.getSimpleValueType();
14007   SDLoc dl(Op);
14008
14009   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14010     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14011
14012   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14013       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14014       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14015     return SDValue();
14016
14017   if (Subtarget->hasInt256())
14018     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14019
14020   // Optimize vectors in AVX mode
14021   // Sign extend  v8i16 to v8i32 and
14022   //              v4i32 to v4i64
14023   //
14024   // Divide input vector into two parts
14025   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14026   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14027   // concat the vectors to original VT
14028
14029   unsigned NumElems = InVT.getVectorNumElements();
14030   SDValue Undef = DAG.getUNDEF(InVT);
14031
14032   SmallVector<int,8> ShufMask1(NumElems, -1);
14033   for (unsigned i = 0; i != NumElems/2; ++i)
14034     ShufMask1[i] = i;
14035
14036   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14037
14038   SmallVector<int,8> ShufMask2(NumElems, -1);
14039   for (unsigned i = 0; i != NumElems/2; ++i)
14040     ShufMask2[i] = i + NumElems/2;
14041
14042   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14043
14044   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14045                                 VT.getVectorNumElements()/2);
14046
14047   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14048   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14049
14050   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14051 }
14052
14053 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14054 // may emit an illegal shuffle but the expansion is still better than scalar
14055 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14056 // we'll emit a shuffle and a arithmetic shift.
14057 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14058 // TODO: It is possible to support ZExt by zeroing the undef values during
14059 // the shuffle phase or after the shuffle.
14060 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14061                                  SelectionDAG &DAG) {
14062   MVT RegVT = Op.getSimpleValueType();
14063   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14064   assert(RegVT.isInteger() &&
14065          "We only custom lower integer vector sext loads.");
14066
14067   // Nothing useful we can do without SSE2 shuffles.
14068   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14069
14070   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14071   SDLoc dl(Ld);
14072   EVT MemVT = Ld->getMemoryVT();
14073   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14074   unsigned RegSz = RegVT.getSizeInBits();
14075
14076   ISD::LoadExtType Ext = Ld->getExtensionType();
14077
14078   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14079          && "Only anyext and sext are currently implemented.");
14080   assert(MemVT != RegVT && "Cannot extend to the same type");
14081   assert(MemVT.isVector() && "Must load a vector from memory");
14082
14083   unsigned NumElems = RegVT.getVectorNumElements();
14084   unsigned MemSz = MemVT.getSizeInBits();
14085   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14086
14087   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14088     // The only way in which we have a legal 256-bit vector result but not the
14089     // integer 256-bit operations needed to directly lower a sextload is if we
14090     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14091     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14092     // correctly legalized. We do this late to allow the canonical form of
14093     // sextload to persist throughout the rest of the DAG combiner -- it wants
14094     // to fold together any extensions it can, and so will fuse a sign_extend
14095     // of an sextload into a sextload targeting a wider value.
14096     SDValue Load;
14097     if (MemSz == 128) {
14098       // Just switch this to a normal load.
14099       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14100                                        "it must be a legal 128-bit vector "
14101                                        "type!");
14102       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14103                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14104                   Ld->isInvariant(), Ld->getAlignment());
14105     } else {
14106       assert(MemSz < 128 &&
14107              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14108       // Do an sext load to a 128-bit vector type. We want to use the same
14109       // number of elements, but elements half as wide. This will end up being
14110       // recursively lowered by this routine, but will succeed as we definitely
14111       // have all the necessary features if we're using AVX1.
14112       EVT HalfEltVT =
14113           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14114       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14115       Load =
14116           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14117                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14118                          Ld->isNonTemporal(), Ld->isInvariant(),
14119                          Ld->getAlignment());
14120     }
14121
14122     // Replace chain users with the new chain.
14123     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14124     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14125
14126     // Finally, do a normal sign-extend to the desired register.
14127     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14128   }
14129
14130   // All sizes must be a power of two.
14131   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14132          "Non-power-of-two elements are not custom lowered!");
14133
14134   // Attempt to load the original value using scalar loads.
14135   // Find the largest scalar type that divides the total loaded size.
14136   MVT SclrLoadTy = MVT::i8;
14137   for (MVT Tp : MVT::integer_valuetypes()) {
14138     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14139       SclrLoadTy = Tp;
14140     }
14141   }
14142
14143   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14144   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14145       (64 <= MemSz))
14146     SclrLoadTy = MVT::f64;
14147
14148   // Calculate the number of scalar loads that we need to perform
14149   // in order to load our vector from memory.
14150   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14151
14152   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14153          "Can only lower sext loads with a single scalar load!");
14154
14155   unsigned loadRegZize = RegSz;
14156   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14157     loadRegZize = 128;
14158
14159   // Represent our vector as a sequence of elements which are the
14160   // largest scalar that we can load.
14161   EVT LoadUnitVecVT = EVT::getVectorVT(
14162       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14163
14164   // Represent the data using the same element type that is stored in
14165   // memory. In practice, we ''widen'' MemVT.
14166   EVT WideVecVT =
14167       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14168                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14169
14170   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14171          "Invalid vector type");
14172
14173   // We can't shuffle using an illegal type.
14174   assert(TLI.isTypeLegal(WideVecVT) &&
14175          "We only lower types that form legal widened vector types");
14176
14177   SmallVector<SDValue, 8> Chains;
14178   SDValue Ptr = Ld->getBasePtr();
14179   SDValue Increment =
14180       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14181   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14182
14183   for (unsigned i = 0; i < NumLoads; ++i) {
14184     // Perform a single load.
14185     SDValue ScalarLoad =
14186         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14187                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14188                     Ld->getAlignment());
14189     Chains.push_back(ScalarLoad.getValue(1));
14190     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14191     // another round of DAGCombining.
14192     if (i == 0)
14193       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14194     else
14195       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14196                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14197
14198     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14199   }
14200
14201   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14202
14203   // Bitcast the loaded value to a vector of the original element type, in
14204   // the size of the target vector type.
14205   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14206   unsigned SizeRatio = RegSz / MemSz;
14207
14208   if (Ext == ISD::SEXTLOAD) {
14209     // If we have SSE4.1, we can directly emit a VSEXT node.
14210     if (Subtarget->hasSSE41()) {
14211       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14212       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14213       return Sext;
14214     }
14215
14216     // Otherwise we'll shuffle the small elements in the high bits of the
14217     // larger type and perform an arithmetic shift. If the shift is not legal
14218     // it's better to scalarize.
14219     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14220            "We can't implement a sext load without an arithmetic right shift!");
14221
14222     // Redistribute the loaded elements into the different locations.
14223     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14224     for (unsigned i = 0; i != NumElems; ++i)
14225       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14226
14227     SDValue Shuff = DAG.getVectorShuffle(
14228         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14229
14230     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14231
14232     // Build the arithmetic shift.
14233     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14234                    MemVT.getVectorElementType().getSizeInBits();
14235     Shuff =
14236         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14237                     DAG.getConstant(Amt, dl, RegVT));
14238
14239     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14240     return Shuff;
14241   }
14242
14243   // Redistribute the loaded elements into the different locations.
14244   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14245   for (unsigned i = 0; i != NumElems; ++i)
14246     ShuffleVec[i * SizeRatio] = i;
14247
14248   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14249                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14250
14251   // Bitcast to the requested type.
14252   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14253   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14254   return Shuff;
14255 }
14256
14257 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14258 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14259 // from the AND / OR.
14260 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14261   Opc = Op.getOpcode();
14262   if (Opc != ISD::OR && Opc != ISD::AND)
14263     return false;
14264   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14265           Op.getOperand(0).hasOneUse() &&
14266           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14267           Op.getOperand(1).hasOneUse());
14268 }
14269
14270 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14271 // 1 and that the SETCC node has a single use.
14272 static bool isXor1OfSetCC(SDValue Op) {
14273   if (Op.getOpcode() != ISD::XOR)
14274     return false;
14275   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14276   if (N1C && N1C->getAPIntValue() == 1) {
14277     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14278       Op.getOperand(0).hasOneUse();
14279   }
14280   return false;
14281 }
14282
14283 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14284   bool addTest = true;
14285   SDValue Chain = Op.getOperand(0);
14286   SDValue Cond  = Op.getOperand(1);
14287   SDValue Dest  = Op.getOperand(2);
14288   SDLoc dl(Op);
14289   SDValue CC;
14290   bool Inverted = false;
14291
14292   if (Cond.getOpcode() == ISD::SETCC) {
14293     // Check for setcc([su]{add,sub,mul}o == 0).
14294     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14295         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14296         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14297         Cond.getOperand(0).getResNo() == 1 &&
14298         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14299          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14300          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14301          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14302          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14303          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14304       Inverted = true;
14305       Cond = Cond.getOperand(0);
14306     } else {
14307       SDValue NewCond = LowerSETCC(Cond, DAG);
14308       if (NewCond.getNode())
14309         Cond = NewCond;
14310     }
14311   }
14312 #if 0
14313   // FIXME: LowerXALUO doesn't handle these!!
14314   else if (Cond.getOpcode() == X86ISD::ADD  ||
14315            Cond.getOpcode() == X86ISD::SUB  ||
14316            Cond.getOpcode() == X86ISD::SMUL ||
14317            Cond.getOpcode() == X86ISD::UMUL)
14318     Cond = LowerXALUO(Cond, DAG);
14319 #endif
14320
14321   // Look pass (and (setcc_carry (cmp ...)), 1).
14322   if (Cond.getOpcode() == ISD::AND &&
14323       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14324     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14325     if (C && C->getAPIntValue() == 1)
14326       Cond = Cond.getOperand(0);
14327   }
14328
14329   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14330   // setting operand in place of the X86ISD::SETCC.
14331   unsigned CondOpcode = Cond.getOpcode();
14332   if (CondOpcode == X86ISD::SETCC ||
14333       CondOpcode == X86ISD::SETCC_CARRY) {
14334     CC = Cond.getOperand(0);
14335
14336     SDValue Cmp = Cond.getOperand(1);
14337     unsigned Opc = Cmp.getOpcode();
14338     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14339     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14340       Cond = Cmp;
14341       addTest = false;
14342     } else {
14343       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14344       default: break;
14345       case X86::COND_O:
14346       case X86::COND_B:
14347         // These can only come from an arithmetic instruction with overflow,
14348         // e.g. SADDO, UADDO.
14349         Cond = Cond.getNode()->getOperand(1);
14350         addTest = false;
14351         break;
14352       }
14353     }
14354   }
14355   CondOpcode = Cond.getOpcode();
14356   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14357       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14358       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14359        Cond.getOperand(0).getValueType() != MVT::i8)) {
14360     SDValue LHS = Cond.getOperand(0);
14361     SDValue RHS = Cond.getOperand(1);
14362     unsigned X86Opcode;
14363     unsigned X86Cond;
14364     SDVTList VTs;
14365     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14366     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14367     // X86ISD::INC).
14368     switch (CondOpcode) {
14369     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14370     case ISD::SADDO:
14371       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14372         if (C->isOne()) {
14373           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14374           break;
14375         }
14376       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14377     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14378     case ISD::SSUBO:
14379       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14380         if (C->isOne()) {
14381           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14382           break;
14383         }
14384       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14385     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14386     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14387     default: llvm_unreachable("unexpected overflowing operator");
14388     }
14389     if (Inverted)
14390       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14391     if (CondOpcode == ISD::UMULO)
14392       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14393                           MVT::i32);
14394     else
14395       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14396
14397     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14398
14399     if (CondOpcode == ISD::UMULO)
14400       Cond = X86Op.getValue(2);
14401     else
14402       Cond = X86Op.getValue(1);
14403
14404     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14405     addTest = false;
14406   } else {
14407     unsigned CondOpc;
14408     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14409       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14410       if (CondOpc == ISD::OR) {
14411         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14412         // two branches instead of an explicit OR instruction with a
14413         // separate test.
14414         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14415             isX86LogicalCmp(Cmp)) {
14416           CC = Cond.getOperand(0).getOperand(0);
14417           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14418                               Chain, Dest, CC, Cmp);
14419           CC = Cond.getOperand(1).getOperand(0);
14420           Cond = Cmp;
14421           addTest = false;
14422         }
14423       } else { // ISD::AND
14424         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14425         // two branches instead of an explicit AND instruction with a
14426         // separate test. However, we only do this if this block doesn't
14427         // have a fall-through edge, because this requires an explicit
14428         // jmp when the condition is false.
14429         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14430             isX86LogicalCmp(Cmp) &&
14431             Op.getNode()->hasOneUse()) {
14432           X86::CondCode CCode =
14433             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14434           CCode = X86::GetOppositeBranchCondition(CCode);
14435           CC = DAG.getConstant(CCode, dl, MVT::i8);
14436           SDNode *User = *Op.getNode()->use_begin();
14437           // Look for an unconditional branch following this conditional branch.
14438           // We need this because we need to reverse the successors in order
14439           // to implement FCMP_OEQ.
14440           if (User->getOpcode() == ISD::BR) {
14441             SDValue FalseBB = User->getOperand(1);
14442             SDNode *NewBR =
14443               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14444             assert(NewBR == User);
14445             (void)NewBR;
14446             Dest = FalseBB;
14447
14448             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14449                                 Chain, Dest, CC, Cmp);
14450             X86::CondCode CCode =
14451               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14452             CCode = X86::GetOppositeBranchCondition(CCode);
14453             CC = DAG.getConstant(CCode, dl, MVT::i8);
14454             Cond = Cmp;
14455             addTest = false;
14456           }
14457         }
14458       }
14459     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14460       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14461       // It should be transformed during dag combiner except when the condition
14462       // is set by a arithmetics with overflow node.
14463       X86::CondCode CCode =
14464         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14465       CCode = X86::GetOppositeBranchCondition(CCode);
14466       CC = DAG.getConstant(CCode, dl, MVT::i8);
14467       Cond = Cond.getOperand(0).getOperand(1);
14468       addTest = false;
14469     } else if (Cond.getOpcode() == ISD::SETCC &&
14470                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14471       // For FCMP_OEQ, we can emit
14472       // two branches instead of an explicit AND instruction with a
14473       // separate test. However, we only do this if this block doesn't
14474       // have a fall-through edge, because this requires an explicit
14475       // jmp when the condition is false.
14476       if (Op.getNode()->hasOneUse()) {
14477         SDNode *User = *Op.getNode()->use_begin();
14478         // Look for an unconditional branch following this conditional branch.
14479         // We need this because we need to reverse the successors in order
14480         // to implement FCMP_OEQ.
14481         if (User->getOpcode() == ISD::BR) {
14482           SDValue FalseBB = User->getOperand(1);
14483           SDNode *NewBR =
14484             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14485           assert(NewBR == User);
14486           (void)NewBR;
14487           Dest = FalseBB;
14488
14489           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14490                                     Cond.getOperand(0), Cond.getOperand(1));
14491           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14492           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14493           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14494                               Chain, Dest, CC, Cmp);
14495           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14496           Cond = Cmp;
14497           addTest = false;
14498         }
14499       }
14500     } else if (Cond.getOpcode() == ISD::SETCC &&
14501                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14502       // For FCMP_UNE, we can emit
14503       // two branches instead of an explicit AND instruction with a
14504       // separate test. However, we only do this if this block doesn't
14505       // have a fall-through edge, because this requires an explicit
14506       // jmp when the condition is false.
14507       if (Op.getNode()->hasOneUse()) {
14508         SDNode *User = *Op.getNode()->use_begin();
14509         // Look for an unconditional branch following this conditional branch.
14510         // We need this because we need to reverse the successors in order
14511         // to implement FCMP_UNE.
14512         if (User->getOpcode() == ISD::BR) {
14513           SDValue FalseBB = User->getOperand(1);
14514           SDNode *NewBR =
14515             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14516           assert(NewBR == User);
14517           (void)NewBR;
14518
14519           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14520                                     Cond.getOperand(0), Cond.getOperand(1));
14521           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14522           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14523           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14524                               Chain, Dest, CC, Cmp);
14525           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14526           Cond = Cmp;
14527           addTest = false;
14528           Dest = FalseBB;
14529         }
14530       }
14531     }
14532   }
14533
14534   if (addTest) {
14535     // Look pass the truncate if the high bits are known zero.
14536     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14537         Cond = Cond.getOperand(0);
14538
14539     // We know the result of AND is compared against zero. Try to match
14540     // it to BT.
14541     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14542       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14543       if (NewSetCC.getNode()) {
14544         CC = NewSetCC.getOperand(0);
14545         Cond = NewSetCC.getOperand(1);
14546         addTest = false;
14547       }
14548     }
14549   }
14550
14551   if (addTest) {
14552     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14553     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14554     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14555   }
14556   Cond = ConvertCmpIfNecessary(Cond, DAG);
14557   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14558                      Chain, Dest, CC, Cond);
14559 }
14560
14561 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14562 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14563 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14564 // that the guard pages used by the OS virtual memory manager are allocated in
14565 // correct sequence.
14566 SDValue
14567 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14568                                            SelectionDAG &DAG) const {
14569   MachineFunction &MF = DAG.getMachineFunction();
14570   bool SplitStack = MF.shouldSplitStack();
14571   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14572                SplitStack;
14573   SDLoc dl(Op);
14574
14575   if (!Lower) {
14576     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14577     SDNode* Node = Op.getNode();
14578
14579     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14580     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14581         " not tell us which reg is the stack pointer!");
14582     EVT VT = Node->getValueType(0);
14583     SDValue Tmp1 = SDValue(Node, 0);
14584     SDValue Tmp2 = SDValue(Node, 1);
14585     SDValue Tmp3 = Node->getOperand(2);
14586     SDValue Chain = Tmp1.getOperand(0);
14587
14588     // Chain the dynamic stack allocation so that it doesn't modify the stack
14589     // pointer when other instructions are using the stack.
14590     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14591         SDLoc(Node));
14592
14593     SDValue Size = Tmp2.getOperand(1);
14594     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14595     Chain = SP.getValue(1);
14596     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14597     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14598     unsigned StackAlign = TFI.getStackAlignment();
14599     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14600     if (Align > StackAlign)
14601       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14602           DAG.getConstant(-(uint64_t)Align, dl, VT));
14603     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14604
14605     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14606         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14607         SDLoc(Node));
14608
14609     SDValue Ops[2] = { Tmp1, Tmp2 };
14610     return DAG.getMergeValues(Ops, dl);
14611   }
14612
14613   // Get the inputs.
14614   SDValue Chain = Op.getOperand(0);
14615   SDValue Size  = Op.getOperand(1);
14616   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14617   EVT VT = Op.getNode()->getValueType(0);
14618
14619   bool Is64Bit = Subtarget->is64Bit();
14620   EVT SPTy = getPointerTy();
14621
14622   if (SplitStack) {
14623     MachineRegisterInfo &MRI = MF.getRegInfo();
14624
14625     if (Is64Bit) {
14626       // The 64 bit implementation of segmented stacks needs to clobber both r10
14627       // r11. This makes it impossible to use it along with nested parameters.
14628       const Function *F = MF.getFunction();
14629
14630       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14631            I != E; ++I)
14632         if (I->hasNestAttr())
14633           report_fatal_error("Cannot use segmented stacks with functions that "
14634                              "have nested arguments.");
14635     }
14636
14637     const TargetRegisterClass *AddrRegClass =
14638       getRegClassFor(getPointerTy());
14639     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14640     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14641     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14642                                 DAG.getRegister(Vreg, SPTy));
14643     SDValue Ops1[2] = { Value, Chain };
14644     return DAG.getMergeValues(Ops1, dl);
14645   } else {
14646     SDValue Flag;
14647     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14648
14649     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14650     Flag = Chain.getValue(1);
14651     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14652
14653     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14654
14655     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14656     unsigned SPReg = RegInfo->getStackRegister();
14657     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14658     Chain = SP.getValue(1);
14659
14660     if (Align) {
14661       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14662                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14663       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14664     }
14665
14666     SDValue Ops1[2] = { SP, Chain };
14667     return DAG.getMergeValues(Ops1, dl);
14668   }
14669 }
14670
14671 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14672   MachineFunction &MF = DAG.getMachineFunction();
14673   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14674
14675   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14676   SDLoc DL(Op);
14677
14678   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14679     // vastart just stores the address of the VarArgsFrameIndex slot into the
14680     // memory location argument.
14681     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14682                                    getPointerTy());
14683     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14684                         MachinePointerInfo(SV), false, false, 0);
14685   }
14686
14687   // __va_list_tag:
14688   //   gp_offset         (0 - 6 * 8)
14689   //   fp_offset         (48 - 48 + 8 * 16)
14690   //   overflow_arg_area (point to parameters coming in memory).
14691   //   reg_save_area
14692   SmallVector<SDValue, 8> MemOps;
14693   SDValue FIN = Op.getOperand(1);
14694   // Store gp_offset
14695   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14696                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14697                                                DL, MVT::i32),
14698                                FIN, MachinePointerInfo(SV), false, false, 0);
14699   MemOps.push_back(Store);
14700
14701   // Store fp_offset
14702   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14703                     FIN, DAG.getIntPtrConstant(4, DL));
14704   Store = DAG.getStore(Op.getOperand(0), DL,
14705                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14706                                        MVT::i32),
14707                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14708   MemOps.push_back(Store);
14709
14710   // Store ptr to overflow_arg_area
14711   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14712                     FIN, DAG.getIntPtrConstant(4, DL));
14713   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14714                                     getPointerTy());
14715   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14716                        MachinePointerInfo(SV, 8),
14717                        false, false, 0);
14718   MemOps.push_back(Store);
14719
14720   // Store ptr to reg_save_area.
14721   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14722                     FIN, DAG.getIntPtrConstant(8, DL));
14723   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14724                                     getPointerTy());
14725   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14726                        MachinePointerInfo(SV, 16), false, false, 0);
14727   MemOps.push_back(Store);
14728   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14729 }
14730
14731 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14732   assert(Subtarget->is64Bit() &&
14733          "LowerVAARG only handles 64-bit va_arg!");
14734   assert((Subtarget->isTargetLinux() ||
14735           Subtarget->isTargetDarwin()) &&
14736           "Unhandled target in LowerVAARG");
14737   assert(Op.getNode()->getNumOperands() == 4);
14738   SDValue Chain = Op.getOperand(0);
14739   SDValue SrcPtr = Op.getOperand(1);
14740   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14741   unsigned Align = Op.getConstantOperandVal(3);
14742   SDLoc dl(Op);
14743
14744   EVT ArgVT = Op.getNode()->getValueType(0);
14745   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14746   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14747   uint8_t ArgMode;
14748
14749   // Decide which area this value should be read from.
14750   // TODO: Implement the AMD64 ABI in its entirety. This simple
14751   // selection mechanism works only for the basic types.
14752   if (ArgVT == MVT::f80) {
14753     llvm_unreachable("va_arg for f80 not yet implemented");
14754   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14755     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14756   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14757     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14758   } else {
14759     llvm_unreachable("Unhandled argument type in LowerVAARG");
14760   }
14761
14762   if (ArgMode == 2) {
14763     // Sanity Check: Make sure using fp_offset makes sense.
14764     assert(!Subtarget->useSoftFloat() &&
14765            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14766                Attribute::NoImplicitFloat)) &&
14767            Subtarget->hasSSE1());
14768   }
14769
14770   // Insert VAARG_64 node into the DAG
14771   // VAARG_64 returns two values: Variable Argument Address, Chain
14772   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14773                        DAG.getConstant(ArgMode, dl, MVT::i8),
14774                        DAG.getConstant(Align, dl, MVT::i32)};
14775   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14776   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14777                                           VTs, InstOps, MVT::i64,
14778                                           MachinePointerInfo(SV),
14779                                           /*Align=*/0,
14780                                           /*Volatile=*/false,
14781                                           /*ReadMem=*/true,
14782                                           /*WriteMem=*/true);
14783   Chain = VAARG.getValue(1);
14784
14785   // Load the next argument and return it
14786   return DAG.getLoad(ArgVT, dl,
14787                      Chain,
14788                      VAARG,
14789                      MachinePointerInfo(),
14790                      false, false, false, 0);
14791 }
14792
14793 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14794                            SelectionDAG &DAG) {
14795   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14796   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14797   SDValue Chain = Op.getOperand(0);
14798   SDValue DstPtr = Op.getOperand(1);
14799   SDValue SrcPtr = Op.getOperand(2);
14800   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14801   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14802   SDLoc DL(Op);
14803
14804   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14805                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14806                        false, false,
14807                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14808 }
14809
14810 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14811 // amount is a constant. Takes immediate version of shift as input.
14812 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14813                                           SDValue SrcOp, uint64_t ShiftAmt,
14814                                           SelectionDAG &DAG) {
14815   MVT ElementType = VT.getVectorElementType();
14816
14817   // Fold this packed shift into its first operand if ShiftAmt is 0.
14818   if (ShiftAmt == 0)
14819     return SrcOp;
14820
14821   // Check for ShiftAmt >= element width
14822   if (ShiftAmt >= ElementType.getSizeInBits()) {
14823     if (Opc == X86ISD::VSRAI)
14824       ShiftAmt = ElementType.getSizeInBits() - 1;
14825     else
14826       return DAG.getConstant(0, dl, VT);
14827   }
14828
14829   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14830          && "Unknown target vector shift-by-constant node");
14831
14832   // Fold this packed vector shift into a build vector if SrcOp is a
14833   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14834   if (VT == SrcOp.getSimpleValueType() &&
14835       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14836     SmallVector<SDValue, 8> Elts;
14837     unsigned NumElts = SrcOp->getNumOperands();
14838     ConstantSDNode *ND;
14839
14840     switch(Opc) {
14841     default: llvm_unreachable(nullptr);
14842     case X86ISD::VSHLI:
14843       for (unsigned i=0; i!=NumElts; ++i) {
14844         SDValue CurrentOp = SrcOp->getOperand(i);
14845         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14846           Elts.push_back(CurrentOp);
14847           continue;
14848         }
14849         ND = cast<ConstantSDNode>(CurrentOp);
14850         const APInt &C = ND->getAPIntValue();
14851         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14852       }
14853       break;
14854     case X86ISD::VSRLI:
14855       for (unsigned i=0; i!=NumElts; ++i) {
14856         SDValue CurrentOp = SrcOp->getOperand(i);
14857         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14858           Elts.push_back(CurrentOp);
14859           continue;
14860         }
14861         ND = cast<ConstantSDNode>(CurrentOp);
14862         const APInt &C = ND->getAPIntValue();
14863         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14864       }
14865       break;
14866     case X86ISD::VSRAI:
14867       for (unsigned i=0; i!=NumElts; ++i) {
14868         SDValue CurrentOp = SrcOp->getOperand(i);
14869         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14870           Elts.push_back(CurrentOp);
14871           continue;
14872         }
14873         ND = cast<ConstantSDNode>(CurrentOp);
14874         const APInt &C = ND->getAPIntValue();
14875         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14876       }
14877       break;
14878     }
14879
14880     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14881   }
14882
14883   return DAG.getNode(Opc, dl, VT, SrcOp,
14884                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14885 }
14886
14887 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14888 // may or may not be a constant. Takes immediate version of shift as input.
14889 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14890                                    SDValue SrcOp, SDValue ShAmt,
14891                                    SelectionDAG &DAG) {
14892   MVT SVT = ShAmt.getSimpleValueType();
14893   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14894
14895   // Catch shift-by-constant.
14896   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14897     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14898                                       CShAmt->getZExtValue(), DAG);
14899
14900   // Change opcode to non-immediate version
14901   switch (Opc) {
14902     default: llvm_unreachable("Unknown target vector shift node");
14903     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14904     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14905     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14906   }
14907
14908   const X86Subtarget &Subtarget =
14909       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14910   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14911       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14912     // Let the shuffle legalizer expand this shift amount node.
14913     SDValue Op0 = ShAmt.getOperand(0);
14914     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14915     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14916   } else {
14917     // Need to build a vector containing shift amount.
14918     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14919     SmallVector<SDValue, 4> ShOps;
14920     ShOps.push_back(ShAmt);
14921     if (SVT == MVT::i32) {
14922       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14923       ShOps.push_back(DAG.getUNDEF(SVT));
14924     }
14925     ShOps.push_back(DAG.getUNDEF(SVT));
14926
14927     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14928     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14929   }
14930
14931   // The return type has to be a 128-bit type with the same element
14932   // type as the input type.
14933   MVT EltVT = VT.getVectorElementType();
14934   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14935
14936   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14937   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14938 }
14939
14940 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14941 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14942 /// necessary casting for \p Mask when lowering masking intrinsics.
14943 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14944                                     SDValue PreservedSrc,
14945                                     const X86Subtarget *Subtarget,
14946                                     SelectionDAG &DAG) {
14947     EVT VT = Op.getValueType();
14948     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14949                                   MVT::i1, VT.getVectorNumElements());
14950     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14951                                      Mask.getValueType().getSizeInBits());
14952     SDLoc dl(Op);
14953
14954     assert(MaskVT.isSimple() && "invalid mask type");
14955
14956     if (isAllOnes(Mask))
14957       return Op;
14958
14959     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14960     // are extracted by EXTRACT_SUBVECTOR.
14961     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14962                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14963                               DAG.getIntPtrConstant(0, dl));
14964
14965     switch (Op.getOpcode()) {
14966       default: break;
14967       case X86ISD::PCMPEQM:
14968       case X86ISD::PCMPGTM:
14969       case X86ISD::CMPM:
14970       case X86ISD::CMPMU:
14971         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14972     }
14973     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14974       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14975     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14976 }
14977
14978 /// \brief Creates an SDNode for a predicated scalar operation.
14979 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14980 /// The mask is comming as MVT::i8 and it should be truncated
14981 /// to MVT::i1 while lowering masking intrinsics.
14982 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14983 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14984 /// a scalar instruction.
14985 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14986                                     SDValue PreservedSrc,
14987                                     const X86Subtarget *Subtarget,
14988                                     SelectionDAG &DAG) {
14989     if (isAllOnes(Mask))
14990       return Op;
14991
14992     EVT VT = Op.getValueType();
14993     SDLoc dl(Op);
14994     // The mask should be of type MVT::i1
14995     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14996
14997     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14998       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14999     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15000 }
15001
15002 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15003                                        SelectionDAG &DAG) {
15004   SDLoc dl(Op);
15005   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15006   EVT VT = Op.getValueType();
15007   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15008   if (IntrData) {
15009     switch(IntrData->Type) {
15010     case INTR_TYPE_1OP:
15011       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15012     case INTR_TYPE_2OP:
15013       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15014         Op.getOperand(2));
15015     case INTR_TYPE_3OP:
15016       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15017         Op.getOperand(2), Op.getOperand(3));
15018     case INTR_TYPE_1OP_MASK_RM: {
15019       SDValue Src = Op.getOperand(1);
15020       SDValue Src0 = Op.getOperand(2);
15021       SDValue Mask = Op.getOperand(3);
15022       SDValue RoundingMode = Op.getOperand(4);
15023       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15024                                               RoundingMode),
15025                                   Mask, Src0, Subtarget, DAG);
15026     }
15027     case INTR_TYPE_SCALAR_MASK_RM: {
15028       SDValue Src1 = Op.getOperand(1);
15029       SDValue Src2 = Op.getOperand(2);
15030       SDValue Src0 = Op.getOperand(3);
15031       SDValue Mask = Op.getOperand(4);
15032       // There are 2 kinds of intrinsics in this group:
15033       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15034       // (2) With rounding mode and sae - 7 operands.
15035       if (Op.getNumOperands() == 6) {
15036         SDValue Sae  = Op.getOperand(5);
15037         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15038         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15039                                                 Sae),
15040                                     Mask, Src0, Subtarget, DAG);
15041       }
15042       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15043       SDValue RoundingMode  = Op.getOperand(5);
15044       SDValue Sae  = Op.getOperand(6);
15045       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15046                                               RoundingMode, Sae),
15047                                   Mask, Src0, Subtarget, DAG);
15048     }
15049     case INTR_TYPE_2OP_MASK: {
15050       SDValue Src1 = Op.getOperand(1);
15051       SDValue Src2 = Op.getOperand(2);
15052       SDValue PassThru = Op.getOperand(3);
15053       SDValue Mask = Op.getOperand(4);
15054       // We specify 2 possible opcodes for intrinsics with rounding modes.
15055       // First, we check if the intrinsic may have non-default rounding mode,
15056       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15057       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15058       if (IntrWithRoundingModeOpcode != 0) {
15059         SDValue Rnd = Op.getOperand(5);
15060         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15061         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15062           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15063                                       dl, Op.getValueType(),
15064                                       Src1, Src2, Rnd),
15065                                       Mask, PassThru, Subtarget, DAG);
15066         }
15067       }
15068       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15069                                               Src1,Src2),
15070                                   Mask, PassThru, Subtarget, DAG);
15071     }
15072     case FMA_OP_MASK: {
15073       SDValue Src1 = Op.getOperand(1);
15074       SDValue Src2 = Op.getOperand(2);
15075       SDValue Src3 = Op.getOperand(3);
15076       SDValue Mask = Op.getOperand(4);
15077       // We specify 2 possible opcodes for intrinsics with rounding modes.
15078       // First, we check if the intrinsic may have non-default rounding mode,
15079       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15080       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15081       if (IntrWithRoundingModeOpcode != 0) {
15082         SDValue Rnd = Op.getOperand(5);
15083         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15084             X86::STATIC_ROUNDING::CUR_DIRECTION)
15085           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15086                                                   dl, Op.getValueType(),
15087                                                   Src1, Src2, Src3, Rnd),
15088                                       Mask, Src1, Subtarget, DAG);
15089       }
15090       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15091                                               dl, Op.getValueType(),
15092                                               Src1, Src2, Src3),
15093                                   Mask, Src1, Subtarget, DAG);
15094     }
15095     case CMP_MASK:
15096     case CMP_MASK_CC: {
15097       // Comparison intrinsics with masks.
15098       // Example of transformation:
15099       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15100       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15101       // (i8 (bitcast
15102       //   (v8i1 (insert_subvector undef,
15103       //           (v2i1 (and (PCMPEQM %a, %b),
15104       //                      (extract_subvector
15105       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15106       EVT VT = Op.getOperand(1).getValueType();
15107       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15108                                     VT.getVectorNumElements());
15109       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15110       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15111                                        Mask.getValueType().getSizeInBits());
15112       SDValue Cmp;
15113       if (IntrData->Type == CMP_MASK_CC) {
15114         SDValue CC = Op.getOperand(3);
15115         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15116         // We specify 2 possible opcodes for intrinsics with rounding modes.
15117         // First, we check if the intrinsic may have non-default rounding mode,
15118         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15119         if (IntrData->Opc1 != 0) {
15120           SDValue Rnd = Op.getOperand(5);
15121           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15122               X86::STATIC_ROUNDING::CUR_DIRECTION)
15123             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15124                               Op.getOperand(2), CC, Rnd);
15125         }
15126         //default rounding mode
15127         if(!Cmp.getNode())
15128             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15129                               Op.getOperand(2), CC);
15130
15131       } else {
15132         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15133         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15134                           Op.getOperand(2));
15135       }
15136       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15137                                              DAG.getTargetConstant(0, dl,
15138                                                                    MaskVT),
15139                                              Subtarget, DAG);
15140       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15141                                 DAG.getUNDEF(BitcastVT), CmpMask,
15142                                 DAG.getIntPtrConstant(0, dl));
15143       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
15144     }
15145     case COMI: { // Comparison intrinsics
15146       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15147       SDValue LHS = Op.getOperand(1);
15148       SDValue RHS = Op.getOperand(2);
15149       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15150       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15151       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15152       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15153                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15154       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15155     }
15156     case VSHIFT:
15157       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15158                                  Op.getOperand(1), Op.getOperand(2), DAG);
15159     case VSHIFT_MASK:
15160       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15161                                                       Op.getSimpleValueType(),
15162                                                       Op.getOperand(1),
15163                                                       Op.getOperand(2), DAG),
15164                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15165                                   DAG);
15166     case COMPRESS_EXPAND_IN_REG: {
15167       SDValue Mask = Op.getOperand(3);
15168       SDValue DataToCompress = Op.getOperand(1);
15169       SDValue PassThru = Op.getOperand(2);
15170       if (isAllOnes(Mask)) // return data as is
15171         return Op.getOperand(1);
15172       EVT VT = Op.getValueType();
15173       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15174                                     VT.getVectorNumElements());
15175       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15176                                        Mask.getValueType().getSizeInBits());
15177       SDLoc dl(Op);
15178       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15179                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15180                                   DAG.getIntPtrConstant(0, dl));
15181
15182       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15183                          PassThru);
15184     }
15185     case BLEND: {
15186       SDValue Mask = Op.getOperand(3);
15187       EVT VT = Op.getValueType();
15188       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15189                                     VT.getVectorNumElements());
15190       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15191                                        Mask.getValueType().getSizeInBits());
15192       SDLoc dl(Op);
15193       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15194                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15195                                   DAG.getIntPtrConstant(0, dl));
15196       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15197                          Op.getOperand(2));
15198     }
15199     default:
15200       break;
15201     }
15202   }
15203
15204   switch (IntNo) {
15205   default: return SDValue();    // Don't custom lower most intrinsics.
15206
15207   case Intrinsic::x86_avx2_permd:
15208   case Intrinsic::x86_avx2_permps:
15209     // Operands intentionally swapped. Mask is last operand to intrinsic,
15210     // but second operand for node/instruction.
15211     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15212                        Op.getOperand(2), Op.getOperand(1));
15213
15214   case Intrinsic::x86_avx512_mask_valign_q_512:
15215   case Intrinsic::x86_avx512_mask_valign_d_512:
15216     // Vector source operands are swapped.
15217     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15218                                             Op.getValueType(), Op.getOperand(2),
15219                                             Op.getOperand(1),
15220                                             Op.getOperand(3)),
15221                                 Op.getOperand(5), Op.getOperand(4),
15222                                 Subtarget, DAG);
15223
15224   // ptest and testp intrinsics. The intrinsic these come from are designed to
15225   // return an integer value, not just an instruction so lower it to the ptest
15226   // or testp pattern and a setcc for the result.
15227   case Intrinsic::x86_sse41_ptestz:
15228   case Intrinsic::x86_sse41_ptestc:
15229   case Intrinsic::x86_sse41_ptestnzc:
15230   case Intrinsic::x86_avx_ptestz_256:
15231   case Intrinsic::x86_avx_ptestc_256:
15232   case Intrinsic::x86_avx_ptestnzc_256:
15233   case Intrinsic::x86_avx_vtestz_ps:
15234   case Intrinsic::x86_avx_vtestc_ps:
15235   case Intrinsic::x86_avx_vtestnzc_ps:
15236   case Intrinsic::x86_avx_vtestz_pd:
15237   case Intrinsic::x86_avx_vtestc_pd:
15238   case Intrinsic::x86_avx_vtestnzc_pd:
15239   case Intrinsic::x86_avx_vtestz_ps_256:
15240   case Intrinsic::x86_avx_vtestc_ps_256:
15241   case Intrinsic::x86_avx_vtestnzc_ps_256:
15242   case Intrinsic::x86_avx_vtestz_pd_256:
15243   case Intrinsic::x86_avx_vtestc_pd_256:
15244   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15245     bool IsTestPacked = false;
15246     unsigned X86CC;
15247     switch (IntNo) {
15248     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15249     case Intrinsic::x86_avx_vtestz_ps:
15250     case Intrinsic::x86_avx_vtestz_pd:
15251     case Intrinsic::x86_avx_vtestz_ps_256:
15252     case Intrinsic::x86_avx_vtestz_pd_256:
15253       IsTestPacked = true; // Fallthrough
15254     case Intrinsic::x86_sse41_ptestz:
15255     case Intrinsic::x86_avx_ptestz_256:
15256       // ZF = 1
15257       X86CC = X86::COND_E;
15258       break;
15259     case Intrinsic::x86_avx_vtestc_ps:
15260     case Intrinsic::x86_avx_vtestc_pd:
15261     case Intrinsic::x86_avx_vtestc_ps_256:
15262     case Intrinsic::x86_avx_vtestc_pd_256:
15263       IsTestPacked = true; // Fallthrough
15264     case Intrinsic::x86_sse41_ptestc:
15265     case Intrinsic::x86_avx_ptestc_256:
15266       // CF = 1
15267       X86CC = X86::COND_B;
15268       break;
15269     case Intrinsic::x86_avx_vtestnzc_ps:
15270     case Intrinsic::x86_avx_vtestnzc_pd:
15271     case Intrinsic::x86_avx_vtestnzc_ps_256:
15272     case Intrinsic::x86_avx_vtestnzc_pd_256:
15273       IsTestPacked = true; // Fallthrough
15274     case Intrinsic::x86_sse41_ptestnzc:
15275     case Intrinsic::x86_avx_ptestnzc_256:
15276       // ZF and CF = 0
15277       X86CC = X86::COND_A;
15278       break;
15279     }
15280
15281     SDValue LHS = Op.getOperand(1);
15282     SDValue RHS = Op.getOperand(2);
15283     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15284     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15285     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15286     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15287     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15288   }
15289   case Intrinsic::x86_avx512_kortestz_w:
15290   case Intrinsic::x86_avx512_kortestc_w: {
15291     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15292     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15293     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15294     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15295     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15296     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15297     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15298   }
15299
15300   case Intrinsic::x86_sse42_pcmpistria128:
15301   case Intrinsic::x86_sse42_pcmpestria128:
15302   case Intrinsic::x86_sse42_pcmpistric128:
15303   case Intrinsic::x86_sse42_pcmpestric128:
15304   case Intrinsic::x86_sse42_pcmpistrio128:
15305   case Intrinsic::x86_sse42_pcmpestrio128:
15306   case Intrinsic::x86_sse42_pcmpistris128:
15307   case Intrinsic::x86_sse42_pcmpestris128:
15308   case Intrinsic::x86_sse42_pcmpistriz128:
15309   case Intrinsic::x86_sse42_pcmpestriz128: {
15310     unsigned Opcode;
15311     unsigned X86CC;
15312     switch (IntNo) {
15313     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15314     case Intrinsic::x86_sse42_pcmpistria128:
15315       Opcode = X86ISD::PCMPISTRI;
15316       X86CC = X86::COND_A;
15317       break;
15318     case Intrinsic::x86_sse42_pcmpestria128:
15319       Opcode = X86ISD::PCMPESTRI;
15320       X86CC = X86::COND_A;
15321       break;
15322     case Intrinsic::x86_sse42_pcmpistric128:
15323       Opcode = X86ISD::PCMPISTRI;
15324       X86CC = X86::COND_B;
15325       break;
15326     case Intrinsic::x86_sse42_pcmpestric128:
15327       Opcode = X86ISD::PCMPESTRI;
15328       X86CC = X86::COND_B;
15329       break;
15330     case Intrinsic::x86_sse42_pcmpistrio128:
15331       Opcode = X86ISD::PCMPISTRI;
15332       X86CC = X86::COND_O;
15333       break;
15334     case Intrinsic::x86_sse42_pcmpestrio128:
15335       Opcode = X86ISD::PCMPESTRI;
15336       X86CC = X86::COND_O;
15337       break;
15338     case Intrinsic::x86_sse42_pcmpistris128:
15339       Opcode = X86ISD::PCMPISTRI;
15340       X86CC = X86::COND_S;
15341       break;
15342     case Intrinsic::x86_sse42_pcmpestris128:
15343       Opcode = X86ISD::PCMPESTRI;
15344       X86CC = X86::COND_S;
15345       break;
15346     case Intrinsic::x86_sse42_pcmpistriz128:
15347       Opcode = X86ISD::PCMPISTRI;
15348       X86CC = X86::COND_E;
15349       break;
15350     case Intrinsic::x86_sse42_pcmpestriz128:
15351       Opcode = X86ISD::PCMPESTRI;
15352       X86CC = X86::COND_E;
15353       break;
15354     }
15355     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15356     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15357     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15358     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15359                                 DAG.getConstant(X86CC, dl, MVT::i8),
15360                                 SDValue(PCMP.getNode(), 1));
15361     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15362   }
15363
15364   case Intrinsic::x86_sse42_pcmpistri128:
15365   case Intrinsic::x86_sse42_pcmpestri128: {
15366     unsigned Opcode;
15367     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15368       Opcode = X86ISD::PCMPISTRI;
15369     else
15370       Opcode = X86ISD::PCMPESTRI;
15371
15372     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15373     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15374     return DAG.getNode(Opcode, dl, VTs, NewOps);
15375   }
15376
15377   case Intrinsic::x86_seh_lsda: {
15378     // Compute the symbol for the LSDA. We know it'll get emitted later.
15379     MachineFunction &MF = DAG.getMachineFunction();
15380     SDValue Op1 = Op.getOperand(1);
15381     Op1->dump();
15382     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15383     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15384         GlobalValue::getRealLinkageName(Fn->getName()));
15385     StringRef Name = LSDASym->getName();
15386     assert(Name.data()[Name.size()] == '\0' && "not null terminated");
15387
15388     // Generate a simple absolute symbol reference. This intrinsic is only
15389     // supported on 32-bit Windows, which isn't PIC.
15390     SDValue Result =
15391         DAG.getTargetExternalSymbol(Name.data(), VT, X86II::MO_NOPREFIX);
15392     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15393   }
15394   }
15395 }
15396
15397 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15398                               SDValue Src, SDValue Mask, SDValue Base,
15399                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15400                               const X86Subtarget * Subtarget) {
15401   SDLoc dl(Op);
15402   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15403   assert(C && "Invalid scale type");
15404   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15405   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15406                              Index.getSimpleValueType().getVectorNumElements());
15407   SDValue MaskInReg;
15408   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15409   if (MaskC)
15410     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15411   else
15412     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15413   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15414   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15415   SDValue Segment = DAG.getRegister(0, MVT::i32);
15416   if (Src.getOpcode() == ISD::UNDEF)
15417     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15418   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15419   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15420   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15421   return DAG.getMergeValues(RetOps, dl);
15422 }
15423
15424 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15425                                SDValue Src, SDValue Mask, SDValue Base,
15426                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15427   SDLoc dl(Op);
15428   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15429   assert(C && "Invalid scale type");
15430   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15431   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15432   SDValue Segment = DAG.getRegister(0, MVT::i32);
15433   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15434                              Index.getSimpleValueType().getVectorNumElements());
15435   SDValue MaskInReg;
15436   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15437   if (MaskC)
15438     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15439   else
15440     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15441   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15442   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15443   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15444   return SDValue(Res, 1);
15445 }
15446
15447 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15448                                SDValue Mask, SDValue Base, SDValue Index,
15449                                SDValue ScaleOp, SDValue Chain) {
15450   SDLoc dl(Op);
15451   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15452   assert(C && "Invalid scale type");
15453   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15454   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15455   SDValue Segment = DAG.getRegister(0, MVT::i32);
15456   EVT MaskVT =
15457     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15458   SDValue MaskInReg;
15459   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15460   if (MaskC)
15461     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15462   else
15463     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15464   //SDVTList VTs = DAG.getVTList(MVT::Other);
15465   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15466   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15467   return SDValue(Res, 0);
15468 }
15469
15470 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15471 // read performance monitor counters (x86_rdpmc).
15472 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15473                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15474                               SmallVectorImpl<SDValue> &Results) {
15475   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15476   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15477   SDValue LO, HI;
15478
15479   // The ECX register is used to select the index of the performance counter
15480   // to read.
15481   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15482                                    N->getOperand(2));
15483   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15484
15485   // Reads the content of a 64-bit performance counter and returns it in the
15486   // registers EDX:EAX.
15487   if (Subtarget->is64Bit()) {
15488     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15489     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15490                             LO.getValue(2));
15491   } else {
15492     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15493     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15494                             LO.getValue(2));
15495   }
15496   Chain = HI.getValue(1);
15497
15498   if (Subtarget->is64Bit()) {
15499     // The EAX register is loaded with the low-order 32 bits. The EDX register
15500     // is loaded with the supported high-order bits of the counter.
15501     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15502                               DAG.getConstant(32, DL, MVT::i8));
15503     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15504     Results.push_back(Chain);
15505     return;
15506   }
15507
15508   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15509   SDValue Ops[] = { LO, HI };
15510   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15511   Results.push_back(Pair);
15512   Results.push_back(Chain);
15513 }
15514
15515 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15516 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15517 // also used to custom lower READCYCLECOUNTER nodes.
15518 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15519                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15520                               SmallVectorImpl<SDValue> &Results) {
15521   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15522   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15523   SDValue LO, HI;
15524
15525   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15526   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15527   // and the EAX register is loaded with the low-order 32 bits.
15528   if (Subtarget->is64Bit()) {
15529     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15530     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15531                             LO.getValue(2));
15532   } else {
15533     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15534     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15535                             LO.getValue(2));
15536   }
15537   SDValue Chain = HI.getValue(1);
15538
15539   if (Opcode == X86ISD::RDTSCP_DAG) {
15540     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15541
15542     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15543     // the ECX register. Add 'ecx' explicitly to the chain.
15544     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15545                                      HI.getValue(2));
15546     // Explicitly store the content of ECX at the location passed in input
15547     // to the 'rdtscp' intrinsic.
15548     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15549                          MachinePointerInfo(), false, false, 0);
15550   }
15551
15552   if (Subtarget->is64Bit()) {
15553     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15554     // the EAX register is loaded with the low-order 32 bits.
15555     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15556                               DAG.getConstant(32, DL, MVT::i8));
15557     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15558     Results.push_back(Chain);
15559     return;
15560   }
15561
15562   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15563   SDValue Ops[] = { LO, HI };
15564   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15565   Results.push_back(Pair);
15566   Results.push_back(Chain);
15567 }
15568
15569 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15570                                      SelectionDAG &DAG) {
15571   SmallVector<SDValue, 2> Results;
15572   SDLoc DL(Op);
15573   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15574                           Results);
15575   return DAG.getMergeValues(Results, DL);
15576 }
15577
15578
15579 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15580                                       SelectionDAG &DAG) {
15581   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15582
15583   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15584   if (!IntrData)
15585     return SDValue();
15586
15587   SDLoc dl(Op);
15588   switch(IntrData->Type) {
15589   default:
15590     llvm_unreachable("Unknown Intrinsic Type");
15591     break;
15592   case RDSEED:
15593   case RDRAND: {
15594     // Emit the node with the right value type.
15595     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15596     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15597
15598     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15599     // Otherwise return the value from Rand, which is always 0, casted to i32.
15600     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15601                       DAG.getConstant(1, dl, Op->getValueType(1)),
15602                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15603                       SDValue(Result.getNode(), 1) };
15604     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15605                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15606                                   Ops);
15607
15608     // Return { result, isValid, chain }.
15609     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15610                        SDValue(Result.getNode(), 2));
15611   }
15612   case GATHER: {
15613   //gather(v1, mask, index, base, scale);
15614     SDValue Chain = Op.getOperand(0);
15615     SDValue Src   = Op.getOperand(2);
15616     SDValue Base  = Op.getOperand(3);
15617     SDValue Index = Op.getOperand(4);
15618     SDValue Mask  = Op.getOperand(5);
15619     SDValue Scale = Op.getOperand(6);
15620     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15621                          Chain, Subtarget);
15622   }
15623   case SCATTER: {
15624   //scatter(base, mask, index, v1, scale);
15625     SDValue Chain = Op.getOperand(0);
15626     SDValue Base  = Op.getOperand(2);
15627     SDValue Mask  = Op.getOperand(3);
15628     SDValue Index = Op.getOperand(4);
15629     SDValue Src   = Op.getOperand(5);
15630     SDValue Scale = Op.getOperand(6);
15631     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15632                           Scale, Chain);
15633   }
15634   case PREFETCH: {
15635     SDValue Hint = Op.getOperand(6);
15636     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15637     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15638     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15639     SDValue Chain = Op.getOperand(0);
15640     SDValue Mask  = Op.getOperand(2);
15641     SDValue Index = Op.getOperand(3);
15642     SDValue Base  = Op.getOperand(4);
15643     SDValue Scale = Op.getOperand(5);
15644     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15645   }
15646   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15647   case RDTSC: {
15648     SmallVector<SDValue, 2> Results;
15649     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15650                             Results);
15651     return DAG.getMergeValues(Results, dl);
15652   }
15653   // Read Performance Monitoring Counters.
15654   case RDPMC: {
15655     SmallVector<SDValue, 2> Results;
15656     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15657     return DAG.getMergeValues(Results, dl);
15658   }
15659   // XTEST intrinsics.
15660   case XTEST: {
15661     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15662     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15663     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15664                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15665                                 InTrans);
15666     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15667     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15668                        Ret, SDValue(InTrans.getNode(), 1));
15669   }
15670   // ADC/ADCX/SBB
15671   case ADX: {
15672     SmallVector<SDValue, 2> Results;
15673     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15674     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15675     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15676                                 DAG.getConstant(-1, dl, MVT::i8));
15677     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15678                               Op.getOperand(4), GenCF.getValue(1));
15679     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15680                                  Op.getOperand(5), MachinePointerInfo(),
15681                                  false, false, 0);
15682     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15683                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15684                                 Res.getValue(1));
15685     Results.push_back(SetCC);
15686     Results.push_back(Store);
15687     return DAG.getMergeValues(Results, dl);
15688   }
15689   case COMPRESS_TO_MEM: {
15690     SDLoc dl(Op);
15691     SDValue Mask = Op.getOperand(4);
15692     SDValue DataToCompress = Op.getOperand(3);
15693     SDValue Addr = Op.getOperand(2);
15694     SDValue Chain = Op.getOperand(0);
15695
15696     if (isAllOnes(Mask)) // return just a store
15697       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15698                           MachinePointerInfo(), false, false, 0);
15699
15700     EVT VT = DataToCompress.getValueType();
15701     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15702                                   VT.getVectorNumElements());
15703     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15704                                      Mask.getValueType().getSizeInBits());
15705     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15706                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15707                                 DAG.getIntPtrConstant(0, dl));
15708
15709     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15710                                       DataToCompress, DAG.getUNDEF(VT));
15711     return DAG.getStore(Chain, dl, Compressed, Addr,
15712                         MachinePointerInfo(), false, false, 0);
15713   }
15714   case EXPAND_FROM_MEM: {
15715     SDLoc dl(Op);
15716     SDValue Mask = Op.getOperand(4);
15717     SDValue PathThru = Op.getOperand(3);
15718     SDValue Addr = Op.getOperand(2);
15719     SDValue Chain = Op.getOperand(0);
15720     EVT VT = Op.getValueType();
15721
15722     if (isAllOnes(Mask)) // return just a load
15723       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15724                          false, 0);
15725     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15726                                   VT.getVectorNumElements());
15727     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15728                                      Mask.getValueType().getSizeInBits());
15729     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15730                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15731                                 DAG.getIntPtrConstant(0, dl));
15732
15733     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15734                                    false, false, false, 0);
15735
15736     SDValue Results[] = {
15737         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15738         Chain};
15739     return DAG.getMergeValues(Results, dl);
15740   }
15741   }
15742 }
15743
15744 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15745                                            SelectionDAG &DAG) const {
15746   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15747   MFI->setReturnAddressIsTaken(true);
15748
15749   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15750     return SDValue();
15751
15752   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15753   SDLoc dl(Op);
15754   EVT PtrVT = getPointerTy();
15755
15756   if (Depth > 0) {
15757     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15758     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15759     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15760     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15761                        DAG.getNode(ISD::ADD, dl, PtrVT,
15762                                    FrameAddr, Offset),
15763                        MachinePointerInfo(), false, false, false, 0);
15764   }
15765
15766   // Just load the return address.
15767   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15768   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15769                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15770 }
15771
15772 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15773   MachineFunction &MF = DAG.getMachineFunction();
15774   MachineFrameInfo *MFI = MF.getFrameInfo();
15775   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15776   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15777   EVT VT = Op.getValueType();
15778
15779   MFI->setFrameAddressIsTaken(true);
15780
15781   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15782     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15783     // is not possible to crawl up the stack without looking at the unwind codes
15784     // simultaneously.
15785     int FrameAddrIndex = FuncInfo->getFAIndex();
15786     if (!FrameAddrIndex) {
15787       // Set up a frame object for the return address.
15788       unsigned SlotSize = RegInfo->getSlotSize();
15789       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15790           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
15791       FuncInfo->setFAIndex(FrameAddrIndex);
15792     }
15793     return DAG.getFrameIndex(FrameAddrIndex, VT);
15794   }
15795
15796   unsigned FrameReg =
15797       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15798   SDLoc dl(Op);  // FIXME probably not meaningful
15799   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15800   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15801           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15802          "Invalid Frame Register!");
15803   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15804   while (Depth--)
15805     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15806                             MachinePointerInfo(),
15807                             false, false, false, 0);
15808   return FrameAddr;
15809 }
15810
15811 // FIXME? Maybe this could be a TableGen attribute on some registers and
15812 // this table could be generated automatically from RegInfo.
15813 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15814                                               EVT VT) const {
15815   unsigned Reg = StringSwitch<unsigned>(RegName)
15816                        .Case("esp", X86::ESP)
15817                        .Case("rsp", X86::RSP)
15818                        .Default(0);
15819   if (Reg)
15820     return Reg;
15821   report_fatal_error("Invalid register name global variable");
15822 }
15823
15824 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15825                                                      SelectionDAG &DAG) const {
15826   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15827   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15828 }
15829
15830 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15831   SDValue Chain     = Op.getOperand(0);
15832   SDValue Offset    = Op.getOperand(1);
15833   SDValue Handler   = Op.getOperand(2);
15834   SDLoc dl      (Op);
15835
15836   EVT PtrVT = getPointerTy();
15837   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15838   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15839   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15840           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15841          "Invalid Frame Register!");
15842   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15843   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15844
15845   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15846                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15847                                                        dl));
15848   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15849   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15850                        false, false, 0);
15851   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15852
15853   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15854                      DAG.getRegister(StoreAddrReg, PtrVT));
15855 }
15856
15857 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15858                                                SelectionDAG &DAG) const {
15859   SDLoc DL(Op);
15860   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15861                      DAG.getVTList(MVT::i32, MVT::Other),
15862                      Op.getOperand(0), Op.getOperand(1));
15863 }
15864
15865 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15866                                                 SelectionDAG &DAG) const {
15867   SDLoc DL(Op);
15868   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15869                      Op.getOperand(0), Op.getOperand(1));
15870 }
15871
15872 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15873   return Op.getOperand(0);
15874 }
15875
15876 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15877                                                 SelectionDAG &DAG) const {
15878   SDValue Root = Op.getOperand(0);
15879   SDValue Trmp = Op.getOperand(1); // trampoline
15880   SDValue FPtr = Op.getOperand(2); // nested function
15881   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15882   SDLoc dl (Op);
15883
15884   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15885   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15886
15887   if (Subtarget->is64Bit()) {
15888     SDValue OutChains[6];
15889
15890     // Large code-model.
15891     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15892     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15893
15894     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15895     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15896
15897     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15898
15899     // Load the pointer to the nested function into R11.
15900     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15901     SDValue Addr = Trmp;
15902     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15903                                 Addr, MachinePointerInfo(TrmpAddr),
15904                                 false, false, 0);
15905
15906     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15907                        DAG.getConstant(2, dl, MVT::i64));
15908     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15909                                 MachinePointerInfo(TrmpAddr, 2),
15910                                 false, false, 2);
15911
15912     // Load the 'nest' parameter value into R10.
15913     // R10 is specified in X86CallingConv.td
15914     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15915     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15916                        DAG.getConstant(10, dl, MVT::i64));
15917     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15918                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15919                                 false, false, 0);
15920
15921     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15922                        DAG.getConstant(12, dl, MVT::i64));
15923     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15924                                 MachinePointerInfo(TrmpAddr, 12),
15925                                 false, false, 2);
15926
15927     // Jump to the nested function.
15928     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15929     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15930                        DAG.getConstant(20, dl, MVT::i64));
15931     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15932                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15933                                 false, false, 0);
15934
15935     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15936     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15937                        DAG.getConstant(22, dl, MVT::i64));
15938     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15939                                 Addr, MachinePointerInfo(TrmpAddr, 22),
15940                                 false, false, 0);
15941
15942     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15943   } else {
15944     const Function *Func =
15945       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15946     CallingConv::ID CC = Func->getCallingConv();
15947     unsigned NestReg;
15948
15949     switch (CC) {
15950     default:
15951       llvm_unreachable("Unsupported calling convention");
15952     case CallingConv::C:
15953     case CallingConv::X86_StdCall: {
15954       // Pass 'nest' parameter in ECX.
15955       // Must be kept in sync with X86CallingConv.td
15956       NestReg = X86::ECX;
15957
15958       // Check that ECX wasn't needed by an 'inreg' parameter.
15959       FunctionType *FTy = Func->getFunctionType();
15960       const AttributeSet &Attrs = Func->getAttributes();
15961
15962       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15963         unsigned InRegCount = 0;
15964         unsigned Idx = 1;
15965
15966         for (FunctionType::param_iterator I = FTy->param_begin(),
15967              E = FTy->param_end(); I != E; ++I, ++Idx)
15968           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15969             // FIXME: should only count parameters that are lowered to integers.
15970             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15971
15972         if (InRegCount > 2) {
15973           report_fatal_error("Nest register in use - reduce number of inreg"
15974                              " parameters!");
15975         }
15976       }
15977       break;
15978     }
15979     case CallingConv::X86_FastCall:
15980     case CallingConv::X86_ThisCall:
15981     case CallingConv::Fast:
15982       // Pass 'nest' parameter in EAX.
15983       // Must be kept in sync with X86CallingConv.td
15984       NestReg = X86::EAX;
15985       break;
15986     }
15987
15988     SDValue OutChains[4];
15989     SDValue Addr, Disp;
15990
15991     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15992                        DAG.getConstant(10, dl, MVT::i32));
15993     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15994
15995     // This is storing the opcode for MOV32ri.
15996     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15997     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15998     OutChains[0] = DAG.getStore(Root, dl,
15999                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16000                                 Trmp, MachinePointerInfo(TrmpAddr),
16001                                 false, false, 0);
16002
16003     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16004                        DAG.getConstant(1, dl, MVT::i32));
16005     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16006                                 MachinePointerInfo(TrmpAddr, 1),
16007                                 false, false, 1);
16008
16009     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16010     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16011                        DAG.getConstant(5, dl, MVT::i32));
16012     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16013                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16014                                 false, false, 1);
16015
16016     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16017                        DAG.getConstant(6, dl, MVT::i32));
16018     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16019                                 MachinePointerInfo(TrmpAddr, 6),
16020                                 false, false, 1);
16021
16022     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16023   }
16024 }
16025
16026 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16027                                             SelectionDAG &DAG) const {
16028   /*
16029    The rounding mode is in bits 11:10 of FPSR, and has the following
16030    settings:
16031      00 Round to nearest
16032      01 Round to -inf
16033      10 Round to +inf
16034      11 Round to 0
16035
16036   FLT_ROUNDS, on the other hand, expects the following:
16037     -1 Undefined
16038      0 Round to 0
16039      1 Round to nearest
16040      2 Round to +inf
16041      3 Round to -inf
16042
16043   To perform the conversion, we do:
16044     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16045   */
16046
16047   MachineFunction &MF = DAG.getMachineFunction();
16048   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16049   unsigned StackAlignment = TFI.getStackAlignment();
16050   MVT VT = Op.getSimpleValueType();
16051   SDLoc DL(Op);
16052
16053   // Save FP Control Word to stack slot
16054   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16055   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
16056
16057   MachineMemOperand *MMO =
16058    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16059                            MachineMemOperand::MOStore, 2, 2);
16060
16061   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16062   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16063                                           DAG.getVTList(MVT::Other),
16064                                           Ops, MVT::i16, MMO);
16065
16066   // Load FP Control Word from stack slot
16067   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16068                             MachinePointerInfo(), false, false, false, 0);
16069
16070   // Transform as necessary
16071   SDValue CWD1 =
16072     DAG.getNode(ISD::SRL, DL, MVT::i16,
16073                 DAG.getNode(ISD::AND, DL, MVT::i16,
16074                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16075                 DAG.getConstant(11, DL, MVT::i8));
16076   SDValue CWD2 =
16077     DAG.getNode(ISD::SRL, DL, MVT::i16,
16078                 DAG.getNode(ISD::AND, DL, MVT::i16,
16079                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16080                 DAG.getConstant(9, DL, MVT::i8));
16081
16082   SDValue RetVal =
16083     DAG.getNode(ISD::AND, DL, MVT::i16,
16084                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16085                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16086                             DAG.getConstant(1, DL, MVT::i16)),
16087                 DAG.getConstant(3, DL, MVT::i16));
16088
16089   return DAG.getNode((VT.getSizeInBits() < 16 ?
16090                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16091 }
16092
16093 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16094   MVT VT = Op.getSimpleValueType();
16095   EVT OpVT = VT;
16096   unsigned NumBits = VT.getSizeInBits();
16097   SDLoc dl(Op);
16098
16099   Op = Op.getOperand(0);
16100   if (VT == MVT::i8) {
16101     // Zero extend to i32 since there is not an i8 bsr.
16102     OpVT = MVT::i32;
16103     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16104   }
16105
16106   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16107   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16108   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16109
16110   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16111   SDValue Ops[] = {
16112     Op,
16113     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16114     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16115     Op.getValue(1)
16116   };
16117   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16118
16119   // Finally xor with NumBits-1.
16120   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16121                    DAG.getConstant(NumBits - 1, dl, OpVT));
16122
16123   if (VT == MVT::i8)
16124     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16125   return Op;
16126 }
16127
16128 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16129   MVT VT = Op.getSimpleValueType();
16130   EVT OpVT = VT;
16131   unsigned NumBits = VT.getSizeInBits();
16132   SDLoc dl(Op);
16133
16134   Op = Op.getOperand(0);
16135   if (VT == MVT::i8) {
16136     // Zero extend to i32 since there is not an i8 bsr.
16137     OpVT = MVT::i32;
16138     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16139   }
16140
16141   // Issue a bsr (scan bits in reverse).
16142   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16143   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16144
16145   // And xor with NumBits-1.
16146   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16147                    DAG.getConstant(NumBits - 1, dl, OpVT));
16148
16149   if (VT == MVT::i8)
16150     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16151   return Op;
16152 }
16153
16154 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16155   MVT VT = Op.getSimpleValueType();
16156   unsigned NumBits = VT.getSizeInBits();
16157   SDLoc dl(Op);
16158   Op = Op.getOperand(0);
16159
16160   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16161   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16162   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16163
16164   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16165   SDValue Ops[] = {
16166     Op,
16167     DAG.getConstant(NumBits, dl, VT),
16168     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16169     Op.getValue(1)
16170   };
16171   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16172 }
16173
16174 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16175 // ones, and then concatenate the result back.
16176 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16177   MVT VT = Op.getSimpleValueType();
16178
16179   assert(VT.is256BitVector() && VT.isInteger() &&
16180          "Unsupported value type for operation");
16181
16182   unsigned NumElems = VT.getVectorNumElements();
16183   SDLoc dl(Op);
16184
16185   // Extract the LHS vectors
16186   SDValue LHS = Op.getOperand(0);
16187   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16188   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16189
16190   // Extract the RHS vectors
16191   SDValue RHS = Op.getOperand(1);
16192   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16193   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16194
16195   MVT EltVT = VT.getVectorElementType();
16196   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16197
16198   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16199                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16200                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16201 }
16202
16203 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16204   if (Op.getValueType() == MVT::i1)
16205     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16206                        Op.getOperand(0), Op.getOperand(1));
16207   assert(Op.getSimpleValueType().is256BitVector() &&
16208          Op.getSimpleValueType().isInteger() &&
16209          "Only handle AVX 256-bit vector integer operation");
16210   return Lower256IntArith(Op, DAG);
16211 }
16212
16213 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16214   if (Op.getValueType() == MVT::i1)
16215     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16216                        Op.getOperand(0), Op.getOperand(1));
16217   assert(Op.getSimpleValueType().is256BitVector() &&
16218          Op.getSimpleValueType().isInteger() &&
16219          "Only handle AVX 256-bit vector integer operation");
16220   return Lower256IntArith(Op, DAG);
16221 }
16222
16223 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16224                         SelectionDAG &DAG) {
16225   SDLoc dl(Op);
16226   MVT VT = Op.getSimpleValueType();
16227
16228   if (VT == MVT::i1)
16229     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16230
16231   // Decompose 256-bit ops into smaller 128-bit ops.
16232   if (VT.is256BitVector() && !Subtarget->hasInt256())
16233     return Lower256IntArith(Op, DAG);
16234
16235   SDValue A = Op.getOperand(0);
16236   SDValue B = Op.getOperand(1);
16237
16238   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16239   // pairs, multiply and truncate.
16240   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16241     if (Subtarget->hasInt256()) {
16242       if (VT == MVT::v32i8) {
16243         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16244         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16245         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16246         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16247         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16248         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16249         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16250         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16251                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16252                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16253       }
16254
16255       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16256       return DAG.getNode(
16257           ISD::TRUNCATE, dl, VT,
16258           DAG.getNode(ISD::MUL, dl, ExVT,
16259                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16260                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16261     }
16262
16263     assert(VT == MVT::v16i8 &&
16264            "Pre-AVX2 support only supports v16i8 multiplication");
16265     MVT ExVT = MVT::v8i16;
16266
16267     // Extract the lo parts and sign extend to i16
16268     SDValue ALo, BLo;
16269     if (Subtarget->hasSSE41()) {
16270       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16271       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16272     } else {
16273       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16274                               -1, 4, -1, 5, -1, 6, -1, 7};
16275       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16276       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16277       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16278       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16279       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16280       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16281     }
16282
16283     // Extract the hi parts and sign extend to i16
16284     SDValue AHi, BHi;
16285     if (Subtarget->hasSSE41()) {
16286       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16287                               -1, -1, -1, -1, -1, -1, -1, -1};
16288       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16289       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16290       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16291       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16292     } else {
16293       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16294                               -1, 12, -1, 13, -1, 14, -1, 15};
16295       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16296       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16297       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16298       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16299       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16300       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16301     }
16302
16303     // Multiply, mask the lower 8bits of the lo/hi results and pack
16304     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16305     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16306     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16307     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16308     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16309   }
16310
16311   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16312   if (VT == MVT::v4i32) {
16313     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16314            "Should not custom lower when pmuldq is available!");
16315
16316     // Extract the odd parts.
16317     static const int UnpackMask[] = { 1, -1, 3, -1 };
16318     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16319     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16320
16321     // Multiply the even parts.
16322     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16323     // Now multiply odd parts.
16324     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16325
16326     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16327     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16328
16329     // Merge the two vectors back together with a shuffle. This expands into 2
16330     // shuffles.
16331     static const int ShufMask[] = { 0, 4, 2, 6 };
16332     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16333   }
16334
16335   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16336          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16337
16338   //  Ahi = psrlqi(a, 32);
16339   //  Bhi = psrlqi(b, 32);
16340   //
16341   //  AloBlo = pmuludq(a, b);
16342   //  AloBhi = pmuludq(a, Bhi);
16343   //  AhiBlo = pmuludq(Ahi, b);
16344
16345   //  AloBhi = psllqi(AloBhi, 32);
16346   //  AhiBlo = psllqi(AhiBlo, 32);
16347   //  return AloBlo + AloBhi + AhiBlo;
16348
16349   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16350   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16351
16352   // Bit cast to 32-bit vectors for MULUDQ
16353   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16354                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16355   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16356   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16357   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16358   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16359
16360   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16361   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16362   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16363
16364   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16365   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16366
16367   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16368   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16369 }
16370
16371 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16372   assert(Subtarget->isTargetWin64() && "Unexpected target");
16373   EVT VT = Op.getValueType();
16374   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16375          "Unexpected return type for lowering");
16376
16377   RTLIB::Libcall LC;
16378   bool isSigned;
16379   switch (Op->getOpcode()) {
16380   default: llvm_unreachable("Unexpected request for libcall!");
16381   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16382   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16383   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16384   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16385   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16386   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16387   }
16388
16389   SDLoc dl(Op);
16390   SDValue InChain = DAG.getEntryNode();
16391
16392   TargetLowering::ArgListTy Args;
16393   TargetLowering::ArgListEntry Entry;
16394   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16395     EVT ArgVT = Op->getOperand(i).getValueType();
16396     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16397            "Unexpected argument type for lowering");
16398     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16399     Entry.Node = StackPtr;
16400     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16401                            false, false, 16);
16402     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16403     Entry.Ty = PointerType::get(ArgTy,0);
16404     Entry.isSExt = false;
16405     Entry.isZExt = false;
16406     Args.push_back(Entry);
16407   }
16408
16409   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16410                                          getPointerTy());
16411
16412   TargetLowering::CallLoweringInfo CLI(DAG);
16413   CLI.setDebugLoc(dl).setChain(InChain)
16414     .setCallee(getLibcallCallingConv(LC),
16415                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16416                Callee, std::move(Args), 0)
16417     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16418
16419   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16420   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16421 }
16422
16423 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16424                              SelectionDAG &DAG) {
16425   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16426   EVT VT = Op0.getValueType();
16427   SDLoc dl(Op);
16428
16429   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16430          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16431
16432   // PMULxD operations multiply each even value (starting at 0) of LHS with
16433   // the related value of RHS and produce a widen result.
16434   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16435   // => <2 x i64> <ae|cg>
16436   //
16437   // In other word, to have all the results, we need to perform two PMULxD:
16438   // 1. one with the even values.
16439   // 2. one with the odd values.
16440   // To achieve #2, with need to place the odd values at an even position.
16441   //
16442   // Place the odd value at an even position (basically, shift all values 1
16443   // step to the left):
16444   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16445   // <a|b|c|d> => <b|undef|d|undef>
16446   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16447   // <e|f|g|h> => <f|undef|h|undef>
16448   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16449
16450   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16451   // ints.
16452   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16453   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16454   unsigned Opcode =
16455       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16456   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16457   // => <2 x i64> <ae|cg>
16458   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16459                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16460   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16461   // => <2 x i64> <bf|dh>
16462   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16463                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16464
16465   // Shuffle it back into the right order.
16466   SDValue Highs, Lows;
16467   if (VT == MVT::v8i32) {
16468     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16469     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16470     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16471     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16472   } else {
16473     const int HighMask[] = {1, 5, 3, 7};
16474     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16475     const int LowMask[] = {0, 4, 2, 6};
16476     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16477   }
16478
16479   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16480   // unsigned multiply.
16481   if (IsSigned && !Subtarget->hasSSE41()) {
16482     SDValue ShAmt =
16483         DAG.getConstant(31, dl,
16484                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16485     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16486                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16487     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16488                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16489
16490     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16491     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16492   }
16493
16494   // The first result of MUL_LOHI is actually the low value, followed by the
16495   // high value.
16496   SDValue Ops[] = {Lows, Highs};
16497   return DAG.getMergeValues(Ops, dl);
16498 }
16499
16500 // Return true if the requred (according to Opcode) shift-imm form is natively
16501 // supported by the Subtarget
16502 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget, 
16503                                         unsigned Opcode) {
16504   if (VT.getScalarSizeInBits() < 16)
16505     return false;
16506  
16507   if (VT.is512BitVector() &&
16508       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16509     return true;
16510
16511   bool LShift = VT.is128BitVector() || 
16512     (VT.is256BitVector() && Subtarget->hasInt256());
16513
16514   bool AShift = LShift && (Subtarget->hasVLX() ||
16515     (VT != MVT::v2i64 && VT != MVT::v4i64));
16516   return (Opcode == ISD::SRA) ? AShift : LShift;
16517 }
16518
16519 // The shift amount is a variable, but it is the same for all vector lanes.
16520 // These instrcutions are defined together with shift-immediate.
16521 static 
16522 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget, 
16523                                       unsigned Opcode) {
16524   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16525 }
16526
16527 // Return true if the requred (according to Opcode) variable-shift form is
16528 // natively supported by the Subtarget
16529 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget, 
16530                                     unsigned Opcode) {
16531
16532   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16533     return false;
16534
16535   // vXi16 supported only on AVX-512, BWI
16536   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16537     return false;
16538
16539   if (VT.is512BitVector() || Subtarget->hasVLX())
16540     return true;
16541
16542   bool LShift = VT.is128BitVector() || VT.is256BitVector();
16543   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
16544   return (Opcode == ISD::SRA) ? AShift : LShift;
16545 }
16546
16547 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16548                                          const X86Subtarget *Subtarget) {
16549   MVT VT = Op.getSimpleValueType();
16550   SDLoc dl(Op);
16551   SDValue R = Op.getOperand(0);
16552   SDValue Amt = Op.getOperand(1);
16553
16554   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16555     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16556
16557   // Optimize shl/srl/sra with constant shift amount.
16558   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16559     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16560       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16561
16562       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
16563         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16564
16565       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16566         unsigned NumElts = VT.getVectorNumElements();
16567         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16568
16569         if (Op.getOpcode() == ISD::SHL) {
16570           // Simple i8 add case
16571           if (ShiftAmt == 1)
16572             return DAG.getNode(ISD::ADD, dl, VT, R, R);
16573
16574           // Make a large shift.
16575           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16576                                                    R, ShiftAmt, DAG);
16577           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16578           // Zero out the rightmost bits.
16579           SmallVector<SDValue, 32> V(
16580               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16581           return DAG.getNode(ISD::AND, dl, VT, SHL,
16582                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16583         }
16584         if (Op.getOpcode() == ISD::SRL) {
16585           // Make a large shift.
16586           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16587                                                    R, ShiftAmt, DAG);
16588           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16589           // Zero out the leftmost bits.
16590           SmallVector<SDValue, 32> V(
16591               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16592           return DAG.getNode(ISD::AND, dl, VT, SRL,
16593                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16594         }
16595         if (Op.getOpcode() == ISD::SRA) {
16596           if (ShiftAmt == 7) {
16597             // R s>> 7  ===  R s< 0
16598             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16599             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16600           }
16601
16602           // R s>> a === ((R u>> a) ^ m) - m
16603           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16604           SmallVector<SDValue, 32> V(NumElts,
16605                                      DAG.getConstant(128 >> ShiftAmt, dl,
16606                                                      MVT::i8));
16607           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16608           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16609           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16610           return Res;
16611         }
16612         llvm_unreachable("Unknown shift opcode.");
16613       }
16614     }
16615   }
16616
16617   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16618   if (!Subtarget->is64Bit() &&
16619       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16620       Amt.getOpcode() == ISD::BITCAST &&
16621       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16622     Amt = Amt.getOperand(0);
16623     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16624                      VT.getVectorNumElements();
16625     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16626     uint64_t ShiftAmt = 0;
16627     for (unsigned i = 0; i != Ratio; ++i) {
16628       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16629       if (!C)
16630         return SDValue();
16631       // 6 == Log2(64)
16632       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16633     }
16634     // Check remaining shift amounts.
16635     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16636       uint64_t ShAmt = 0;
16637       for (unsigned j = 0; j != Ratio; ++j) {
16638         ConstantSDNode *C =
16639           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16640         if (!C)
16641           return SDValue();
16642         // 6 == Log2(64)
16643         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16644       }
16645       if (ShAmt != ShiftAmt)
16646         return SDValue();
16647     }
16648     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16649   }
16650
16651   return SDValue();
16652 }
16653
16654 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16655                                         const X86Subtarget* Subtarget) {
16656   MVT VT = Op.getSimpleValueType();
16657   SDLoc dl(Op);
16658   SDValue R = Op.getOperand(0);
16659   SDValue Amt = Op.getOperand(1);
16660
16661   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16662     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16663
16664   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
16665     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
16666
16667   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
16668     SDValue BaseShAmt;
16669     EVT EltVT = VT.getVectorElementType();
16670
16671     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16672       // Check if this build_vector node is doing a splat.
16673       // If so, then set BaseShAmt equal to the splat value.
16674       BaseShAmt = BV->getSplatValue();
16675       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16676         BaseShAmt = SDValue();
16677     } else {
16678       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16679         Amt = Amt.getOperand(0);
16680
16681       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16682       if (SVN && SVN->isSplat()) {
16683         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16684         SDValue InVec = Amt.getOperand(0);
16685         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16686           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16687                  "Unexpected shuffle index found!");
16688           BaseShAmt = InVec.getOperand(SplatIdx);
16689         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16690            if (ConstantSDNode *C =
16691                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16692              if (C->getZExtValue() == SplatIdx)
16693                BaseShAmt = InVec.getOperand(1);
16694            }
16695         }
16696
16697         if (!BaseShAmt)
16698           // Avoid introducing an extract element from a shuffle.
16699           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16700                                   DAG.getIntPtrConstant(SplatIdx, dl));
16701       }
16702     }
16703
16704     if (BaseShAmt.getNode()) {
16705       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16706       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16707         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16708       else if (EltVT.bitsLT(MVT::i32))
16709         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16710
16711       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
16712     }
16713   }
16714
16715   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16716   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16717       Amt.getOpcode() == ISD::BITCAST &&
16718       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16719     Amt = Amt.getOperand(0);
16720     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16721                      VT.getVectorNumElements();
16722     std::vector<SDValue> Vals(Ratio);
16723     for (unsigned i = 0; i != Ratio; ++i)
16724       Vals[i] = Amt.getOperand(i);
16725     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16726       for (unsigned j = 0; j != Ratio; ++j)
16727         if (Vals[j] != Amt.getOperand(i + j))
16728           return SDValue();
16729     }
16730     return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
16731   }
16732   return SDValue();
16733 }
16734
16735 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16736                           SelectionDAG &DAG) {
16737   MVT VT = Op.getSimpleValueType();
16738   SDLoc dl(Op);
16739   SDValue R = Op.getOperand(0);
16740   SDValue Amt = Op.getOperand(1);
16741
16742   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16743   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16744
16745   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16746     return V;
16747
16748   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16749       return V;
16750
16751   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
16752     return Op;
16753
16754   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16755   // shifts per-lane and then shuffle the partial results back together.
16756   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16757     // Splat the shift amounts so the scalar shifts above will catch it.
16758     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16759     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16760     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16761     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16762     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16763   }
16764
16765   // If possible, lower this packed shift into a vector multiply instead of
16766   // expanding it into a sequence of scalar shifts.
16767   // Do this only if the vector shift count is a constant build_vector.
16768   if (Op.getOpcode() == ISD::SHL &&
16769       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16770        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16771       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16772     SmallVector<SDValue, 8> Elts;
16773     EVT SVT = VT.getScalarType();
16774     unsigned SVTBits = SVT.getSizeInBits();
16775     const APInt &One = APInt(SVTBits, 1);
16776     unsigned NumElems = VT.getVectorNumElements();
16777
16778     for (unsigned i=0; i !=NumElems; ++i) {
16779       SDValue Op = Amt->getOperand(i);
16780       if (Op->getOpcode() == ISD::UNDEF) {
16781         Elts.push_back(Op);
16782         continue;
16783       }
16784
16785       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16786       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16787       uint64_t ShAmt = C.getZExtValue();
16788       if (ShAmt >= SVTBits) {
16789         Elts.push_back(DAG.getUNDEF(SVT));
16790         continue;
16791       }
16792       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16793     }
16794     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16795     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16796   }
16797
16798   // Lower SHL with variable shift amount.
16799   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16800     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16801
16802     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16803                      DAG.getConstant(0x3f800000U, dl, VT));
16804     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16805     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16806     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16807   }
16808
16809   // If possible, lower this shift as a sequence of two shifts by
16810   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16811   // Example:
16812   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16813   //
16814   // Could be rewritten as:
16815   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16816   //
16817   // The advantage is that the two shifts from the example would be
16818   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16819   // the vector shift into four scalar shifts plus four pairs of vector
16820   // insert/extract.
16821   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16822       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16823     unsigned TargetOpcode = X86ISD::MOVSS;
16824     bool CanBeSimplified;
16825     // The splat value for the first packed shift (the 'X' from the example).
16826     SDValue Amt1 = Amt->getOperand(0);
16827     // The splat value for the second packed shift (the 'Y' from the example).
16828     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16829                                         Amt->getOperand(2);
16830
16831     // See if it is possible to replace this node with a sequence of
16832     // two shifts followed by a MOVSS/MOVSD
16833     if (VT == MVT::v4i32) {
16834       // Check if it is legal to use a MOVSS.
16835       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16836                         Amt2 == Amt->getOperand(3);
16837       if (!CanBeSimplified) {
16838         // Otherwise, check if we can still simplify this node using a MOVSD.
16839         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16840                           Amt->getOperand(2) == Amt->getOperand(3);
16841         TargetOpcode = X86ISD::MOVSD;
16842         Amt2 = Amt->getOperand(2);
16843       }
16844     } else {
16845       // Do similar checks for the case where the machine value type
16846       // is MVT::v8i16.
16847       CanBeSimplified = Amt1 == Amt->getOperand(1);
16848       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16849         CanBeSimplified = Amt2 == Amt->getOperand(i);
16850
16851       if (!CanBeSimplified) {
16852         TargetOpcode = X86ISD::MOVSD;
16853         CanBeSimplified = true;
16854         Amt2 = Amt->getOperand(4);
16855         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16856           CanBeSimplified = Amt1 == Amt->getOperand(i);
16857         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16858           CanBeSimplified = Amt2 == Amt->getOperand(j);
16859       }
16860     }
16861
16862     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16863         isa<ConstantSDNode>(Amt2)) {
16864       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16865       EVT CastVT = MVT::v4i32;
16866       SDValue Splat1 =
16867         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16868       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16869       SDValue Splat2 =
16870         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16871       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16872       if (TargetOpcode == X86ISD::MOVSD)
16873         CastVT = MVT::v2i64;
16874       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16875       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16876       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16877                                             BitCast1, DAG);
16878       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16879     }
16880   }
16881
16882   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16883     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16884     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16885
16886     SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16887     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16888     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16889
16890     // r = VSELECT(r, shl(r, 4), a);
16891     SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16892     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16893
16894     // a += a
16895     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16896     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16897     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16898
16899     // r = VSELECT(r, shl(r, 2), a);
16900     M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16901     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16902
16903     // a += a
16904     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16905     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16906     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16907
16908     // return VSELECT(r, r+r, a);
16909     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16910                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16911     return R;
16912   }
16913
16914   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16915   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16916   // solution better.
16917   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16918     MVT ExtVT = MVT::v8i32;
16919     unsigned ExtOpc =
16920         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16921     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
16922     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
16923     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16924                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
16925   }
16926
16927   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
16928     MVT ExtVT = MVT::v8i32;
16929     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
16930     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
16931     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
16932     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
16933     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
16934     ALo = DAG.getNode(ISD::BITCAST, dl, ExtVT, ALo);
16935     AHi = DAG.getNode(ISD::BITCAST, dl, ExtVT, AHi);
16936     RLo = DAG.getNode(ISD::BITCAST, dl, ExtVT, RLo);
16937     RHi = DAG.getNode(ISD::BITCAST, dl, ExtVT, RHi);
16938     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
16939     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
16940     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
16941     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
16942     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
16943   }
16944
16945   // Decompose 256-bit shifts into smaller 128-bit shifts.
16946   if (VT.is256BitVector()) {
16947     unsigned NumElems = VT.getVectorNumElements();
16948     MVT EltVT = VT.getVectorElementType();
16949     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16950
16951     // Extract the two vectors
16952     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16953     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16954
16955     // Recreate the shift amount vectors
16956     SDValue Amt1, Amt2;
16957     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16958       // Constant shift amount
16959       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16960       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16961       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16962
16963       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16964       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16965     } else {
16966       // Variable shift amount
16967       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16968       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16969     }
16970
16971     // Issue new vector shifts for the smaller types
16972     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16973     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16974
16975     // Concatenate the result back
16976     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16977   }
16978
16979   return SDValue();
16980 }
16981
16982 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16983   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16984   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16985   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16986   // has only one use.
16987   SDNode *N = Op.getNode();
16988   SDValue LHS = N->getOperand(0);
16989   SDValue RHS = N->getOperand(1);
16990   unsigned BaseOp = 0;
16991   unsigned Cond = 0;
16992   SDLoc DL(Op);
16993   switch (Op.getOpcode()) {
16994   default: llvm_unreachable("Unknown ovf instruction!");
16995   case ISD::SADDO:
16996     // A subtract of one will be selected as a INC. Note that INC doesn't
16997     // set CF, so we can't do this for UADDO.
16998     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16999       if (C->isOne()) {
17000         BaseOp = X86ISD::INC;
17001         Cond = X86::COND_O;
17002         break;
17003       }
17004     BaseOp = X86ISD::ADD;
17005     Cond = X86::COND_O;
17006     break;
17007   case ISD::UADDO:
17008     BaseOp = X86ISD::ADD;
17009     Cond = X86::COND_B;
17010     break;
17011   case ISD::SSUBO:
17012     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17013     // set CF, so we can't do this for USUBO.
17014     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17015       if (C->isOne()) {
17016         BaseOp = X86ISD::DEC;
17017         Cond = X86::COND_O;
17018         break;
17019       }
17020     BaseOp = X86ISD::SUB;
17021     Cond = X86::COND_O;
17022     break;
17023   case ISD::USUBO:
17024     BaseOp = X86ISD::SUB;
17025     Cond = X86::COND_B;
17026     break;
17027   case ISD::SMULO:
17028     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17029     Cond = X86::COND_O;
17030     break;
17031   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17032     if (N->getValueType(0) == MVT::i8) {
17033       BaseOp = X86ISD::UMUL8;
17034       Cond = X86::COND_O;
17035       break;
17036     }
17037     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17038                                  MVT::i32);
17039     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17040
17041     SDValue SetCC =
17042       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17043                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17044                   SDValue(Sum.getNode(), 2));
17045
17046     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17047   }
17048   }
17049
17050   // Also sets EFLAGS.
17051   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17052   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17053
17054   SDValue SetCC =
17055     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17056                 DAG.getConstant(Cond, DL, MVT::i32),
17057                 SDValue(Sum.getNode(), 1));
17058
17059   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17060 }
17061
17062 /// Returns true if the operand type is exactly twice the native width, and
17063 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17064 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17065 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17066 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17067   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17068
17069   if (OpWidth == 64)
17070     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17071   else if (OpWidth == 128)
17072     return Subtarget->hasCmpxchg16b();
17073   else
17074     return false;
17075 }
17076
17077 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17078   return needsCmpXchgNb(SI->getValueOperand()->getType());
17079 }
17080
17081 // Note: this turns large loads into lock cmpxchg8b/16b.
17082 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17083 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17084   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17085   return needsCmpXchgNb(PTy->getElementType());
17086 }
17087
17088 TargetLoweringBase::AtomicRMWExpansionKind
17089 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17090   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17091   const Type *MemType = AI->getType();
17092
17093   // If the operand is too big, we must see if cmpxchg8/16b is available
17094   // and default to library calls otherwise.
17095   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17096     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17097                                    : AtomicRMWExpansionKind::None;
17098   }
17099
17100   AtomicRMWInst::BinOp Op = AI->getOperation();
17101   switch (Op) {
17102   default:
17103     llvm_unreachable("Unknown atomic operation");
17104   case AtomicRMWInst::Xchg:
17105   case AtomicRMWInst::Add:
17106   case AtomicRMWInst::Sub:
17107     // It's better to use xadd, xsub or xchg for these in all cases.
17108     return AtomicRMWExpansionKind::None;
17109   case AtomicRMWInst::Or:
17110   case AtomicRMWInst::And:
17111   case AtomicRMWInst::Xor:
17112     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17113     // prefix to a normal instruction for these operations.
17114     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17115                             : AtomicRMWExpansionKind::None;
17116   case AtomicRMWInst::Nand:
17117   case AtomicRMWInst::Max:
17118   case AtomicRMWInst::Min:
17119   case AtomicRMWInst::UMax:
17120   case AtomicRMWInst::UMin:
17121     // These always require a non-trivial set of data operations on x86. We must
17122     // use a cmpxchg loop.
17123     return AtomicRMWExpansionKind::CmpXChg;
17124   }
17125 }
17126
17127 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17128   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17129   // no-sse2). There isn't any reason to disable it if the target processor
17130   // supports it.
17131   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17132 }
17133
17134 LoadInst *
17135 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17136   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17137   const Type *MemType = AI->getType();
17138   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17139   // there is no benefit in turning such RMWs into loads, and it is actually
17140   // harmful as it introduces a mfence.
17141   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17142     return nullptr;
17143
17144   auto Builder = IRBuilder<>(AI);
17145   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17146   auto SynchScope = AI->getSynchScope();
17147   // We must restrict the ordering to avoid generating loads with Release or
17148   // ReleaseAcquire orderings.
17149   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17150   auto Ptr = AI->getPointerOperand();
17151
17152   // Before the load we need a fence. Here is an example lifted from
17153   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17154   // is required:
17155   // Thread 0:
17156   //   x.store(1, relaxed);
17157   //   r1 = y.fetch_add(0, release);
17158   // Thread 1:
17159   //   y.fetch_add(42, acquire);
17160   //   r2 = x.load(relaxed);
17161   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17162   // lowered to just a load without a fence. A mfence flushes the store buffer,
17163   // making the optimization clearly correct.
17164   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17165   // otherwise, we might be able to be more agressive on relaxed idempotent
17166   // rmw. In practice, they do not look useful, so we don't try to be
17167   // especially clever.
17168   if (SynchScope == SingleThread)
17169     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17170     // the IR level, so we must wrap it in an intrinsic.
17171     return nullptr;
17172
17173   if (!hasMFENCE(*Subtarget))
17174     // FIXME: it might make sense to use a locked operation here but on a
17175     // different cache-line to prevent cache-line bouncing. In practice it
17176     // is probably a small win, and x86 processors without mfence are rare
17177     // enough that we do not bother.
17178     return nullptr;
17179
17180   Function *MFence =
17181       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17182   Builder.CreateCall(MFence, {});
17183
17184   // Finally we can emit the atomic load.
17185   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17186           AI->getType()->getPrimitiveSizeInBits());
17187   Loaded->setAtomic(Order, SynchScope);
17188   AI->replaceAllUsesWith(Loaded);
17189   AI->eraseFromParent();
17190   return Loaded;
17191 }
17192
17193 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17194                                  SelectionDAG &DAG) {
17195   SDLoc dl(Op);
17196   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17197     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17198   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17199     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17200
17201   // The only fence that needs an instruction is a sequentially-consistent
17202   // cross-thread fence.
17203   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17204     if (hasMFENCE(*Subtarget))
17205       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17206
17207     SDValue Chain = Op.getOperand(0);
17208     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17209     SDValue Ops[] = {
17210       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17211       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17212       DAG.getRegister(0, MVT::i32),            // Index
17213       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17214       DAG.getRegister(0, MVT::i32),            // Segment.
17215       Zero,
17216       Chain
17217     };
17218     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17219     return SDValue(Res, 0);
17220   }
17221
17222   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17223   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17224 }
17225
17226 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17227                              SelectionDAG &DAG) {
17228   MVT T = Op.getSimpleValueType();
17229   SDLoc DL(Op);
17230   unsigned Reg = 0;
17231   unsigned size = 0;
17232   switch(T.SimpleTy) {
17233   default: llvm_unreachable("Invalid value type!");
17234   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17235   case MVT::i16: Reg = X86::AX;  size = 2; break;
17236   case MVT::i32: Reg = X86::EAX; size = 4; break;
17237   case MVT::i64:
17238     assert(Subtarget->is64Bit() && "Node not type legal!");
17239     Reg = X86::RAX; size = 8;
17240     break;
17241   }
17242   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17243                                   Op.getOperand(2), SDValue());
17244   SDValue Ops[] = { cpIn.getValue(0),
17245                     Op.getOperand(1),
17246                     Op.getOperand(3),
17247                     DAG.getTargetConstant(size, DL, MVT::i8),
17248                     cpIn.getValue(1) };
17249   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17250   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17251   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17252                                            Ops, T, MMO);
17253
17254   SDValue cpOut =
17255     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17256   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17257                                       MVT::i32, cpOut.getValue(2));
17258   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17259                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17260                                 EFLAGS);
17261
17262   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17263   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17264   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17265   return SDValue();
17266 }
17267
17268 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17269                             SelectionDAG &DAG) {
17270   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17271   MVT DstVT = Op.getSimpleValueType();
17272
17273   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17274     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17275     if (DstVT != MVT::f64)
17276       // This conversion needs to be expanded.
17277       return SDValue();
17278
17279     SDValue InVec = Op->getOperand(0);
17280     SDLoc dl(Op);
17281     unsigned NumElts = SrcVT.getVectorNumElements();
17282     EVT SVT = SrcVT.getVectorElementType();
17283
17284     // Widen the vector in input in the case of MVT::v2i32.
17285     // Example: from MVT::v2i32 to MVT::v4i32.
17286     SmallVector<SDValue, 16> Elts;
17287     for (unsigned i = 0, e = NumElts; i != e; ++i)
17288       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17289                                  DAG.getIntPtrConstant(i, dl)));
17290
17291     // Explicitly mark the extra elements as Undef.
17292     Elts.append(NumElts, DAG.getUNDEF(SVT));
17293
17294     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17295     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17296     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17297     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17298                        DAG.getIntPtrConstant(0, dl));
17299   }
17300
17301   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17302          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17303   assert((DstVT == MVT::i64 ||
17304           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17305          "Unexpected custom BITCAST");
17306   // i64 <=> MMX conversions are Legal.
17307   if (SrcVT==MVT::i64 && DstVT.isVector())
17308     return Op;
17309   if (DstVT==MVT::i64 && SrcVT.isVector())
17310     return Op;
17311   // MMX <=> MMX conversions are Legal.
17312   if (SrcVT.isVector() && DstVT.isVector())
17313     return Op;
17314   // All other conversions need to be expanded.
17315   return SDValue();
17316 }
17317
17318 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17319                           SelectionDAG &DAG) {
17320   SDNode *Node = Op.getNode();
17321   SDLoc dl(Node);
17322
17323   Op = Op.getOperand(0);
17324   EVT VT = Op.getValueType();
17325   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17326          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17327
17328   unsigned NumElts = VT.getVectorNumElements();
17329   EVT EltVT = VT.getVectorElementType();
17330   unsigned Len = EltVT.getSizeInBits();
17331
17332   // This is the vectorized version of the "best" algorithm from
17333   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17334   // with a minor tweak to use a series of adds + shifts instead of vector
17335   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17336   //
17337   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17338   //  v8i32 => Always profitable
17339   //
17340   // FIXME: There a couple of possible improvements:
17341   //
17342   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17343   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17344   //
17345   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17346          "CTPOP not implemented for this vector element type.");
17347
17348   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17349   // extra legalization.
17350   bool NeedsBitcast = EltVT == MVT::i32;
17351   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17352
17353   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17354                                   EltVT);
17355   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17356                                   EltVT);
17357   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17358                                   EltVT);
17359
17360   // v = v - ((v >> 1) & 0x55555555...)
17361   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17362   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17363   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17364   if (NeedsBitcast)
17365     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17366
17367   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17368   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17369   if (NeedsBitcast)
17370     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17371
17372   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17373   if (VT != And.getValueType())
17374     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17375   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17376
17377   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17378   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17379   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17380   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17381   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17382
17383   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17384   if (NeedsBitcast) {
17385     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17386     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17387     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17388   }
17389
17390   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17391   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17392   if (VT != AndRHS.getValueType()) {
17393     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17394     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17395   }
17396   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17397
17398   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17399   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17400   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17401   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17402   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17403
17404   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17405   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17406   if (NeedsBitcast) {
17407     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17408     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17409   }
17410   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17411   if (VT != And.getValueType())
17412     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17413
17414   // The algorithm mentioned above uses:
17415   //    v = (v * 0x01010101...) >> (Len - 8)
17416   //
17417   // Change it to use vector adds + vector shifts which yield faster results on
17418   // Haswell than using vector integer multiplication.
17419   //
17420   // For i32 elements:
17421   //    v = v + (v >> 8)
17422   //    v = v + (v >> 16)
17423   //
17424   // For i64 elements:
17425   //    v = v + (v >> 8)
17426   //    v = v + (v >> 16)
17427   //    v = v + (v >> 32)
17428   //
17429   Add = And;
17430   SmallVector<SDValue, 8> Csts;
17431   for (unsigned i = 8; i <= Len/2; i *= 2) {
17432     Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17433     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17434     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17435     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17436     Csts.clear();
17437   }
17438
17439   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17440   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17441                                   EltVT);
17442   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17443   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17444   if (NeedsBitcast) {
17445     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17446     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17447   }
17448   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17449   if (VT != And.getValueType())
17450     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17451
17452   return And;
17453 }
17454
17455 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17456   SDNode *Node = Op.getNode();
17457   SDLoc dl(Node);
17458   EVT T = Node->getValueType(0);
17459   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17460                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17461   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17462                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17463                        Node->getOperand(0),
17464                        Node->getOperand(1), negOp,
17465                        cast<AtomicSDNode>(Node)->getMemOperand(),
17466                        cast<AtomicSDNode>(Node)->getOrdering(),
17467                        cast<AtomicSDNode>(Node)->getSynchScope());
17468 }
17469
17470 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17471   SDNode *Node = Op.getNode();
17472   SDLoc dl(Node);
17473   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17474
17475   // Convert seq_cst store -> xchg
17476   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17477   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17478   //        (The only way to get a 16-byte store is cmpxchg16b)
17479   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17480   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17481       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17482     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17483                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17484                                  Node->getOperand(0),
17485                                  Node->getOperand(1), Node->getOperand(2),
17486                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17487                                  cast<AtomicSDNode>(Node)->getOrdering(),
17488                                  cast<AtomicSDNode>(Node)->getSynchScope());
17489     return Swap.getValue(1);
17490   }
17491   // Other atomic stores have a simple pattern.
17492   return Op;
17493 }
17494
17495 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17496   EVT VT = Op.getNode()->getSimpleValueType(0);
17497
17498   // Let legalize expand this if it isn't a legal type yet.
17499   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17500     return SDValue();
17501
17502   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17503
17504   unsigned Opc;
17505   bool ExtraOp = false;
17506   switch (Op.getOpcode()) {
17507   default: llvm_unreachable("Invalid code");
17508   case ISD::ADDC: Opc = X86ISD::ADD; break;
17509   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17510   case ISD::SUBC: Opc = X86ISD::SUB; break;
17511   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17512   }
17513
17514   if (!ExtraOp)
17515     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17516                        Op.getOperand(1));
17517   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17518                      Op.getOperand(1), Op.getOperand(2));
17519 }
17520
17521 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17522                             SelectionDAG &DAG) {
17523   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17524
17525   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17526   // which returns the values as { float, float } (in XMM0) or
17527   // { double, double } (which is returned in XMM0, XMM1).
17528   SDLoc dl(Op);
17529   SDValue Arg = Op.getOperand(0);
17530   EVT ArgVT = Arg.getValueType();
17531   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17532
17533   TargetLowering::ArgListTy Args;
17534   TargetLowering::ArgListEntry Entry;
17535
17536   Entry.Node = Arg;
17537   Entry.Ty = ArgTy;
17538   Entry.isSExt = false;
17539   Entry.isZExt = false;
17540   Args.push_back(Entry);
17541
17542   bool isF64 = ArgVT == MVT::f64;
17543   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17544   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17545   // the results are returned via SRet in memory.
17546   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17547   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17548   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17549
17550   Type *RetTy = isF64
17551     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17552     : (Type*)VectorType::get(ArgTy, 4);
17553
17554   TargetLowering::CallLoweringInfo CLI(DAG);
17555   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17556     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17557
17558   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17559
17560   if (isF64)
17561     // Returned in xmm0 and xmm1.
17562     return CallResult.first;
17563
17564   // Returned in bits 0:31 and 32:64 xmm0.
17565   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17566                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17567   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17568                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17569   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17570   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17571 }
17572
17573 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17574                              SelectionDAG &DAG) {
17575   assert(Subtarget->hasAVX512() &&
17576          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17577
17578   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17579   EVT VT = N->getValue().getValueType();
17580   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17581   SDLoc dl(Op);
17582
17583   // X86 scatter kills mask register, so its type should be added to
17584   // the list of return values
17585   if (N->getNumValues() == 1) {
17586     SDValue Index = N->getIndex();
17587     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17588         !Index.getValueType().is512BitVector())
17589       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17590
17591     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17592     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17593                       N->getOperand(3), Index };
17594
17595     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17596     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17597     return SDValue(NewScatter.getNode(), 0);
17598   }
17599   return Op;
17600 }
17601
17602 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17603                             SelectionDAG &DAG) {
17604   assert(Subtarget->hasAVX512() &&
17605          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17606
17607   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17608   EVT VT = Op.getValueType();
17609   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17610   SDLoc dl(Op);
17611
17612   SDValue Index = N->getIndex();
17613   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17614       !Index.getValueType().is512BitVector()) {
17615     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17616     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17617                       N->getOperand(3), Index };
17618     DAG.UpdateNodeOperands(N, Ops);
17619   }
17620   return Op;
17621 }
17622
17623 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17624                                                     SelectionDAG &DAG) const {
17625   // TODO: Eventually, the lowering of these nodes should be informed by or
17626   // deferred to the GC strategy for the function in which they appear. For
17627   // now, however, they must be lowered to something. Since they are logically
17628   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17629   // require special handling for these nodes), lower them as literal NOOPs for
17630   // the time being.
17631   SmallVector<SDValue, 2> Ops;
17632
17633   Ops.push_back(Op.getOperand(0));
17634   if (Op->getGluedNode())
17635     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17636
17637   SDLoc OpDL(Op);
17638   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17639   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17640
17641   return NOOP;
17642 }
17643
17644 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17645                                                   SelectionDAG &DAG) const {
17646   // TODO: Eventually, the lowering of these nodes should be informed by or
17647   // deferred to the GC strategy for the function in which they appear. For
17648   // now, however, they must be lowered to something. Since they are logically
17649   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17650   // require special handling for these nodes), lower them as literal NOOPs for
17651   // the time being.
17652   SmallVector<SDValue, 2> Ops;
17653
17654   Ops.push_back(Op.getOperand(0));
17655   if (Op->getGluedNode())
17656     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17657
17658   SDLoc OpDL(Op);
17659   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17660   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17661
17662   return NOOP;
17663 }
17664
17665 /// LowerOperation - Provide custom lowering hooks for some operations.
17666 ///
17667 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17668   switch (Op.getOpcode()) {
17669   default: llvm_unreachable("Should not custom lower this!");
17670   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17671   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17672     return LowerCMP_SWAP(Op, Subtarget, DAG);
17673   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17674   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17675   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17676   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17677   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17678   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17679   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17680   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17681   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17682   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17683   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17684   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17685   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17686   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17687   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17688   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17689   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17690   case ISD::SHL_PARTS:
17691   case ISD::SRA_PARTS:
17692   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17693   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17694   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17695   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17696   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17697   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17698   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17699   case ISD::SIGN_EXTEND_VECTOR_INREG:
17700     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
17701   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17702   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17703   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17704   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17705   case ISD::FABS:
17706   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17707   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17708   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17709   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17710   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17711   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17712   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17713   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17714   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17715   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17716   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17717   case ISD::INTRINSIC_VOID:
17718   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17719   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17720   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17721   case ISD::FRAME_TO_ARGS_OFFSET:
17722                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17723   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17724   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17725   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17726   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17727   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17728   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17729   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17730   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17731   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17732   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17733   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17734   case ISD::UMUL_LOHI:
17735   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17736   case ISD::SRA:
17737   case ISD::SRL:
17738   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17739   case ISD::SADDO:
17740   case ISD::UADDO:
17741   case ISD::SSUBO:
17742   case ISD::USUBO:
17743   case ISD::SMULO:
17744   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17745   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17746   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17747   case ISD::ADDC:
17748   case ISD::ADDE:
17749   case ISD::SUBC:
17750   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17751   case ISD::ADD:                return LowerADD(Op, DAG);
17752   case ISD::SUB:                return LowerSUB(Op, DAG);
17753   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17754   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
17755   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
17756   case ISD::GC_TRANSITION_START:
17757                                 return LowerGC_TRANSITION_START(Op, DAG);
17758   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
17759   }
17760 }
17761
17762 /// ReplaceNodeResults - Replace a node with an illegal result type
17763 /// with a new node built out of custom code.
17764 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17765                                            SmallVectorImpl<SDValue>&Results,
17766                                            SelectionDAG &DAG) const {
17767   SDLoc dl(N);
17768   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17769   switch (N->getOpcode()) {
17770   default:
17771     llvm_unreachable("Do not know how to custom type legalize this operation!");
17772   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17773   case X86ISD::FMINC:
17774   case X86ISD::FMIN:
17775   case X86ISD::FMAXC:
17776   case X86ISD::FMAX: {
17777     EVT VT = N->getValueType(0);
17778     if (VT != MVT::v2f32)
17779       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17780     SDValue UNDEF = DAG.getUNDEF(VT);
17781     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17782                               N->getOperand(0), UNDEF);
17783     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17784                               N->getOperand(1), UNDEF);
17785     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17786     return;
17787   }
17788   case ISD::SIGN_EXTEND_INREG:
17789   case ISD::ADDC:
17790   case ISD::ADDE:
17791   case ISD::SUBC:
17792   case ISD::SUBE:
17793     // We don't want to expand or promote these.
17794     return;
17795   case ISD::SDIV:
17796   case ISD::UDIV:
17797   case ISD::SREM:
17798   case ISD::UREM:
17799   case ISD::SDIVREM:
17800   case ISD::UDIVREM: {
17801     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17802     Results.push_back(V);
17803     return;
17804   }
17805   case ISD::FP_TO_SINT:
17806     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
17807     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17808     if (N->getOperand(0).getValueType() == MVT::f16)
17809       break;
17810     // fallthrough
17811   case ISD::FP_TO_UINT: {
17812     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17813
17814     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17815       return;
17816
17817     std::pair<SDValue,SDValue> Vals =
17818         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17819     SDValue FIST = Vals.first, StackSlot = Vals.second;
17820     if (FIST.getNode()) {
17821       EVT VT = N->getValueType(0);
17822       // Return a load from the stack slot.
17823       if (StackSlot.getNode())
17824         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17825                                       MachinePointerInfo(),
17826                                       false, false, false, 0));
17827       else
17828         Results.push_back(FIST);
17829     }
17830     return;
17831   }
17832   case ISD::UINT_TO_FP: {
17833     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17834     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17835         N->getValueType(0) != MVT::v2f32)
17836       return;
17837     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17838                                  N->getOperand(0));
17839     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17840                                      MVT::f64);
17841     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17842     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17843                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17844     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17845     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17846     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17847     return;
17848   }
17849   case ISD::FP_ROUND: {
17850     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17851         return;
17852     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17853     Results.push_back(V);
17854     return;
17855   }
17856   case ISD::FP_EXTEND: {
17857     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17858     // No other ValueType for FP_EXTEND should reach this point.
17859     assert(N->getValueType(0) == MVT::v2f32 &&
17860            "Do not know how to legalize this Node");
17861     return;
17862   }
17863   case ISD::INTRINSIC_W_CHAIN: {
17864     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17865     switch (IntNo) {
17866     default : llvm_unreachable("Do not know how to custom type "
17867                                "legalize this intrinsic operation!");
17868     case Intrinsic::x86_rdtsc:
17869       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17870                                      Results);
17871     case Intrinsic::x86_rdtscp:
17872       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17873                                      Results);
17874     case Intrinsic::x86_rdpmc:
17875       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17876     }
17877   }
17878   case ISD::READCYCLECOUNTER: {
17879     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17880                                    Results);
17881   }
17882   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17883     EVT T = N->getValueType(0);
17884     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17885     bool Regs64bit = T == MVT::i128;
17886     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17887     SDValue cpInL, cpInH;
17888     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17889                         DAG.getConstant(0, dl, HalfT));
17890     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17891                         DAG.getConstant(1, dl, HalfT));
17892     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17893                              Regs64bit ? X86::RAX : X86::EAX,
17894                              cpInL, SDValue());
17895     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17896                              Regs64bit ? X86::RDX : X86::EDX,
17897                              cpInH, cpInL.getValue(1));
17898     SDValue swapInL, swapInH;
17899     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17900                           DAG.getConstant(0, dl, HalfT));
17901     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17902                           DAG.getConstant(1, dl, HalfT));
17903     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17904                                Regs64bit ? X86::RBX : X86::EBX,
17905                                swapInL, cpInH.getValue(1));
17906     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17907                                Regs64bit ? X86::RCX : X86::ECX,
17908                                swapInH, swapInL.getValue(1));
17909     SDValue Ops[] = { swapInH.getValue(0),
17910                       N->getOperand(1),
17911                       swapInH.getValue(1) };
17912     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17913     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17914     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17915                                   X86ISD::LCMPXCHG8_DAG;
17916     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17917     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17918                                         Regs64bit ? X86::RAX : X86::EAX,
17919                                         HalfT, Result.getValue(1));
17920     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17921                                         Regs64bit ? X86::RDX : X86::EDX,
17922                                         HalfT, cpOutL.getValue(2));
17923     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17924
17925     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17926                                         MVT::i32, cpOutH.getValue(2));
17927     SDValue Success =
17928         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17929                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17930     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17931
17932     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17933     Results.push_back(Success);
17934     Results.push_back(EFLAGS.getValue(1));
17935     return;
17936   }
17937   case ISD::ATOMIC_SWAP:
17938   case ISD::ATOMIC_LOAD_ADD:
17939   case ISD::ATOMIC_LOAD_SUB:
17940   case ISD::ATOMIC_LOAD_AND:
17941   case ISD::ATOMIC_LOAD_OR:
17942   case ISD::ATOMIC_LOAD_XOR:
17943   case ISD::ATOMIC_LOAD_NAND:
17944   case ISD::ATOMIC_LOAD_MIN:
17945   case ISD::ATOMIC_LOAD_MAX:
17946   case ISD::ATOMIC_LOAD_UMIN:
17947   case ISD::ATOMIC_LOAD_UMAX:
17948   case ISD::ATOMIC_LOAD: {
17949     // Delegate to generic TypeLegalization. Situations we can really handle
17950     // should have already been dealt with by AtomicExpandPass.cpp.
17951     break;
17952   }
17953   case ISD::BITCAST: {
17954     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17955     EVT DstVT = N->getValueType(0);
17956     EVT SrcVT = N->getOperand(0)->getValueType(0);
17957
17958     if (SrcVT != MVT::f64 ||
17959         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17960       return;
17961
17962     unsigned NumElts = DstVT.getVectorNumElements();
17963     EVT SVT = DstVT.getVectorElementType();
17964     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17965     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17966                                    MVT::v2f64, N->getOperand(0));
17967     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17968
17969     if (ExperimentalVectorWideningLegalization) {
17970       // If we are legalizing vectors by widening, we already have the desired
17971       // legal vector type, just return it.
17972       Results.push_back(ToVecInt);
17973       return;
17974     }
17975
17976     SmallVector<SDValue, 8> Elts;
17977     for (unsigned i = 0, e = NumElts; i != e; ++i)
17978       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17979                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
17980
17981     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17982   }
17983   }
17984 }
17985
17986 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17987   switch ((X86ISD::NodeType)Opcode) {
17988   case X86ISD::FIRST_NUMBER:       break;
17989   case X86ISD::BSF:                return "X86ISD::BSF";
17990   case X86ISD::BSR:                return "X86ISD::BSR";
17991   case X86ISD::SHLD:               return "X86ISD::SHLD";
17992   case X86ISD::SHRD:               return "X86ISD::SHRD";
17993   case X86ISD::FAND:               return "X86ISD::FAND";
17994   case X86ISD::FANDN:              return "X86ISD::FANDN";
17995   case X86ISD::FOR:                return "X86ISD::FOR";
17996   case X86ISD::FXOR:               return "X86ISD::FXOR";
17997   case X86ISD::FSRL:               return "X86ISD::FSRL";
17998   case X86ISD::FILD:               return "X86ISD::FILD";
17999   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18000   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18001   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18002   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18003   case X86ISD::FLD:                return "X86ISD::FLD";
18004   case X86ISD::FST:                return "X86ISD::FST";
18005   case X86ISD::CALL:               return "X86ISD::CALL";
18006   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18007   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18008   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18009   case X86ISD::BT:                 return "X86ISD::BT";
18010   case X86ISD::CMP:                return "X86ISD::CMP";
18011   case X86ISD::COMI:               return "X86ISD::COMI";
18012   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18013   case X86ISD::CMPM:               return "X86ISD::CMPM";
18014   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18015   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18016   case X86ISD::SETCC:              return "X86ISD::SETCC";
18017   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18018   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18019   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18020   case X86ISD::CMOV:               return "X86ISD::CMOV";
18021   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18022   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18023   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18024   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18025   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18026   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18027   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18028   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
18029   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
18030   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
18031   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
18032   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
18033   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
18034   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
18035   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
18036   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
18037   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
18038   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
18039   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
18040   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
18041   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
18042   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
18043   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
18044   case X86ISD::HADD:               return "X86ISD::HADD";
18045   case X86ISD::HSUB:               return "X86ISD::HSUB";
18046   case X86ISD::FHADD:              return "X86ISD::FHADD";
18047   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
18048   case X86ISD::UMAX:               return "X86ISD::UMAX";
18049   case X86ISD::UMIN:               return "X86ISD::UMIN";
18050   case X86ISD::SMAX:               return "X86ISD::SMAX";
18051   case X86ISD::SMIN:               return "X86ISD::SMIN";
18052   case X86ISD::FMAX:               return "X86ISD::FMAX";
18053   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
18054   case X86ISD::FMIN:               return "X86ISD::FMIN";
18055   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
18056   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18057   case X86ISD::FMINC:              return "X86ISD::FMINC";
18058   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18059   case X86ISD::FRCP:               return "X86ISD::FRCP";
18060   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18061   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18062   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18063   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18064   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18065   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18066   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18067   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18068   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18069   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18070   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18071   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18072   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18073   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18074   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18075   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18076   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18077   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18078   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18079   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18080   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18081   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18082   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18083   case X86ISD::VSHL:               return "X86ISD::VSHL";
18084   case X86ISD::VSRL:               return "X86ISD::VSRL";
18085   case X86ISD::VSRA:               return "X86ISD::VSRA";
18086   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18087   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18088   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18089   case X86ISD::CMPP:               return "X86ISD::CMPP";
18090   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18091   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18092   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18093   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18094   case X86ISD::ADD:                return "X86ISD::ADD";
18095   case X86ISD::SUB:                return "X86ISD::SUB";
18096   case X86ISD::ADC:                return "X86ISD::ADC";
18097   case X86ISD::SBB:                return "X86ISD::SBB";
18098   case X86ISD::SMUL:               return "X86ISD::SMUL";
18099   case X86ISD::UMUL:               return "X86ISD::UMUL";
18100   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18101   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18102   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18103   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18104   case X86ISD::INC:                return "X86ISD::INC";
18105   case X86ISD::DEC:                return "X86ISD::DEC";
18106   case X86ISD::OR:                 return "X86ISD::OR";
18107   case X86ISD::XOR:                return "X86ISD::XOR";
18108   case X86ISD::AND:                return "X86ISD::AND";
18109   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18110   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18111   case X86ISD::PTEST:              return "X86ISD::PTEST";
18112   case X86ISD::TESTP:              return "X86ISD::TESTP";
18113   case X86ISD::TESTM:              return "X86ISD::TESTM";
18114   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18115   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18116   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
18117   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
18118   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
18119   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
18120   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
18121   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
18122   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
18123   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
18124   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
18125   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
18126   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
18127   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
18128   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
18129   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
18130   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
18131   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
18132   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
18133   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
18134   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
18135   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18136   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18137   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
18138   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18139   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
18140   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18141   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18142   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18143   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18144   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18145   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18146   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18147   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18148   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18149   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
18150   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
18151   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
18152   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
18153   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
18154   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
18155   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18156   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18157   case X86ISD::SAHF:               return "X86ISD::SAHF";
18158   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18159   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18160   case X86ISD::FMADD:              return "X86ISD::FMADD";
18161   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18162   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18163   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18164   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18165   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18166   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18167   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18168   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18169   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18170   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18171   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18172   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18173   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18174   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18175   case X86ISD::XTEST:              return "X86ISD::XTEST";
18176   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18177   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18178   case X86ISD::SELECT:             return "X86ISD::SELECT";
18179   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18180   case X86ISD::RCP28:              return "X86ISD::RCP28";
18181   case X86ISD::EXP2:               return "X86ISD::EXP2";
18182   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18183   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18184   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18185   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18186   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18187   case X86ISD::ADDS:               return "X86ISD::ADDS";
18188   case X86ISD::SUBS:               return "X86ISD::SUBS";
18189   }
18190   return nullptr;
18191 }
18192
18193 // isLegalAddressingMode - Return true if the addressing mode represented
18194 // by AM is legal for this target, for a load/store of the specified type.
18195 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18196                                               Type *Ty) const {
18197   // X86 supports extremely general addressing modes.
18198   CodeModel::Model M = getTargetMachine().getCodeModel();
18199   Reloc::Model R = getTargetMachine().getRelocationModel();
18200
18201   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18202   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18203     return false;
18204
18205   if (AM.BaseGV) {
18206     unsigned GVFlags =
18207       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18208
18209     // If a reference to this global requires an extra load, we can't fold it.
18210     if (isGlobalStubReference(GVFlags))
18211       return false;
18212
18213     // If BaseGV requires a register for the PIC base, we cannot also have a
18214     // BaseReg specified.
18215     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18216       return false;
18217
18218     // If lower 4G is not available, then we must use rip-relative addressing.
18219     if ((M != CodeModel::Small || R != Reloc::Static) &&
18220         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18221       return false;
18222   }
18223
18224   switch (AM.Scale) {
18225   case 0:
18226   case 1:
18227   case 2:
18228   case 4:
18229   case 8:
18230     // These scales always work.
18231     break;
18232   case 3:
18233   case 5:
18234   case 9:
18235     // These scales are formed with basereg+scalereg.  Only accept if there is
18236     // no basereg yet.
18237     if (AM.HasBaseReg)
18238       return false;
18239     break;
18240   default:  // Other stuff never works.
18241     return false;
18242   }
18243
18244   return true;
18245 }
18246
18247 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18248   unsigned Bits = Ty->getScalarSizeInBits();
18249
18250   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18251   // particularly cheaper than those without.
18252   if (Bits == 8)
18253     return false;
18254
18255   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18256   // variable shifts just as cheap as scalar ones.
18257   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18258     return false;
18259
18260   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18261   // fully general vector.
18262   return true;
18263 }
18264
18265 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18266   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18267     return false;
18268   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18269   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18270   return NumBits1 > NumBits2;
18271 }
18272
18273 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18274   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18275     return false;
18276
18277   if (!isTypeLegal(EVT::getEVT(Ty1)))
18278     return false;
18279
18280   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18281
18282   // Assuming the caller doesn't have a zeroext or signext return parameter,
18283   // truncation all the way down to i1 is valid.
18284   return true;
18285 }
18286
18287 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18288   return isInt<32>(Imm);
18289 }
18290
18291 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18292   // Can also use sub to handle negated immediates.
18293   return isInt<32>(Imm);
18294 }
18295
18296 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18297   if (!VT1.isInteger() || !VT2.isInteger())
18298     return false;
18299   unsigned NumBits1 = VT1.getSizeInBits();
18300   unsigned NumBits2 = VT2.getSizeInBits();
18301   return NumBits1 > NumBits2;
18302 }
18303
18304 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18305   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18306   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18307 }
18308
18309 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18310   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18311   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18312 }
18313
18314 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18315   EVT VT1 = Val.getValueType();
18316   if (isZExtFree(VT1, VT2))
18317     return true;
18318
18319   if (Val.getOpcode() != ISD::LOAD)
18320     return false;
18321
18322   if (!VT1.isSimple() || !VT1.isInteger() ||
18323       !VT2.isSimple() || !VT2.isInteger())
18324     return false;
18325
18326   switch (VT1.getSimpleVT().SimpleTy) {
18327   default: break;
18328   case MVT::i8:
18329   case MVT::i16:
18330   case MVT::i32:
18331     // X86 has 8, 16, and 32-bit zero-extending loads.
18332     return true;
18333   }
18334
18335   return false;
18336 }
18337
18338 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18339
18340 bool
18341 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18342   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18343     return false;
18344
18345   VT = VT.getScalarType();
18346
18347   if (!VT.isSimple())
18348     return false;
18349
18350   switch (VT.getSimpleVT().SimpleTy) {
18351   case MVT::f32:
18352   case MVT::f64:
18353     return true;
18354   default:
18355     break;
18356   }
18357
18358   return false;
18359 }
18360
18361 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18362   // i16 instructions are longer (0x66 prefix) and potentially slower.
18363   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18364 }
18365
18366 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18367 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18368 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18369 /// are assumed to be legal.
18370 bool
18371 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18372                                       EVT VT) const {
18373   if (!VT.isSimple())
18374     return false;
18375
18376   // Not for i1 vectors
18377   if (VT.getScalarType() == MVT::i1)
18378     return false;
18379
18380   // Very little shuffling can be done for 64-bit vectors right now.
18381   if (VT.getSizeInBits() == 64)
18382     return false;
18383
18384   // We only care that the types being shuffled are legal. The lowering can
18385   // handle any possible shuffle mask that results.
18386   return isTypeLegal(VT.getSimpleVT());
18387 }
18388
18389 bool
18390 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18391                                           EVT VT) const {
18392   // Just delegate to the generic legality, clear masks aren't special.
18393   return isShuffleMaskLegal(Mask, VT);
18394 }
18395
18396 //===----------------------------------------------------------------------===//
18397 //                           X86 Scheduler Hooks
18398 //===----------------------------------------------------------------------===//
18399
18400 /// Utility function to emit xbegin specifying the start of an RTM region.
18401 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18402                                      const TargetInstrInfo *TII) {
18403   DebugLoc DL = MI->getDebugLoc();
18404
18405   const BasicBlock *BB = MBB->getBasicBlock();
18406   MachineFunction::iterator I = MBB;
18407   ++I;
18408
18409   // For the v = xbegin(), we generate
18410   //
18411   // thisMBB:
18412   //  xbegin sinkMBB
18413   //
18414   // mainMBB:
18415   //  eax = -1
18416   //
18417   // sinkMBB:
18418   //  v = eax
18419
18420   MachineBasicBlock *thisMBB = MBB;
18421   MachineFunction *MF = MBB->getParent();
18422   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18423   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18424   MF->insert(I, mainMBB);
18425   MF->insert(I, sinkMBB);
18426
18427   // Transfer the remainder of BB and its successor edges to sinkMBB.
18428   sinkMBB->splice(sinkMBB->begin(), MBB,
18429                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18430   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18431
18432   // thisMBB:
18433   //  xbegin sinkMBB
18434   //  # fallthrough to mainMBB
18435   //  # abortion to sinkMBB
18436   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18437   thisMBB->addSuccessor(mainMBB);
18438   thisMBB->addSuccessor(sinkMBB);
18439
18440   // mainMBB:
18441   //  EAX = -1
18442   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18443   mainMBB->addSuccessor(sinkMBB);
18444
18445   // sinkMBB:
18446   // EAX is live into the sinkMBB
18447   sinkMBB->addLiveIn(X86::EAX);
18448   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18449           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18450     .addReg(X86::EAX);
18451
18452   MI->eraseFromParent();
18453   return sinkMBB;
18454 }
18455
18456 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18457 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18458 // in the .td file.
18459 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18460                                        const TargetInstrInfo *TII) {
18461   unsigned Opc;
18462   switch (MI->getOpcode()) {
18463   default: llvm_unreachable("illegal opcode!");
18464   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18465   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18466   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18467   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18468   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18469   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18470   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18471   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18472   }
18473
18474   DebugLoc dl = MI->getDebugLoc();
18475   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18476
18477   unsigned NumArgs = MI->getNumOperands();
18478   for (unsigned i = 1; i < NumArgs; ++i) {
18479     MachineOperand &Op = MI->getOperand(i);
18480     if (!(Op.isReg() && Op.isImplicit()))
18481       MIB.addOperand(Op);
18482   }
18483   if (MI->hasOneMemOperand())
18484     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18485
18486   BuildMI(*BB, MI, dl,
18487     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18488     .addReg(X86::XMM0);
18489
18490   MI->eraseFromParent();
18491   return BB;
18492 }
18493
18494 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18495 // defs in an instruction pattern
18496 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18497                                        const TargetInstrInfo *TII) {
18498   unsigned Opc;
18499   switch (MI->getOpcode()) {
18500   default: llvm_unreachable("illegal opcode!");
18501   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18502   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18503   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18504   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18505   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18506   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18507   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18508   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18509   }
18510
18511   DebugLoc dl = MI->getDebugLoc();
18512   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18513
18514   unsigned NumArgs = MI->getNumOperands(); // remove the results
18515   for (unsigned i = 1; i < NumArgs; ++i) {
18516     MachineOperand &Op = MI->getOperand(i);
18517     if (!(Op.isReg() && Op.isImplicit()))
18518       MIB.addOperand(Op);
18519   }
18520   if (MI->hasOneMemOperand())
18521     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18522
18523   BuildMI(*BB, MI, dl,
18524     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18525     .addReg(X86::ECX);
18526
18527   MI->eraseFromParent();
18528   return BB;
18529 }
18530
18531 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18532                                       const X86Subtarget *Subtarget) {
18533   DebugLoc dl = MI->getDebugLoc();
18534   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18535   // Address into RAX/EAX, other two args into ECX, EDX.
18536   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18537   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18538   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18539   for (int i = 0; i < X86::AddrNumOperands; ++i)
18540     MIB.addOperand(MI->getOperand(i));
18541
18542   unsigned ValOps = X86::AddrNumOperands;
18543   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18544     .addReg(MI->getOperand(ValOps).getReg());
18545   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18546     .addReg(MI->getOperand(ValOps+1).getReg());
18547
18548   // The instruction doesn't actually take any operands though.
18549   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18550
18551   MI->eraseFromParent(); // The pseudo is gone now.
18552   return BB;
18553 }
18554
18555 MachineBasicBlock *
18556 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18557                                                  MachineBasicBlock *MBB) const {
18558   // Emit va_arg instruction on X86-64.
18559
18560   // Operands to this pseudo-instruction:
18561   // 0  ) Output        : destination address (reg)
18562   // 1-5) Input         : va_list address (addr, i64mem)
18563   // 6  ) ArgSize       : Size (in bytes) of vararg type
18564   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18565   // 8  ) Align         : Alignment of type
18566   // 9  ) EFLAGS (implicit-def)
18567
18568   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18569   static_assert(X86::AddrNumOperands == 5,
18570                 "VAARG_64 assumes 5 address operands");
18571
18572   unsigned DestReg = MI->getOperand(0).getReg();
18573   MachineOperand &Base = MI->getOperand(1);
18574   MachineOperand &Scale = MI->getOperand(2);
18575   MachineOperand &Index = MI->getOperand(3);
18576   MachineOperand &Disp = MI->getOperand(4);
18577   MachineOperand &Segment = MI->getOperand(5);
18578   unsigned ArgSize = MI->getOperand(6).getImm();
18579   unsigned ArgMode = MI->getOperand(7).getImm();
18580   unsigned Align = MI->getOperand(8).getImm();
18581
18582   // Memory Reference
18583   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18584   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18585   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18586
18587   // Machine Information
18588   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18589   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18590   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18591   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18592   DebugLoc DL = MI->getDebugLoc();
18593
18594   // struct va_list {
18595   //   i32   gp_offset
18596   //   i32   fp_offset
18597   //   i64   overflow_area (address)
18598   //   i64   reg_save_area (address)
18599   // }
18600   // sizeof(va_list) = 24
18601   // alignment(va_list) = 8
18602
18603   unsigned TotalNumIntRegs = 6;
18604   unsigned TotalNumXMMRegs = 8;
18605   bool UseGPOffset = (ArgMode == 1);
18606   bool UseFPOffset = (ArgMode == 2);
18607   unsigned MaxOffset = TotalNumIntRegs * 8 +
18608                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18609
18610   /* Align ArgSize to a multiple of 8 */
18611   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18612   bool NeedsAlign = (Align > 8);
18613
18614   MachineBasicBlock *thisMBB = MBB;
18615   MachineBasicBlock *overflowMBB;
18616   MachineBasicBlock *offsetMBB;
18617   MachineBasicBlock *endMBB;
18618
18619   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18620   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18621   unsigned OffsetReg = 0;
18622
18623   if (!UseGPOffset && !UseFPOffset) {
18624     // If we only pull from the overflow region, we don't create a branch.
18625     // We don't need to alter control flow.
18626     OffsetDestReg = 0; // unused
18627     OverflowDestReg = DestReg;
18628
18629     offsetMBB = nullptr;
18630     overflowMBB = thisMBB;
18631     endMBB = thisMBB;
18632   } else {
18633     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18634     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18635     // If not, pull from overflow_area. (branch to overflowMBB)
18636     //
18637     //       thisMBB
18638     //         |     .
18639     //         |        .
18640     //     offsetMBB   overflowMBB
18641     //         |        .
18642     //         |     .
18643     //        endMBB
18644
18645     // Registers for the PHI in endMBB
18646     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18647     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18648
18649     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18650     MachineFunction *MF = MBB->getParent();
18651     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18652     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18653     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18654
18655     MachineFunction::iterator MBBIter = MBB;
18656     ++MBBIter;
18657
18658     // Insert the new basic blocks
18659     MF->insert(MBBIter, offsetMBB);
18660     MF->insert(MBBIter, overflowMBB);
18661     MF->insert(MBBIter, endMBB);
18662
18663     // Transfer the remainder of MBB and its successor edges to endMBB.
18664     endMBB->splice(endMBB->begin(), thisMBB,
18665                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18666     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18667
18668     // Make offsetMBB and overflowMBB successors of thisMBB
18669     thisMBB->addSuccessor(offsetMBB);
18670     thisMBB->addSuccessor(overflowMBB);
18671
18672     // endMBB is a successor of both offsetMBB and overflowMBB
18673     offsetMBB->addSuccessor(endMBB);
18674     overflowMBB->addSuccessor(endMBB);
18675
18676     // Load the offset value into a register
18677     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18678     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18679       .addOperand(Base)
18680       .addOperand(Scale)
18681       .addOperand(Index)
18682       .addDisp(Disp, UseFPOffset ? 4 : 0)
18683       .addOperand(Segment)
18684       .setMemRefs(MMOBegin, MMOEnd);
18685
18686     // Check if there is enough room left to pull this argument.
18687     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18688       .addReg(OffsetReg)
18689       .addImm(MaxOffset + 8 - ArgSizeA8);
18690
18691     // Branch to "overflowMBB" if offset >= max
18692     // Fall through to "offsetMBB" otherwise
18693     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18694       .addMBB(overflowMBB);
18695   }
18696
18697   // In offsetMBB, emit code to use the reg_save_area.
18698   if (offsetMBB) {
18699     assert(OffsetReg != 0);
18700
18701     // Read the reg_save_area address.
18702     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18703     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18704       .addOperand(Base)
18705       .addOperand(Scale)
18706       .addOperand(Index)
18707       .addDisp(Disp, 16)
18708       .addOperand(Segment)
18709       .setMemRefs(MMOBegin, MMOEnd);
18710
18711     // Zero-extend the offset
18712     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18713       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18714         .addImm(0)
18715         .addReg(OffsetReg)
18716         .addImm(X86::sub_32bit);
18717
18718     // Add the offset to the reg_save_area to get the final address.
18719     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18720       .addReg(OffsetReg64)
18721       .addReg(RegSaveReg);
18722
18723     // Compute the offset for the next argument
18724     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18725     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18726       .addReg(OffsetReg)
18727       .addImm(UseFPOffset ? 16 : 8);
18728
18729     // Store it back into the va_list.
18730     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18731       .addOperand(Base)
18732       .addOperand(Scale)
18733       .addOperand(Index)
18734       .addDisp(Disp, UseFPOffset ? 4 : 0)
18735       .addOperand(Segment)
18736       .addReg(NextOffsetReg)
18737       .setMemRefs(MMOBegin, MMOEnd);
18738
18739     // Jump to endMBB
18740     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18741       .addMBB(endMBB);
18742   }
18743
18744   //
18745   // Emit code to use overflow area
18746   //
18747
18748   // Load the overflow_area address into a register.
18749   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18750   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18751     .addOperand(Base)
18752     .addOperand(Scale)
18753     .addOperand(Index)
18754     .addDisp(Disp, 8)
18755     .addOperand(Segment)
18756     .setMemRefs(MMOBegin, MMOEnd);
18757
18758   // If we need to align it, do so. Otherwise, just copy the address
18759   // to OverflowDestReg.
18760   if (NeedsAlign) {
18761     // Align the overflow address
18762     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18763     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18764
18765     // aligned_addr = (addr + (align-1)) & ~(align-1)
18766     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18767       .addReg(OverflowAddrReg)
18768       .addImm(Align-1);
18769
18770     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18771       .addReg(TmpReg)
18772       .addImm(~(uint64_t)(Align-1));
18773   } else {
18774     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18775       .addReg(OverflowAddrReg);
18776   }
18777
18778   // Compute the next overflow address after this argument.
18779   // (the overflow address should be kept 8-byte aligned)
18780   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18781   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18782     .addReg(OverflowDestReg)
18783     .addImm(ArgSizeA8);
18784
18785   // Store the new overflow address.
18786   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18787     .addOperand(Base)
18788     .addOperand(Scale)
18789     .addOperand(Index)
18790     .addDisp(Disp, 8)
18791     .addOperand(Segment)
18792     .addReg(NextAddrReg)
18793     .setMemRefs(MMOBegin, MMOEnd);
18794
18795   // If we branched, emit the PHI to the front of endMBB.
18796   if (offsetMBB) {
18797     BuildMI(*endMBB, endMBB->begin(), DL,
18798             TII->get(X86::PHI), DestReg)
18799       .addReg(OffsetDestReg).addMBB(offsetMBB)
18800       .addReg(OverflowDestReg).addMBB(overflowMBB);
18801   }
18802
18803   // Erase the pseudo instruction
18804   MI->eraseFromParent();
18805
18806   return endMBB;
18807 }
18808
18809 MachineBasicBlock *
18810 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18811                                                  MachineInstr *MI,
18812                                                  MachineBasicBlock *MBB) const {
18813   // Emit code to save XMM registers to the stack. The ABI says that the
18814   // number of registers to save is given in %al, so it's theoretically
18815   // possible to do an indirect jump trick to avoid saving all of them,
18816   // however this code takes a simpler approach and just executes all
18817   // of the stores if %al is non-zero. It's less code, and it's probably
18818   // easier on the hardware branch predictor, and stores aren't all that
18819   // expensive anyway.
18820
18821   // Create the new basic blocks. One block contains all the XMM stores,
18822   // and one block is the final destination regardless of whether any
18823   // stores were performed.
18824   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18825   MachineFunction *F = MBB->getParent();
18826   MachineFunction::iterator MBBIter = MBB;
18827   ++MBBIter;
18828   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18829   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18830   F->insert(MBBIter, XMMSaveMBB);
18831   F->insert(MBBIter, EndMBB);
18832
18833   // Transfer the remainder of MBB and its successor edges to EndMBB.
18834   EndMBB->splice(EndMBB->begin(), MBB,
18835                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18836   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18837
18838   // The original block will now fall through to the XMM save block.
18839   MBB->addSuccessor(XMMSaveMBB);
18840   // The XMMSaveMBB will fall through to the end block.
18841   XMMSaveMBB->addSuccessor(EndMBB);
18842
18843   // Now add the instructions.
18844   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18845   DebugLoc DL = MI->getDebugLoc();
18846
18847   unsigned CountReg = MI->getOperand(0).getReg();
18848   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18849   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18850
18851   if (!Subtarget->isTargetWin64()) {
18852     // If %al is 0, branch around the XMM save block.
18853     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18854     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18855     MBB->addSuccessor(EndMBB);
18856   }
18857
18858   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18859   // that was just emitted, but clearly shouldn't be "saved".
18860   assert((MI->getNumOperands() <= 3 ||
18861           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18862           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18863          && "Expected last argument to be EFLAGS");
18864   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18865   // In the XMM save block, save all the XMM argument registers.
18866   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18867     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18868     MachineMemOperand *MMO =
18869       F->getMachineMemOperand(
18870           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18871         MachineMemOperand::MOStore,
18872         /*Size=*/16, /*Align=*/16);
18873     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18874       .addFrameIndex(RegSaveFrameIndex)
18875       .addImm(/*Scale=*/1)
18876       .addReg(/*IndexReg=*/0)
18877       .addImm(/*Disp=*/Offset)
18878       .addReg(/*Segment=*/0)
18879       .addReg(MI->getOperand(i).getReg())
18880       .addMemOperand(MMO);
18881   }
18882
18883   MI->eraseFromParent();   // The pseudo instruction is gone now.
18884
18885   return EndMBB;
18886 }
18887
18888 // The EFLAGS operand of SelectItr might be missing a kill marker
18889 // because there were multiple uses of EFLAGS, and ISel didn't know
18890 // which to mark. Figure out whether SelectItr should have had a
18891 // kill marker, and set it if it should. Returns the correct kill
18892 // marker value.
18893 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18894                                      MachineBasicBlock* BB,
18895                                      const TargetRegisterInfo* TRI) {
18896   // Scan forward through BB for a use/def of EFLAGS.
18897   MachineBasicBlock::iterator miI(std::next(SelectItr));
18898   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18899     const MachineInstr& mi = *miI;
18900     if (mi.readsRegister(X86::EFLAGS))
18901       return false;
18902     if (mi.definesRegister(X86::EFLAGS))
18903       break; // Should have kill-flag - update below.
18904   }
18905
18906   // If we hit the end of the block, check whether EFLAGS is live into a
18907   // successor.
18908   if (miI == BB->end()) {
18909     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18910                                           sEnd = BB->succ_end();
18911          sItr != sEnd; ++sItr) {
18912       MachineBasicBlock* succ = *sItr;
18913       if (succ->isLiveIn(X86::EFLAGS))
18914         return false;
18915     }
18916   }
18917
18918   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18919   // out. SelectMI should have a kill flag on EFLAGS.
18920   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18921   return true;
18922 }
18923
18924 MachineBasicBlock *
18925 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18926                                      MachineBasicBlock *BB) const {
18927   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18928   DebugLoc DL = MI->getDebugLoc();
18929
18930   // To "insert" a SELECT_CC instruction, we actually have to insert the
18931   // diamond control-flow pattern.  The incoming instruction knows the
18932   // destination vreg to set, the condition code register to branch on, the
18933   // true/false values to select between, and a branch opcode to use.
18934   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18935   MachineFunction::iterator It = BB;
18936   ++It;
18937
18938   //  thisMBB:
18939   //  ...
18940   //   TrueVal = ...
18941   //   cmpTY ccX, r1, r2
18942   //   bCC copy1MBB
18943   //   fallthrough --> copy0MBB
18944   MachineBasicBlock *thisMBB = BB;
18945   MachineFunction *F = BB->getParent();
18946
18947   // We also lower double CMOVs:
18948   //   (CMOV (CMOV F, T, cc1), T, cc2)
18949   // to two successives branches.  For that, we look for another CMOV as the
18950   // following instruction.
18951   //
18952   // Without this, we would add a PHI between the two jumps, which ends up
18953   // creating a few copies all around. For instance, for
18954   //
18955   //    (sitofp (zext (fcmp une)))
18956   //
18957   // we would generate:
18958   //
18959   //         ucomiss %xmm1, %xmm0
18960   //         movss  <1.0f>, %xmm0
18961   //         movaps  %xmm0, %xmm1
18962   //         jne     .LBB5_2
18963   //         xorps   %xmm1, %xmm1
18964   // .LBB5_2:
18965   //         jp      .LBB5_4
18966   //         movaps  %xmm1, %xmm0
18967   // .LBB5_4:
18968   //         retq
18969   //
18970   // because this custom-inserter would have generated:
18971   //
18972   //   A
18973   //   | \
18974   //   |  B
18975   //   | /
18976   //   C
18977   //   | \
18978   //   |  D
18979   //   | /
18980   //   E
18981   //
18982   // A: X = ...; Y = ...
18983   // B: empty
18984   // C: Z = PHI [X, A], [Y, B]
18985   // D: empty
18986   // E: PHI [X, C], [Z, D]
18987   //
18988   // If we lower both CMOVs in a single step, we can instead generate:
18989   //
18990   //   A
18991   //   | \
18992   //   |  C
18993   //   | /|
18994   //   |/ |
18995   //   |  |
18996   //   |  D
18997   //   | /
18998   //   E
18999   //
19000   // A: X = ...; Y = ...
19001   // D: empty
19002   // E: PHI [X, A], [X, C], [Y, D]
19003   //
19004   // Which, in our sitofp/fcmp example, gives us something like:
19005   //
19006   //         ucomiss %xmm1, %xmm0
19007   //         movss  <1.0f>, %xmm0
19008   //         jne     .LBB5_4
19009   //         jp      .LBB5_4
19010   //         xorps   %xmm0, %xmm0
19011   // .LBB5_4:
19012   //         retq
19013   //
19014   MachineInstr *NextCMOV = nullptr;
19015   MachineBasicBlock::iterator NextMIIt =
19016       std::next(MachineBasicBlock::iterator(MI));
19017   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19018       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19019       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19020     NextCMOV = &*NextMIIt;
19021
19022   MachineBasicBlock *jcc1MBB = nullptr;
19023
19024   // If we have a double CMOV, we lower it to two successive branches to
19025   // the same block.  EFLAGS is used by both, so mark it as live in the second.
19026   if (NextCMOV) {
19027     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19028     F->insert(It, jcc1MBB);
19029     jcc1MBB->addLiveIn(X86::EFLAGS);
19030   }
19031
19032   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19033   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19034   F->insert(It, copy0MBB);
19035   F->insert(It, sinkMBB);
19036
19037   // If the EFLAGS register isn't dead in the terminator, then claim that it's
19038   // live into the sink and copy blocks.
19039   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19040
19041   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19042   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19043       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19044     copy0MBB->addLiveIn(X86::EFLAGS);
19045     sinkMBB->addLiveIn(X86::EFLAGS);
19046   }
19047
19048   // Transfer the remainder of BB and its successor edges to sinkMBB.
19049   sinkMBB->splice(sinkMBB->begin(), BB,
19050                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
19051   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19052
19053   // Add the true and fallthrough blocks as its successors.
19054   if (NextCMOV) {
19055     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19056     BB->addSuccessor(jcc1MBB);
19057
19058     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19059     // jump to the sinkMBB.
19060     jcc1MBB->addSuccessor(copy0MBB);
19061     jcc1MBB->addSuccessor(sinkMBB);
19062   } else {
19063     BB->addSuccessor(copy0MBB);
19064   }
19065
19066   // The true block target of the first (or only) branch is always sinkMBB.
19067   BB->addSuccessor(sinkMBB);
19068
19069   // Create the conditional branch instruction.
19070   unsigned Opc =
19071     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19072   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19073
19074   if (NextCMOV) {
19075     unsigned Opc2 = X86::GetCondBranchFromCond(
19076         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19077     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19078   }
19079
19080   //  copy0MBB:
19081   //   %FalseValue = ...
19082   //   # fallthrough to sinkMBB
19083   copy0MBB->addSuccessor(sinkMBB);
19084
19085   //  sinkMBB:
19086   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19087   //  ...
19088   MachineInstrBuilder MIB =
19089       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19090               MI->getOperand(0).getReg())
19091           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19092           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19093
19094   // If we have a double CMOV, the second Jcc provides the same incoming
19095   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19096   if (NextCMOV) {
19097     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19098     // Copy the PHI result to the register defined by the second CMOV.
19099     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19100             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19101         .addReg(MI->getOperand(0).getReg());
19102     NextCMOV->eraseFromParent();
19103   }
19104
19105   MI->eraseFromParent();   // The pseudo instruction is gone now.
19106   return sinkMBB;
19107 }
19108
19109 MachineBasicBlock *
19110 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19111                                         MachineBasicBlock *BB) const {
19112   MachineFunction *MF = BB->getParent();
19113   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19114   DebugLoc DL = MI->getDebugLoc();
19115   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19116
19117   assert(MF->shouldSplitStack());
19118
19119   const bool Is64Bit = Subtarget->is64Bit();
19120   const bool IsLP64 = Subtarget->isTarget64BitLP64();
19121
19122   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19123   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19124
19125   // BB:
19126   //  ... [Till the alloca]
19127   // If stacklet is not large enough, jump to mallocMBB
19128   //
19129   // bumpMBB:
19130   //  Allocate by subtracting from RSP
19131   //  Jump to continueMBB
19132   //
19133   // mallocMBB:
19134   //  Allocate by call to runtime
19135   //
19136   // continueMBB:
19137   //  ...
19138   //  [rest of original BB]
19139   //
19140
19141   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19142   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19143   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19144
19145   MachineRegisterInfo &MRI = MF->getRegInfo();
19146   const TargetRegisterClass *AddrRegClass =
19147     getRegClassFor(getPointerTy());
19148
19149   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19150     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19151     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19152     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19153     sizeVReg = MI->getOperand(1).getReg(),
19154     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19155
19156   MachineFunction::iterator MBBIter = BB;
19157   ++MBBIter;
19158
19159   MF->insert(MBBIter, bumpMBB);
19160   MF->insert(MBBIter, mallocMBB);
19161   MF->insert(MBBIter, continueMBB);
19162
19163   continueMBB->splice(continueMBB->begin(), BB,
19164                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19165   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19166
19167   // Add code to the main basic block to check if the stack limit has been hit,
19168   // and if so, jump to mallocMBB otherwise to bumpMBB.
19169   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19170   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19171     .addReg(tmpSPVReg).addReg(sizeVReg);
19172   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19173     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19174     .addReg(SPLimitVReg);
19175   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19176
19177   // bumpMBB simply decreases the stack pointer, since we know the current
19178   // stacklet has enough space.
19179   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19180     .addReg(SPLimitVReg);
19181   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19182     .addReg(SPLimitVReg);
19183   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19184
19185   // Calls into a routine in libgcc to allocate more space from the heap.
19186   const uint32_t *RegMask =
19187       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19188   if (IsLP64) {
19189     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19190       .addReg(sizeVReg);
19191     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19192       .addExternalSymbol("__morestack_allocate_stack_space")
19193       .addRegMask(RegMask)
19194       .addReg(X86::RDI, RegState::Implicit)
19195       .addReg(X86::RAX, RegState::ImplicitDefine);
19196   } else if (Is64Bit) {
19197     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19198       .addReg(sizeVReg);
19199     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19200       .addExternalSymbol("__morestack_allocate_stack_space")
19201       .addRegMask(RegMask)
19202       .addReg(X86::EDI, RegState::Implicit)
19203       .addReg(X86::EAX, RegState::ImplicitDefine);
19204   } else {
19205     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19206       .addImm(12);
19207     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19208     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19209       .addExternalSymbol("__morestack_allocate_stack_space")
19210       .addRegMask(RegMask)
19211       .addReg(X86::EAX, RegState::ImplicitDefine);
19212   }
19213
19214   if (!Is64Bit)
19215     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19216       .addImm(16);
19217
19218   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19219     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19220   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19221
19222   // Set up the CFG correctly.
19223   BB->addSuccessor(bumpMBB);
19224   BB->addSuccessor(mallocMBB);
19225   mallocMBB->addSuccessor(continueMBB);
19226   bumpMBB->addSuccessor(continueMBB);
19227
19228   // Take care of the PHI nodes.
19229   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19230           MI->getOperand(0).getReg())
19231     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19232     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19233
19234   // Delete the original pseudo instruction.
19235   MI->eraseFromParent();
19236
19237   // And we're done.
19238   return continueMBB;
19239 }
19240
19241 MachineBasicBlock *
19242 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19243                                         MachineBasicBlock *BB) const {
19244   DebugLoc DL = MI->getDebugLoc();
19245
19246   assert(!Subtarget->isTargetMachO());
19247
19248   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19249
19250   MI->eraseFromParent();   // The pseudo instruction is gone now.
19251   return BB;
19252 }
19253
19254 MachineBasicBlock *
19255 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19256                                       MachineBasicBlock *BB) const {
19257   // This is pretty easy.  We're taking the value that we received from
19258   // our load from the relocation, sticking it in either RDI (x86-64)
19259   // or EAX and doing an indirect call.  The return value will then
19260   // be in the normal return register.
19261   MachineFunction *F = BB->getParent();
19262   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19263   DebugLoc DL = MI->getDebugLoc();
19264
19265   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19266   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19267
19268   // Get a register mask for the lowered call.
19269   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19270   // proper register mask.
19271   const uint32_t *RegMask =
19272       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19273   if (Subtarget->is64Bit()) {
19274     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19275                                       TII->get(X86::MOV64rm), X86::RDI)
19276     .addReg(X86::RIP)
19277     .addImm(0).addReg(0)
19278     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19279                       MI->getOperand(3).getTargetFlags())
19280     .addReg(0);
19281     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19282     addDirectMem(MIB, X86::RDI);
19283     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19284   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19285     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19286                                       TII->get(X86::MOV32rm), X86::EAX)
19287     .addReg(0)
19288     .addImm(0).addReg(0)
19289     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19290                       MI->getOperand(3).getTargetFlags())
19291     .addReg(0);
19292     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19293     addDirectMem(MIB, X86::EAX);
19294     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19295   } else {
19296     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19297                                       TII->get(X86::MOV32rm), X86::EAX)
19298     .addReg(TII->getGlobalBaseReg(F))
19299     .addImm(0).addReg(0)
19300     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19301                       MI->getOperand(3).getTargetFlags())
19302     .addReg(0);
19303     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19304     addDirectMem(MIB, X86::EAX);
19305     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19306   }
19307
19308   MI->eraseFromParent(); // The pseudo instruction is gone now.
19309   return BB;
19310 }
19311
19312 MachineBasicBlock *
19313 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19314                                     MachineBasicBlock *MBB) const {
19315   DebugLoc DL = MI->getDebugLoc();
19316   MachineFunction *MF = MBB->getParent();
19317   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19318   MachineRegisterInfo &MRI = MF->getRegInfo();
19319
19320   const BasicBlock *BB = MBB->getBasicBlock();
19321   MachineFunction::iterator I = MBB;
19322   ++I;
19323
19324   // Memory Reference
19325   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19326   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19327
19328   unsigned DstReg;
19329   unsigned MemOpndSlot = 0;
19330
19331   unsigned CurOp = 0;
19332
19333   DstReg = MI->getOperand(CurOp++).getReg();
19334   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19335   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19336   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19337   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19338
19339   MemOpndSlot = CurOp;
19340
19341   MVT PVT = getPointerTy();
19342   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19343          "Invalid Pointer Size!");
19344
19345   // For v = setjmp(buf), we generate
19346   //
19347   // thisMBB:
19348   //  buf[LabelOffset] = restoreMBB
19349   //  SjLjSetup restoreMBB
19350   //
19351   // mainMBB:
19352   //  v_main = 0
19353   //
19354   // sinkMBB:
19355   //  v = phi(main, restore)
19356   //
19357   // restoreMBB:
19358   //  if base pointer being used, load it from frame
19359   //  v_restore = 1
19360
19361   MachineBasicBlock *thisMBB = MBB;
19362   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19363   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19364   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19365   MF->insert(I, mainMBB);
19366   MF->insert(I, sinkMBB);
19367   MF->push_back(restoreMBB);
19368
19369   MachineInstrBuilder MIB;
19370
19371   // Transfer the remainder of BB and its successor edges to sinkMBB.
19372   sinkMBB->splice(sinkMBB->begin(), MBB,
19373                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19374   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19375
19376   // thisMBB:
19377   unsigned PtrStoreOpc = 0;
19378   unsigned LabelReg = 0;
19379   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19380   Reloc::Model RM = MF->getTarget().getRelocationModel();
19381   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19382                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19383
19384   // Prepare IP either in reg or imm.
19385   if (!UseImmLabel) {
19386     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19387     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19388     LabelReg = MRI.createVirtualRegister(PtrRC);
19389     if (Subtarget->is64Bit()) {
19390       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19391               .addReg(X86::RIP)
19392               .addImm(0)
19393               .addReg(0)
19394               .addMBB(restoreMBB)
19395               .addReg(0);
19396     } else {
19397       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19398       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19399               .addReg(XII->getGlobalBaseReg(MF))
19400               .addImm(0)
19401               .addReg(0)
19402               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19403               .addReg(0);
19404     }
19405   } else
19406     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19407   // Store IP
19408   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19409   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19410     if (i == X86::AddrDisp)
19411       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19412     else
19413       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19414   }
19415   if (!UseImmLabel)
19416     MIB.addReg(LabelReg);
19417   else
19418     MIB.addMBB(restoreMBB);
19419   MIB.setMemRefs(MMOBegin, MMOEnd);
19420   // Setup
19421   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19422           .addMBB(restoreMBB);
19423
19424   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19425   MIB.addRegMask(RegInfo->getNoPreservedMask());
19426   thisMBB->addSuccessor(mainMBB);
19427   thisMBB->addSuccessor(restoreMBB);
19428
19429   // mainMBB:
19430   //  EAX = 0
19431   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19432   mainMBB->addSuccessor(sinkMBB);
19433
19434   // sinkMBB:
19435   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19436           TII->get(X86::PHI), DstReg)
19437     .addReg(mainDstReg).addMBB(mainMBB)
19438     .addReg(restoreDstReg).addMBB(restoreMBB);
19439
19440   // restoreMBB:
19441   if (RegInfo->hasBasePointer(*MF)) {
19442     const bool Uses64BitFramePtr =
19443         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19444     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19445     X86FI->setRestoreBasePointer(MF);
19446     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19447     unsigned BasePtr = RegInfo->getBaseRegister();
19448     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19449     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19450                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19451       .setMIFlag(MachineInstr::FrameSetup);
19452   }
19453   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19454   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19455   restoreMBB->addSuccessor(sinkMBB);
19456
19457   MI->eraseFromParent();
19458   return sinkMBB;
19459 }
19460
19461 MachineBasicBlock *
19462 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19463                                      MachineBasicBlock *MBB) const {
19464   DebugLoc DL = MI->getDebugLoc();
19465   MachineFunction *MF = MBB->getParent();
19466   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19467   MachineRegisterInfo &MRI = MF->getRegInfo();
19468
19469   // Memory Reference
19470   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19471   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19472
19473   MVT PVT = getPointerTy();
19474   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19475          "Invalid Pointer Size!");
19476
19477   const TargetRegisterClass *RC =
19478     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19479   unsigned Tmp = MRI.createVirtualRegister(RC);
19480   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19481   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19482   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19483   unsigned SP = RegInfo->getStackRegister();
19484
19485   MachineInstrBuilder MIB;
19486
19487   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19488   const int64_t SPOffset = 2 * PVT.getStoreSize();
19489
19490   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19491   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19492
19493   // Reload FP
19494   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19495   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19496     MIB.addOperand(MI->getOperand(i));
19497   MIB.setMemRefs(MMOBegin, MMOEnd);
19498   // Reload IP
19499   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19500   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19501     if (i == X86::AddrDisp)
19502       MIB.addDisp(MI->getOperand(i), LabelOffset);
19503     else
19504       MIB.addOperand(MI->getOperand(i));
19505   }
19506   MIB.setMemRefs(MMOBegin, MMOEnd);
19507   // Reload SP
19508   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19509   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19510     if (i == X86::AddrDisp)
19511       MIB.addDisp(MI->getOperand(i), SPOffset);
19512     else
19513       MIB.addOperand(MI->getOperand(i));
19514   }
19515   MIB.setMemRefs(MMOBegin, MMOEnd);
19516   // Jump
19517   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19518
19519   MI->eraseFromParent();
19520   return MBB;
19521 }
19522
19523 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19524 // accumulator loops. Writing back to the accumulator allows the coalescer
19525 // to remove extra copies in the loop.
19526 MachineBasicBlock *
19527 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19528                                  MachineBasicBlock *MBB) const {
19529   MachineOperand &AddendOp = MI->getOperand(3);
19530
19531   // Bail out early if the addend isn't a register - we can't switch these.
19532   if (!AddendOp.isReg())
19533     return MBB;
19534
19535   MachineFunction &MF = *MBB->getParent();
19536   MachineRegisterInfo &MRI = MF.getRegInfo();
19537
19538   // Check whether the addend is defined by a PHI:
19539   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19540   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19541   if (!AddendDef.isPHI())
19542     return MBB;
19543
19544   // Look for the following pattern:
19545   // loop:
19546   //   %addend = phi [%entry, 0], [%loop, %result]
19547   //   ...
19548   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19549
19550   // Replace with:
19551   //   loop:
19552   //   %addend = phi [%entry, 0], [%loop, %result]
19553   //   ...
19554   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19555
19556   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19557     assert(AddendDef.getOperand(i).isReg());
19558     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19559     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19560     if (&PHISrcInst == MI) {
19561       // Found a matching instruction.
19562       unsigned NewFMAOpc = 0;
19563       switch (MI->getOpcode()) {
19564         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19565         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19566         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19567         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19568         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19569         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19570         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19571         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19572         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19573         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19574         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19575         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19576         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19577         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19578         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19579         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19580         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19581         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19582         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19583         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19584
19585         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19586         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19587         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19588         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19589         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19590         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19591         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19592         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19593         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19594         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19595         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19596         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19597         default: llvm_unreachable("Unrecognized FMA variant.");
19598       }
19599
19600       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19601       MachineInstrBuilder MIB =
19602         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19603         .addOperand(MI->getOperand(0))
19604         .addOperand(MI->getOperand(3))
19605         .addOperand(MI->getOperand(2))
19606         .addOperand(MI->getOperand(1));
19607       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19608       MI->eraseFromParent();
19609     }
19610   }
19611
19612   return MBB;
19613 }
19614
19615 MachineBasicBlock *
19616 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19617                                                MachineBasicBlock *BB) const {
19618   switch (MI->getOpcode()) {
19619   default: llvm_unreachable("Unexpected instr type to insert");
19620   case X86::TAILJMPd64:
19621   case X86::TAILJMPr64:
19622   case X86::TAILJMPm64:
19623   case X86::TAILJMPd64_REX:
19624   case X86::TAILJMPr64_REX:
19625   case X86::TAILJMPm64_REX:
19626     llvm_unreachable("TAILJMP64 would not be touched here.");
19627   case X86::TCRETURNdi64:
19628   case X86::TCRETURNri64:
19629   case X86::TCRETURNmi64:
19630     return BB;
19631   case X86::WIN_ALLOCA:
19632     return EmitLoweredWinAlloca(MI, BB);
19633   case X86::SEG_ALLOCA_32:
19634   case X86::SEG_ALLOCA_64:
19635     return EmitLoweredSegAlloca(MI, BB);
19636   case X86::TLSCall_32:
19637   case X86::TLSCall_64:
19638     return EmitLoweredTLSCall(MI, BB);
19639   case X86::CMOV_GR8:
19640   case X86::CMOV_FR32:
19641   case X86::CMOV_FR64:
19642   case X86::CMOV_V4F32:
19643   case X86::CMOV_V2F64:
19644   case X86::CMOV_V2I64:
19645   case X86::CMOV_V8F32:
19646   case X86::CMOV_V4F64:
19647   case X86::CMOV_V4I64:
19648   case X86::CMOV_V16F32:
19649   case X86::CMOV_V8F64:
19650   case X86::CMOV_V8I64:
19651   case X86::CMOV_GR16:
19652   case X86::CMOV_GR32:
19653   case X86::CMOV_RFP32:
19654   case X86::CMOV_RFP64:
19655   case X86::CMOV_RFP80:
19656   case X86::CMOV_V8I1:
19657   case X86::CMOV_V16I1:
19658   case X86::CMOV_V32I1:
19659   case X86::CMOV_V64I1:
19660     return EmitLoweredSelect(MI, BB);
19661
19662   case X86::FP32_TO_INT16_IN_MEM:
19663   case X86::FP32_TO_INT32_IN_MEM:
19664   case X86::FP32_TO_INT64_IN_MEM:
19665   case X86::FP64_TO_INT16_IN_MEM:
19666   case X86::FP64_TO_INT32_IN_MEM:
19667   case X86::FP64_TO_INT64_IN_MEM:
19668   case X86::FP80_TO_INT16_IN_MEM:
19669   case X86::FP80_TO_INT32_IN_MEM:
19670   case X86::FP80_TO_INT64_IN_MEM: {
19671     MachineFunction *F = BB->getParent();
19672     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19673     DebugLoc DL = MI->getDebugLoc();
19674
19675     // Change the floating point control register to use "round towards zero"
19676     // mode when truncating to an integer value.
19677     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19678     addFrameReference(BuildMI(*BB, MI, DL,
19679                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19680
19681     // Load the old value of the high byte of the control word...
19682     unsigned OldCW =
19683       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19684     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19685                       CWFrameIdx);
19686
19687     // Set the high part to be round to zero...
19688     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19689       .addImm(0xC7F);
19690
19691     // Reload the modified control word now...
19692     addFrameReference(BuildMI(*BB, MI, DL,
19693                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19694
19695     // Restore the memory image of control word to original value
19696     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19697       .addReg(OldCW);
19698
19699     // Get the X86 opcode to use.
19700     unsigned Opc;
19701     switch (MI->getOpcode()) {
19702     default: llvm_unreachable("illegal opcode!");
19703     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19704     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19705     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19706     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19707     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19708     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19709     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19710     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19711     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19712     }
19713
19714     X86AddressMode AM;
19715     MachineOperand &Op = MI->getOperand(0);
19716     if (Op.isReg()) {
19717       AM.BaseType = X86AddressMode::RegBase;
19718       AM.Base.Reg = Op.getReg();
19719     } else {
19720       AM.BaseType = X86AddressMode::FrameIndexBase;
19721       AM.Base.FrameIndex = Op.getIndex();
19722     }
19723     Op = MI->getOperand(1);
19724     if (Op.isImm())
19725       AM.Scale = Op.getImm();
19726     Op = MI->getOperand(2);
19727     if (Op.isImm())
19728       AM.IndexReg = Op.getImm();
19729     Op = MI->getOperand(3);
19730     if (Op.isGlobal()) {
19731       AM.GV = Op.getGlobal();
19732     } else {
19733       AM.Disp = Op.getImm();
19734     }
19735     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19736                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19737
19738     // Reload the original control word now.
19739     addFrameReference(BuildMI(*BB, MI, DL,
19740                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19741
19742     MI->eraseFromParent();   // The pseudo instruction is gone now.
19743     return BB;
19744   }
19745     // String/text processing lowering.
19746   case X86::PCMPISTRM128REG:
19747   case X86::VPCMPISTRM128REG:
19748   case X86::PCMPISTRM128MEM:
19749   case X86::VPCMPISTRM128MEM:
19750   case X86::PCMPESTRM128REG:
19751   case X86::VPCMPESTRM128REG:
19752   case X86::PCMPESTRM128MEM:
19753   case X86::VPCMPESTRM128MEM:
19754     assert(Subtarget->hasSSE42() &&
19755            "Target must have SSE4.2 or AVX features enabled");
19756     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19757
19758   // String/text processing lowering.
19759   case X86::PCMPISTRIREG:
19760   case X86::VPCMPISTRIREG:
19761   case X86::PCMPISTRIMEM:
19762   case X86::VPCMPISTRIMEM:
19763   case X86::PCMPESTRIREG:
19764   case X86::VPCMPESTRIREG:
19765   case X86::PCMPESTRIMEM:
19766   case X86::VPCMPESTRIMEM:
19767     assert(Subtarget->hasSSE42() &&
19768            "Target must have SSE4.2 or AVX features enabled");
19769     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19770
19771   // Thread synchronization.
19772   case X86::MONITOR:
19773     return EmitMonitor(MI, BB, Subtarget);
19774
19775   // xbegin
19776   case X86::XBEGIN:
19777     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19778
19779   case X86::VASTART_SAVE_XMM_REGS:
19780     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19781
19782   case X86::VAARG_64:
19783     return EmitVAARG64WithCustomInserter(MI, BB);
19784
19785   case X86::EH_SjLj_SetJmp32:
19786   case X86::EH_SjLj_SetJmp64:
19787     return emitEHSjLjSetJmp(MI, BB);
19788
19789   case X86::EH_SjLj_LongJmp32:
19790   case X86::EH_SjLj_LongJmp64:
19791     return emitEHSjLjLongJmp(MI, BB);
19792
19793   case TargetOpcode::STATEPOINT:
19794     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19795     // this point in the process.  We diverge later.
19796     return emitPatchPoint(MI, BB);
19797
19798   case TargetOpcode::STACKMAP:
19799   case TargetOpcode::PATCHPOINT:
19800     return emitPatchPoint(MI, BB);
19801
19802   case X86::VFMADDPDr213r:
19803   case X86::VFMADDPSr213r:
19804   case X86::VFMADDSDr213r:
19805   case X86::VFMADDSSr213r:
19806   case X86::VFMSUBPDr213r:
19807   case X86::VFMSUBPSr213r:
19808   case X86::VFMSUBSDr213r:
19809   case X86::VFMSUBSSr213r:
19810   case X86::VFNMADDPDr213r:
19811   case X86::VFNMADDPSr213r:
19812   case X86::VFNMADDSDr213r:
19813   case X86::VFNMADDSSr213r:
19814   case X86::VFNMSUBPDr213r:
19815   case X86::VFNMSUBPSr213r:
19816   case X86::VFNMSUBSDr213r:
19817   case X86::VFNMSUBSSr213r:
19818   case X86::VFMADDSUBPDr213r:
19819   case X86::VFMADDSUBPSr213r:
19820   case X86::VFMSUBADDPDr213r:
19821   case X86::VFMSUBADDPSr213r:
19822   case X86::VFMADDPDr213rY:
19823   case X86::VFMADDPSr213rY:
19824   case X86::VFMSUBPDr213rY:
19825   case X86::VFMSUBPSr213rY:
19826   case X86::VFNMADDPDr213rY:
19827   case X86::VFNMADDPSr213rY:
19828   case X86::VFNMSUBPDr213rY:
19829   case X86::VFNMSUBPSr213rY:
19830   case X86::VFMADDSUBPDr213rY:
19831   case X86::VFMADDSUBPSr213rY:
19832   case X86::VFMSUBADDPDr213rY:
19833   case X86::VFMSUBADDPSr213rY:
19834     return emitFMA3Instr(MI, BB);
19835   }
19836 }
19837
19838 //===----------------------------------------------------------------------===//
19839 //                           X86 Optimization Hooks
19840 //===----------------------------------------------------------------------===//
19841
19842 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19843                                                       APInt &KnownZero,
19844                                                       APInt &KnownOne,
19845                                                       const SelectionDAG &DAG,
19846                                                       unsigned Depth) const {
19847   unsigned BitWidth = KnownZero.getBitWidth();
19848   unsigned Opc = Op.getOpcode();
19849   assert((Opc >= ISD::BUILTIN_OP_END ||
19850           Opc == ISD::INTRINSIC_WO_CHAIN ||
19851           Opc == ISD::INTRINSIC_W_CHAIN ||
19852           Opc == ISD::INTRINSIC_VOID) &&
19853          "Should use MaskedValueIsZero if you don't know whether Op"
19854          " is a target node!");
19855
19856   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19857   switch (Opc) {
19858   default: break;
19859   case X86ISD::ADD:
19860   case X86ISD::SUB:
19861   case X86ISD::ADC:
19862   case X86ISD::SBB:
19863   case X86ISD::SMUL:
19864   case X86ISD::UMUL:
19865   case X86ISD::INC:
19866   case X86ISD::DEC:
19867   case X86ISD::OR:
19868   case X86ISD::XOR:
19869   case X86ISD::AND:
19870     // These nodes' second result is a boolean.
19871     if (Op.getResNo() == 0)
19872       break;
19873     // Fallthrough
19874   case X86ISD::SETCC:
19875     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19876     break;
19877   case ISD::INTRINSIC_WO_CHAIN: {
19878     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19879     unsigned NumLoBits = 0;
19880     switch (IntId) {
19881     default: break;
19882     case Intrinsic::x86_sse_movmsk_ps:
19883     case Intrinsic::x86_avx_movmsk_ps_256:
19884     case Intrinsic::x86_sse2_movmsk_pd:
19885     case Intrinsic::x86_avx_movmsk_pd_256:
19886     case Intrinsic::x86_mmx_pmovmskb:
19887     case Intrinsic::x86_sse2_pmovmskb_128:
19888     case Intrinsic::x86_avx2_pmovmskb: {
19889       // High bits of movmskp{s|d}, pmovmskb are known zero.
19890       switch (IntId) {
19891         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19892         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19893         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19894         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19895         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19896         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19897         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19898         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19899       }
19900       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19901       break;
19902     }
19903     }
19904     break;
19905   }
19906   }
19907 }
19908
19909 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19910   SDValue Op,
19911   const SelectionDAG &,
19912   unsigned Depth) const {
19913   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19914   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19915     return Op.getValueType().getScalarType().getSizeInBits();
19916
19917   // Fallback case.
19918   return 1;
19919 }
19920
19921 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19922 /// node is a GlobalAddress + offset.
19923 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19924                                        const GlobalValue* &GA,
19925                                        int64_t &Offset) const {
19926   if (N->getOpcode() == X86ISD::Wrapper) {
19927     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19928       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19929       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19930       return true;
19931     }
19932   }
19933   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19934 }
19935
19936 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19937 /// same as extracting the high 128-bit part of 256-bit vector and then
19938 /// inserting the result into the low part of a new 256-bit vector
19939 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19940   EVT VT = SVOp->getValueType(0);
19941   unsigned NumElems = VT.getVectorNumElements();
19942
19943   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19944   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19945     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19946         SVOp->getMaskElt(j) >= 0)
19947       return false;
19948
19949   return true;
19950 }
19951
19952 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19953 /// same as extracting the low 128-bit part of 256-bit vector and then
19954 /// inserting the result into the high part of a new 256-bit vector
19955 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19956   EVT VT = SVOp->getValueType(0);
19957   unsigned NumElems = VT.getVectorNumElements();
19958
19959   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19960   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19961     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19962         SVOp->getMaskElt(j) >= 0)
19963       return false;
19964
19965   return true;
19966 }
19967
19968 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19969 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19970                                         TargetLowering::DAGCombinerInfo &DCI,
19971                                         const X86Subtarget* Subtarget) {
19972   SDLoc dl(N);
19973   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19974   SDValue V1 = SVOp->getOperand(0);
19975   SDValue V2 = SVOp->getOperand(1);
19976   EVT VT = SVOp->getValueType(0);
19977   unsigned NumElems = VT.getVectorNumElements();
19978
19979   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19980       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19981     //
19982     //                   0,0,0,...
19983     //                      |
19984     //    V      UNDEF    BUILD_VECTOR    UNDEF
19985     //     \      /           \           /
19986     //  CONCAT_VECTOR         CONCAT_VECTOR
19987     //         \                  /
19988     //          \                /
19989     //          RESULT: V + zero extended
19990     //
19991     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19992         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19993         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19994       return SDValue();
19995
19996     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19997       return SDValue();
19998
19999     // To match the shuffle mask, the first half of the mask should
20000     // be exactly the first vector, and all the rest a splat with the
20001     // first element of the second one.
20002     for (unsigned i = 0; i != NumElems/2; ++i)
20003       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20004           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20005         return SDValue();
20006
20007     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20008     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20009       if (Ld->hasNUsesOfValue(1, 0)) {
20010         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20011         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20012         SDValue ResNode =
20013           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20014                                   Ld->getMemoryVT(),
20015                                   Ld->getPointerInfo(),
20016                                   Ld->getAlignment(),
20017                                   false/*isVolatile*/, true/*ReadMem*/,
20018                                   false/*WriteMem*/);
20019
20020         // Make sure the newly-created LOAD is in the same position as Ld in
20021         // terms of dependency. We create a TokenFactor for Ld and ResNode,
20022         // and update uses of Ld's output chain to use the TokenFactor.
20023         if (Ld->hasAnyUseOfValue(1)) {
20024           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20025                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20026           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20027           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20028                                  SDValue(ResNode.getNode(), 1));
20029         }
20030
20031         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
20032       }
20033     }
20034
20035     // Emit a zeroed vector and insert the desired subvector on its
20036     // first half.
20037     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20038     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20039     return DCI.CombineTo(N, InsV);
20040   }
20041
20042   //===--------------------------------------------------------------------===//
20043   // Combine some shuffles into subvector extracts and inserts:
20044   //
20045
20046   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20047   if (isShuffleHigh128VectorInsertLow(SVOp)) {
20048     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20049     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20050     return DCI.CombineTo(N, InsV);
20051   }
20052
20053   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20054   if (isShuffleLow128VectorInsertHigh(SVOp)) {
20055     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20056     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20057     return DCI.CombineTo(N, InsV);
20058   }
20059
20060   return SDValue();
20061 }
20062
20063 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20064 /// possible.
20065 ///
20066 /// This is the leaf of the recursive combinine below. When we have found some
20067 /// chain of single-use x86 shuffle instructions and accumulated the combined
20068 /// shuffle mask represented by them, this will try to pattern match that mask
20069 /// into either a single instruction if there is a special purpose instruction
20070 /// for this operation, or into a PSHUFB instruction which is a fully general
20071 /// instruction but should only be used to replace chains over a certain depth.
20072 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20073                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20074                                    TargetLowering::DAGCombinerInfo &DCI,
20075                                    const X86Subtarget *Subtarget) {
20076   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20077
20078   // Find the operand that enters the chain. Note that multiple uses are OK
20079   // here, we're not going to remove the operand we find.
20080   SDValue Input = Op.getOperand(0);
20081   while (Input.getOpcode() == ISD::BITCAST)
20082     Input = Input.getOperand(0);
20083
20084   MVT VT = Input.getSimpleValueType();
20085   MVT RootVT = Root.getSimpleValueType();
20086   SDLoc DL(Root);
20087
20088   // Just remove no-op shuffle masks.
20089   if (Mask.size() == 1) {
20090     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
20091                   /*AddTo*/ true);
20092     return true;
20093   }
20094
20095   // Use the float domain if the operand type is a floating point type.
20096   bool FloatDomain = VT.isFloatingPoint();
20097
20098   // For floating point shuffles, we don't have free copies in the shuffle
20099   // instructions or the ability to load as part of the instruction, so
20100   // canonicalize their shuffles to UNPCK or MOV variants.
20101   //
20102   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20103   // vectors because it can have a load folded into it that UNPCK cannot. This
20104   // doesn't preclude something switching to the shorter encoding post-RA.
20105   //
20106   // FIXME: Should teach these routines about AVX vector widths.
20107   if (FloatDomain && VT.getSizeInBits() == 128) {
20108     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20109       bool Lo = Mask.equals({0, 0});
20110       unsigned Shuffle;
20111       MVT ShuffleVT;
20112       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20113       // is no slower than UNPCKLPD but has the option to fold the input operand
20114       // into even an unaligned memory load.
20115       if (Lo && Subtarget->hasSSE3()) {
20116         Shuffle = X86ISD::MOVDDUP;
20117         ShuffleVT = MVT::v2f64;
20118       } else {
20119         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20120         // than the UNPCK variants.
20121         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20122         ShuffleVT = MVT::v4f32;
20123       }
20124       if (Depth == 1 && Root->getOpcode() == Shuffle)
20125         return false; // Nothing to do!
20126       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20127       DCI.AddToWorklist(Op.getNode());
20128       if (Shuffle == X86ISD::MOVDDUP)
20129         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20130       else
20131         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20132       DCI.AddToWorklist(Op.getNode());
20133       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20134                     /*AddTo*/ true);
20135       return true;
20136     }
20137     if (Subtarget->hasSSE3() &&
20138         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20139       bool Lo = Mask.equals({0, 0, 2, 2});
20140       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20141       MVT ShuffleVT = MVT::v4f32;
20142       if (Depth == 1 && Root->getOpcode() == Shuffle)
20143         return false; // Nothing to do!
20144       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20145       DCI.AddToWorklist(Op.getNode());
20146       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20147       DCI.AddToWorklist(Op.getNode());
20148       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20149                     /*AddTo*/ true);
20150       return true;
20151     }
20152     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20153       bool Lo = Mask.equals({0, 0, 1, 1});
20154       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20155       MVT ShuffleVT = MVT::v4f32;
20156       if (Depth == 1 && Root->getOpcode() == Shuffle)
20157         return false; // Nothing to do!
20158       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20159       DCI.AddToWorklist(Op.getNode());
20160       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20161       DCI.AddToWorklist(Op.getNode());
20162       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20163                     /*AddTo*/ true);
20164       return true;
20165     }
20166   }
20167
20168   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20169   // variants as none of these have single-instruction variants that are
20170   // superior to the UNPCK formulation.
20171   if (!FloatDomain && VT.getSizeInBits() == 128 &&
20172       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20173        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20174        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20175        Mask.equals(
20176            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20177     bool Lo = Mask[0] == 0;
20178     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20179     if (Depth == 1 && Root->getOpcode() == Shuffle)
20180       return false; // Nothing to do!
20181     MVT ShuffleVT;
20182     switch (Mask.size()) {
20183     case 8:
20184       ShuffleVT = MVT::v8i16;
20185       break;
20186     case 16:
20187       ShuffleVT = MVT::v16i8;
20188       break;
20189     default:
20190       llvm_unreachable("Impossible mask size!");
20191     };
20192     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20193     DCI.AddToWorklist(Op.getNode());
20194     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20195     DCI.AddToWorklist(Op.getNode());
20196     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20197                   /*AddTo*/ true);
20198     return true;
20199   }
20200
20201   // Don't try to re-form single instruction chains under any circumstances now
20202   // that we've done encoding canonicalization for them.
20203   if (Depth < 2)
20204     return false;
20205
20206   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20207   // can replace them with a single PSHUFB instruction profitably. Intel's
20208   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20209   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20210   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20211     SmallVector<SDValue, 16> PSHUFBMask;
20212     int NumBytes = VT.getSizeInBits() / 8;
20213     int Ratio = NumBytes / Mask.size();
20214     for (int i = 0; i < NumBytes; ++i) {
20215       if (Mask[i / Ratio] == SM_SentinelUndef) {
20216         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20217         continue;
20218       }
20219       int M = Mask[i / Ratio] != SM_SentinelZero
20220                   ? Ratio * Mask[i / Ratio] + i % Ratio
20221                   : 255;
20222       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20223     }
20224     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20225     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20226     DCI.AddToWorklist(Op.getNode());
20227     SDValue PSHUFBMaskOp =
20228         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20229     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20230     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20231     DCI.AddToWorklist(Op.getNode());
20232     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20233                   /*AddTo*/ true);
20234     return true;
20235   }
20236
20237   // Failed to find any combines.
20238   return false;
20239 }
20240
20241 /// \brief Fully generic combining of x86 shuffle instructions.
20242 ///
20243 /// This should be the last combine run over the x86 shuffle instructions. Once
20244 /// they have been fully optimized, this will recursively consider all chains
20245 /// of single-use shuffle instructions, build a generic model of the cumulative
20246 /// shuffle operation, and check for simpler instructions which implement this
20247 /// operation. We use this primarily for two purposes:
20248 ///
20249 /// 1) Collapse generic shuffles to specialized single instructions when
20250 ///    equivalent. In most cases, this is just an encoding size win, but
20251 ///    sometimes we will collapse multiple generic shuffles into a single
20252 ///    special-purpose shuffle.
20253 /// 2) Look for sequences of shuffle instructions with 3 or more total
20254 ///    instructions, and replace them with the slightly more expensive SSSE3
20255 ///    PSHUFB instruction if available. We do this as the last combining step
20256 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20257 ///    a suitable short sequence of other instructions. The PHUFB will either
20258 ///    use a register or have to read from memory and so is slightly (but only
20259 ///    slightly) more expensive than the other shuffle instructions.
20260 ///
20261 /// Because this is inherently a quadratic operation (for each shuffle in
20262 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20263 /// This should never be an issue in practice as the shuffle lowering doesn't
20264 /// produce sequences of more than 8 instructions.
20265 ///
20266 /// FIXME: We will currently miss some cases where the redundant shuffling
20267 /// would simplify under the threshold for PSHUFB formation because of
20268 /// combine-ordering. To fix this, we should do the redundant instruction
20269 /// combining in this recursive walk.
20270 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20271                                           ArrayRef<int> RootMask,
20272                                           int Depth, bool HasPSHUFB,
20273                                           SelectionDAG &DAG,
20274                                           TargetLowering::DAGCombinerInfo &DCI,
20275                                           const X86Subtarget *Subtarget) {
20276   // Bound the depth of our recursive combine because this is ultimately
20277   // quadratic in nature.
20278   if (Depth > 8)
20279     return false;
20280
20281   // Directly rip through bitcasts to find the underlying operand.
20282   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20283     Op = Op.getOperand(0);
20284
20285   MVT VT = Op.getSimpleValueType();
20286   if (!VT.isVector())
20287     return false; // Bail if we hit a non-vector.
20288
20289   assert(Root.getSimpleValueType().isVector() &&
20290          "Shuffles operate on vector types!");
20291   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20292          "Can only combine shuffles of the same vector register size.");
20293
20294   if (!isTargetShuffle(Op.getOpcode()))
20295     return false;
20296   SmallVector<int, 16> OpMask;
20297   bool IsUnary;
20298   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20299   // We only can combine unary shuffles which we can decode the mask for.
20300   if (!HaveMask || !IsUnary)
20301     return false;
20302
20303   assert(VT.getVectorNumElements() == OpMask.size() &&
20304          "Different mask size from vector size!");
20305   assert(((RootMask.size() > OpMask.size() &&
20306            RootMask.size() % OpMask.size() == 0) ||
20307           (OpMask.size() > RootMask.size() &&
20308            OpMask.size() % RootMask.size() == 0) ||
20309           OpMask.size() == RootMask.size()) &&
20310          "The smaller number of elements must divide the larger.");
20311   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20312   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20313   assert(((RootRatio == 1 && OpRatio == 1) ||
20314           (RootRatio == 1) != (OpRatio == 1)) &&
20315          "Must not have a ratio for both incoming and op masks!");
20316
20317   SmallVector<int, 16> Mask;
20318   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20319
20320   // Merge this shuffle operation's mask into our accumulated mask. Note that
20321   // this shuffle's mask will be the first applied to the input, followed by the
20322   // root mask to get us all the way to the root value arrangement. The reason
20323   // for this order is that we are recursing up the operation chain.
20324   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20325     int RootIdx = i / RootRatio;
20326     if (RootMask[RootIdx] < 0) {
20327       // This is a zero or undef lane, we're done.
20328       Mask.push_back(RootMask[RootIdx]);
20329       continue;
20330     }
20331
20332     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20333     int OpIdx = RootMaskedIdx / OpRatio;
20334     if (OpMask[OpIdx] < 0) {
20335       // The incoming lanes are zero or undef, it doesn't matter which ones we
20336       // are using.
20337       Mask.push_back(OpMask[OpIdx]);
20338       continue;
20339     }
20340
20341     // Ok, we have non-zero lanes, map them through.
20342     Mask.push_back(OpMask[OpIdx] * OpRatio +
20343                    RootMaskedIdx % OpRatio);
20344   }
20345
20346   // See if we can recurse into the operand to combine more things.
20347   switch (Op.getOpcode()) {
20348     case X86ISD::PSHUFB:
20349       HasPSHUFB = true;
20350     case X86ISD::PSHUFD:
20351     case X86ISD::PSHUFHW:
20352     case X86ISD::PSHUFLW:
20353       if (Op.getOperand(0).hasOneUse() &&
20354           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20355                                         HasPSHUFB, DAG, DCI, Subtarget))
20356         return true;
20357       break;
20358
20359     case X86ISD::UNPCKL:
20360     case X86ISD::UNPCKH:
20361       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20362       // We can't check for single use, we have to check that this shuffle is the only user.
20363       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20364           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20365                                         HasPSHUFB, DAG, DCI, Subtarget))
20366           return true;
20367       break;
20368   }
20369
20370   // Minor canonicalization of the accumulated shuffle mask to make it easier
20371   // to match below. All this does is detect masks with squential pairs of
20372   // elements, and shrink them to the half-width mask. It does this in a loop
20373   // so it will reduce the size of the mask to the minimal width mask which
20374   // performs an equivalent shuffle.
20375   SmallVector<int, 16> WidenedMask;
20376   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20377     Mask = std::move(WidenedMask);
20378     WidenedMask.clear();
20379   }
20380
20381   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20382                                 Subtarget);
20383 }
20384
20385 /// \brief Get the PSHUF-style mask from PSHUF node.
20386 ///
20387 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20388 /// PSHUF-style masks that can be reused with such instructions.
20389 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20390   MVT VT = N.getSimpleValueType();
20391   SmallVector<int, 4> Mask;
20392   bool IsUnary;
20393   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20394   (void)HaveMask;
20395   assert(HaveMask);
20396
20397   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20398   // matter. Check that the upper masks are repeats and remove them.
20399   if (VT.getSizeInBits() > 128) {
20400     int LaneElts = 128 / VT.getScalarSizeInBits();
20401 #ifndef NDEBUG
20402     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20403       for (int j = 0; j < LaneElts; ++j)
20404         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20405                "Mask doesn't repeat in high 128-bit lanes!");
20406 #endif
20407     Mask.resize(LaneElts);
20408   }
20409
20410   switch (N.getOpcode()) {
20411   case X86ISD::PSHUFD:
20412     return Mask;
20413   case X86ISD::PSHUFLW:
20414     Mask.resize(4);
20415     return Mask;
20416   case X86ISD::PSHUFHW:
20417     Mask.erase(Mask.begin(), Mask.begin() + 4);
20418     for (int &M : Mask)
20419       M -= 4;
20420     return Mask;
20421   default:
20422     llvm_unreachable("No valid shuffle instruction found!");
20423   }
20424 }
20425
20426 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20427 ///
20428 /// We walk up the chain and look for a combinable shuffle, skipping over
20429 /// shuffles that we could hoist this shuffle's transformation past without
20430 /// altering anything.
20431 static SDValue
20432 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20433                              SelectionDAG &DAG,
20434                              TargetLowering::DAGCombinerInfo &DCI) {
20435   assert(N.getOpcode() == X86ISD::PSHUFD &&
20436          "Called with something other than an x86 128-bit half shuffle!");
20437   SDLoc DL(N);
20438
20439   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20440   // of the shuffles in the chain so that we can form a fresh chain to replace
20441   // this one.
20442   SmallVector<SDValue, 8> Chain;
20443   SDValue V = N.getOperand(0);
20444   for (; V.hasOneUse(); V = V.getOperand(0)) {
20445     switch (V.getOpcode()) {
20446     default:
20447       return SDValue(); // Nothing combined!
20448
20449     case ISD::BITCAST:
20450       // Skip bitcasts as we always know the type for the target specific
20451       // instructions.
20452       continue;
20453
20454     case X86ISD::PSHUFD:
20455       // Found another dword shuffle.
20456       break;
20457
20458     case X86ISD::PSHUFLW:
20459       // Check that the low words (being shuffled) are the identity in the
20460       // dword shuffle, and the high words are self-contained.
20461       if (Mask[0] != 0 || Mask[1] != 1 ||
20462           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20463         return SDValue();
20464
20465       Chain.push_back(V);
20466       continue;
20467
20468     case X86ISD::PSHUFHW:
20469       // Check that the high words (being shuffled) are the identity in the
20470       // dword shuffle, and the low words are self-contained.
20471       if (Mask[2] != 2 || Mask[3] != 3 ||
20472           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20473         return SDValue();
20474
20475       Chain.push_back(V);
20476       continue;
20477
20478     case X86ISD::UNPCKL:
20479     case X86ISD::UNPCKH:
20480       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20481       // shuffle into a preceding word shuffle.
20482       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20483           V.getSimpleValueType().getScalarType() != MVT::i16)
20484         return SDValue();
20485
20486       // Search for a half-shuffle which we can combine with.
20487       unsigned CombineOp =
20488           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20489       if (V.getOperand(0) != V.getOperand(1) ||
20490           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20491         return SDValue();
20492       Chain.push_back(V);
20493       V = V.getOperand(0);
20494       do {
20495         switch (V.getOpcode()) {
20496         default:
20497           return SDValue(); // Nothing to combine.
20498
20499         case X86ISD::PSHUFLW:
20500         case X86ISD::PSHUFHW:
20501           if (V.getOpcode() == CombineOp)
20502             break;
20503
20504           Chain.push_back(V);
20505
20506           // Fallthrough!
20507         case ISD::BITCAST:
20508           V = V.getOperand(0);
20509           continue;
20510         }
20511         break;
20512       } while (V.hasOneUse());
20513       break;
20514     }
20515     // Break out of the loop if we break out of the switch.
20516     break;
20517   }
20518
20519   if (!V.hasOneUse())
20520     // We fell out of the loop without finding a viable combining instruction.
20521     return SDValue();
20522
20523   // Merge this node's mask and our incoming mask.
20524   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20525   for (int &M : Mask)
20526     M = VMask[M];
20527   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20528                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20529
20530   // Rebuild the chain around this new shuffle.
20531   while (!Chain.empty()) {
20532     SDValue W = Chain.pop_back_val();
20533
20534     if (V.getValueType() != W.getOperand(0).getValueType())
20535       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20536
20537     switch (W.getOpcode()) {
20538     default:
20539       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20540
20541     case X86ISD::UNPCKL:
20542     case X86ISD::UNPCKH:
20543       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20544       break;
20545
20546     case X86ISD::PSHUFD:
20547     case X86ISD::PSHUFLW:
20548     case X86ISD::PSHUFHW:
20549       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20550       break;
20551     }
20552   }
20553   if (V.getValueType() != N.getValueType())
20554     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20555
20556   // Return the new chain to replace N.
20557   return V;
20558 }
20559
20560 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20561 ///
20562 /// We walk up the chain, skipping shuffles of the other half and looking
20563 /// through shuffles which switch halves trying to find a shuffle of the same
20564 /// pair of dwords.
20565 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20566                                         SelectionDAG &DAG,
20567                                         TargetLowering::DAGCombinerInfo &DCI) {
20568   assert(
20569       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20570       "Called with something other than an x86 128-bit half shuffle!");
20571   SDLoc DL(N);
20572   unsigned CombineOpcode = N.getOpcode();
20573
20574   // Walk up a single-use chain looking for a combinable shuffle.
20575   SDValue V = N.getOperand(0);
20576   for (; V.hasOneUse(); V = V.getOperand(0)) {
20577     switch (V.getOpcode()) {
20578     default:
20579       return false; // Nothing combined!
20580
20581     case ISD::BITCAST:
20582       // Skip bitcasts as we always know the type for the target specific
20583       // instructions.
20584       continue;
20585
20586     case X86ISD::PSHUFLW:
20587     case X86ISD::PSHUFHW:
20588       if (V.getOpcode() == CombineOpcode)
20589         break;
20590
20591       // Other-half shuffles are no-ops.
20592       continue;
20593     }
20594     // Break out of the loop if we break out of the switch.
20595     break;
20596   }
20597
20598   if (!V.hasOneUse())
20599     // We fell out of the loop without finding a viable combining instruction.
20600     return false;
20601
20602   // Combine away the bottom node as its shuffle will be accumulated into
20603   // a preceding shuffle.
20604   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20605
20606   // Record the old value.
20607   SDValue Old = V;
20608
20609   // Merge this node's mask and our incoming mask (adjusted to account for all
20610   // the pshufd instructions encountered).
20611   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20612   for (int &M : Mask)
20613     M = VMask[M];
20614   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20615                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20616
20617   // Check that the shuffles didn't cancel each other out. If not, we need to
20618   // combine to the new one.
20619   if (Old != V)
20620     // Replace the combinable shuffle with the combined one, updating all users
20621     // so that we re-evaluate the chain here.
20622     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20623
20624   return true;
20625 }
20626
20627 /// \brief Try to combine x86 target specific shuffles.
20628 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20629                                            TargetLowering::DAGCombinerInfo &DCI,
20630                                            const X86Subtarget *Subtarget) {
20631   SDLoc DL(N);
20632   MVT VT = N.getSimpleValueType();
20633   SmallVector<int, 4> Mask;
20634
20635   switch (N.getOpcode()) {
20636   case X86ISD::PSHUFD:
20637   case X86ISD::PSHUFLW:
20638   case X86ISD::PSHUFHW:
20639     Mask = getPSHUFShuffleMask(N);
20640     assert(Mask.size() == 4);
20641     break;
20642   default:
20643     return SDValue();
20644   }
20645
20646   // Nuke no-op shuffles that show up after combining.
20647   if (isNoopShuffleMask(Mask))
20648     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20649
20650   // Look for simplifications involving one or two shuffle instructions.
20651   SDValue V = N.getOperand(0);
20652   switch (N.getOpcode()) {
20653   default:
20654     break;
20655   case X86ISD::PSHUFLW:
20656   case X86ISD::PSHUFHW:
20657     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20658
20659     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20660       return SDValue(); // We combined away this shuffle, so we're done.
20661
20662     // See if this reduces to a PSHUFD which is no more expensive and can
20663     // combine with more operations. Note that it has to at least flip the
20664     // dwords as otherwise it would have been removed as a no-op.
20665     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20666       int DMask[] = {0, 1, 2, 3};
20667       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20668       DMask[DOffset + 0] = DOffset + 1;
20669       DMask[DOffset + 1] = DOffset + 0;
20670       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20671       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20672       DCI.AddToWorklist(V.getNode());
20673       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20674                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20675       DCI.AddToWorklist(V.getNode());
20676       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20677     }
20678
20679     // Look for shuffle patterns which can be implemented as a single unpack.
20680     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20681     // only works when we have a PSHUFD followed by two half-shuffles.
20682     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20683         (V.getOpcode() == X86ISD::PSHUFLW ||
20684          V.getOpcode() == X86ISD::PSHUFHW) &&
20685         V.getOpcode() != N.getOpcode() &&
20686         V.hasOneUse()) {
20687       SDValue D = V.getOperand(0);
20688       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20689         D = D.getOperand(0);
20690       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20691         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20692         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20693         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20694         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20695         int WordMask[8];
20696         for (int i = 0; i < 4; ++i) {
20697           WordMask[i + NOffset] = Mask[i] + NOffset;
20698           WordMask[i + VOffset] = VMask[i] + VOffset;
20699         }
20700         // Map the word mask through the DWord mask.
20701         int MappedMask[8];
20702         for (int i = 0; i < 8; ++i)
20703           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20704         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20705             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20706           // We can replace all three shuffles with an unpack.
20707           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20708           DCI.AddToWorklist(V.getNode());
20709           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20710                                                 : X86ISD::UNPCKH,
20711                              DL, VT, V, V);
20712         }
20713       }
20714     }
20715
20716     break;
20717
20718   case X86ISD::PSHUFD:
20719     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20720       return NewN;
20721
20722     break;
20723   }
20724
20725   return SDValue();
20726 }
20727
20728 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20729 ///
20730 /// We combine this directly on the abstract vector shuffle nodes so it is
20731 /// easier to generically match. We also insert dummy vector shuffle nodes for
20732 /// the operands which explicitly discard the lanes which are unused by this
20733 /// operation to try to flow through the rest of the combiner the fact that
20734 /// they're unused.
20735 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20736   SDLoc DL(N);
20737   EVT VT = N->getValueType(0);
20738
20739   // We only handle target-independent shuffles.
20740   // FIXME: It would be easy and harmless to use the target shuffle mask
20741   // extraction tool to support more.
20742   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20743     return SDValue();
20744
20745   auto *SVN = cast<ShuffleVectorSDNode>(N);
20746   ArrayRef<int> Mask = SVN->getMask();
20747   SDValue V1 = N->getOperand(0);
20748   SDValue V2 = N->getOperand(1);
20749
20750   // We require the first shuffle operand to be the SUB node, and the second to
20751   // be the ADD node.
20752   // FIXME: We should support the commuted patterns.
20753   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20754     return SDValue();
20755
20756   // If there are other uses of these operations we can't fold them.
20757   if (!V1->hasOneUse() || !V2->hasOneUse())
20758     return SDValue();
20759
20760   // Ensure that both operations have the same operands. Note that we can
20761   // commute the FADD operands.
20762   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20763   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20764       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20765     return SDValue();
20766
20767   // We're looking for blends between FADD and FSUB nodes. We insist on these
20768   // nodes being lined up in a specific expected pattern.
20769   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20770         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20771         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20772     return SDValue();
20773
20774   // Only specific types are legal at this point, assert so we notice if and
20775   // when these change.
20776   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20777           VT == MVT::v4f64) &&
20778          "Unknown vector type encountered!");
20779
20780   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20781 }
20782
20783 /// PerformShuffleCombine - Performs several different shuffle combines.
20784 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20785                                      TargetLowering::DAGCombinerInfo &DCI,
20786                                      const X86Subtarget *Subtarget) {
20787   SDLoc dl(N);
20788   SDValue N0 = N->getOperand(0);
20789   SDValue N1 = N->getOperand(1);
20790   EVT VT = N->getValueType(0);
20791
20792   // Don't create instructions with illegal types after legalize types has run.
20793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20794   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20795     return SDValue();
20796
20797   // If we have legalized the vector types, look for blends of FADD and FSUB
20798   // nodes that we can fuse into an ADDSUB node.
20799   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20800     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20801       return AddSub;
20802
20803   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20804   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20805       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20806     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20807
20808   // During Type Legalization, when promoting illegal vector types,
20809   // the backend might introduce new shuffle dag nodes and bitcasts.
20810   //
20811   // This code performs the following transformation:
20812   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20813   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20814   //
20815   // We do this only if both the bitcast and the BINOP dag nodes have
20816   // one use. Also, perform this transformation only if the new binary
20817   // operation is legal. This is to avoid introducing dag nodes that
20818   // potentially need to be further expanded (or custom lowered) into a
20819   // less optimal sequence of dag nodes.
20820   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20821       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20822       N0.getOpcode() == ISD::BITCAST) {
20823     SDValue BC0 = N0.getOperand(0);
20824     EVT SVT = BC0.getValueType();
20825     unsigned Opcode = BC0.getOpcode();
20826     unsigned NumElts = VT.getVectorNumElements();
20827
20828     if (BC0.hasOneUse() && SVT.isVector() &&
20829         SVT.getVectorNumElements() * 2 == NumElts &&
20830         TLI.isOperationLegal(Opcode, VT)) {
20831       bool CanFold = false;
20832       switch (Opcode) {
20833       default : break;
20834       case ISD::ADD :
20835       case ISD::FADD :
20836       case ISD::SUB :
20837       case ISD::FSUB :
20838       case ISD::MUL :
20839       case ISD::FMUL :
20840         CanFold = true;
20841       }
20842
20843       unsigned SVTNumElts = SVT.getVectorNumElements();
20844       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20845       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20846         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20847       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20848         CanFold = SVOp->getMaskElt(i) < 0;
20849
20850       if (CanFold) {
20851         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20852         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20853         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20854         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20855       }
20856     }
20857   }
20858
20859   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20860   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20861   // consecutive, non-overlapping, and in the right order.
20862   SmallVector<SDValue, 16> Elts;
20863   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20864     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20865
20866   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20867   if (LD.getNode())
20868     return LD;
20869
20870   if (isTargetShuffle(N->getOpcode())) {
20871     SDValue Shuffle =
20872         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20873     if (Shuffle.getNode())
20874       return Shuffle;
20875
20876     // Try recursively combining arbitrary sequences of x86 shuffle
20877     // instructions into higher-order shuffles. We do this after combining
20878     // specific PSHUF instruction sequences into their minimal form so that we
20879     // can evaluate how many specialized shuffle instructions are involved in
20880     // a particular chain.
20881     SmallVector<int, 1> NonceMask; // Just a placeholder.
20882     NonceMask.push_back(0);
20883     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20884                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20885                                       DCI, Subtarget))
20886       return SDValue(); // This routine will use CombineTo to replace N.
20887   }
20888
20889   return SDValue();
20890 }
20891
20892 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20893 /// specific shuffle of a load can be folded into a single element load.
20894 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20895 /// shuffles have been custom lowered so we need to handle those here.
20896 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20897                                          TargetLowering::DAGCombinerInfo &DCI) {
20898   if (DCI.isBeforeLegalizeOps())
20899     return SDValue();
20900
20901   SDValue InVec = N->getOperand(0);
20902   SDValue EltNo = N->getOperand(1);
20903
20904   if (!isa<ConstantSDNode>(EltNo))
20905     return SDValue();
20906
20907   EVT OriginalVT = InVec.getValueType();
20908
20909   if (InVec.getOpcode() == ISD::BITCAST) {
20910     // Don't duplicate a load with other uses.
20911     if (!InVec.hasOneUse())
20912       return SDValue();
20913     EVT BCVT = InVec.getOperand(0).getValueType();
20914     if (!BCVT.isVector() ||
20915         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20916       return SDValue();
20917     InVec = InVec.getOperand(0);
20918   }
20919
20920   EVT CurrentVT = InVec.getValueType();
20921
20922   if (!isTargetShuffle(InVec.getOpcode()))
20923     return SDValue();
20924
20925   // Don't duplicate a load with other uses.
20926   if (!InVec.hasOneUse())
20927     return SDValue();
20928
20929   SmallVector<int, 16> ShuffleMask;
20930   bool UnaryShuffle;
20931   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20932                             ShuffleMask, UnaryShuffle))
20933     return SDValue();
20934
20935   // Select the input vector, guarding against out of range extract vector.
20936   unsigned NumElems = CurrentVT.getVectorNumElements();
20937   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20938   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20939   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20940                                          : InVec.getOperand(1);
20941
20942   // If inputs to shuffle are the same for both ops, then allow 2 uses
20943   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20944                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20945
20946   if (LdNode.getOpcode() == ISD::BITCAST) {
20947     // Don't duplicate a load with other uses.
20948     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20949       return SDValue();
20950
20951     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20952     LdNode = LdNode.getOperand(0);
20953   }
20954
20955   if (!ISD::isNormalLoad(LdNode.getNode()))
20956     return SDValue();
20957
20958   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20959
20960   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20961     return SDValue();
20962
20963   EVT EltVT = N->getValueType(0);
20964   // If there's a bitcast before the shuffle, check if the load type and
20965   // alignment is valid.
20966   unsigned Align = LN0->getAlignment();
20967   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20968   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20969       EltVT.getTypeForEVT(*DAG.getContext()));
20970
20971   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20972     return SDValue();
20973
20974   // All checks match so transform back to vector_shuffle so that DAG combiner
20975   // can finish the job
20976   SDLoc dl(N);
20977
20978   // Create shuffle node taking into account the case that its a unary shuffle
20979   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20980                                    : InVec.getOperand(1);
20981   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20982                                  InVec.getOperand(0), Shuffle,
20983                                  &ShuffleMask[0]);
20984   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20985   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20986                      EltNo);
20987 }
20988
20989 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20990 /// special and don't usually play with other vector types, it's better to
20991 /// handle them early to be sure we emit efficient code by avoiding
20992 /// store-load conversions.
20993 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20994   if (N->getValueType(0) != MVT::x86mmx ||
20995       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20996       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20997     return SDValue();
20998
20999   SDValue V = N->getOperand(0);
21000   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21001   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21002     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21003                        N->getValueType(0), V.getOperand(0));
21004
21005   return SDValue();
21006 }
21007
21008 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21009 /// generation and convert it from being a bunch of shuffles and extracts
21010 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21011 /// storing the value and loading scalars back, while for x64 we should
21012 /// use 64-bit extracts and shifts.
21013 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21014                                          TargetLowering::DAGCombinerInfo &DCI) {
21015   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
21016   if (NewOp.getNode())
21017     return NewOp;
21018
21019   SDValue InputVector = N->getOperand(0);
21020   SDLoc dl(InputVector);
21021   // Detect mmx to i32 conversion through a v2i32 elt extract.
21022   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21023       N->getValueType(0) == MVT::i32 &&
21024       InputVector.getValueType() == MVT::v2i32) {
21025
21026     // The bitcast source is a direct mmx result.
21027     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21028     if (MMXSrc.getValueType() == MVT::x86mmx)
21029       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21030                          N->getValueType(0),
21031                          InputVector.getNode()->getOperand(0));
21032
21033     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21034     SDValue MMXSrcOp = MMXSrc.getOperand(0);
21035     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21036         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21037         MMXSrcOp.getOpcode() == ISD::BITCAST &&
21038         MMXSrcOp.getValueType() == MVT::v1i64 &&
21039         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21040       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21041                          N->getValueType(0),
21042                          MMXSrcOp.getOperand(0));
21043   }
21044
21045   EVT VT = N->getValueType(0);
21046
21047   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21048       InputVector.getOpcode() == ISD::BITCAST &&
21049       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21050     uint64_t ExtractedElt =
21051           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21052     uint64_t InputValue =
21053           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21054     uint64_t Res = (InputValue >> ExtractedElt) & 1;
21055     return DAG.getConstant(Res, dl, MVT::i1);
21056   }
21057   // Only operate on vectors of 4 elements, where the alternative shuffling
21058   // gets to be more expensive.
21059   if (InputVector.getValueType() != MVT::v4i32)
21060     return SDValue();
21061
21062   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21063   // single use which is a sign-extend or zero-extend, and all elements are
21064   // used.
21065   SmallVector<SDNode *, 4> Uses;
21066   unsigned ExtractedElements = 0;
21067   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21068        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21069     if (UI.getUse().getResNo() != InputVector.getResNo())
21070       return SDValue();
21071
21072     SDNode *Extract = *UI;
21073     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21074       return SDValue();
21075
21076     if (Extract->getValueType(0) != MVT::i32)
21077       return SDValue();
21078     if (!Extract->hasOneUse())
21079       return SDValue();
21080     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21081         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21082       return SDValue();
21083     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21084       return SDValue();
21085
21086     // Record which element was extracted.
21087     ExtractedElements |=
21088       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21089
21090     Uses.push_back(Extract);
21091   }
21092
21093   // If not all the elements were used, this may not be worthwhile.
21094   if (ExtractedElements != 15)
21095     return SDValue();
21096
21097   // Ok, we've now decided to do the transformation.
21098   // If 64-bit shifts are legal, use the extract-shift sequence,
21099   // otherwise bounce the vector off the cache.
21100   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21101   SDValue Vals[4];
21102
21103   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21104     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
21105     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
21106     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21107       DAG.getConstant(0, dl, VecIdxTy));
21108     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21109       DAG.getConstant(1, dl, VecIdxTy));
21110
21111     SDValue ShAmt = DAG.getConstant(32, dl,
21112       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
21113     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21114     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21115       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21116     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21117     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21118       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21119   } else {
21120     // Store the value to a temporary stack slot.
21121     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21122     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21123       MachinePointerInfo(), false, false, 0);
21124
21125     EVT ElementType = InputVector.getValueType().getVectorElementType();
21126     unsigned EltSize = ElementType.getSizeInBits() / 8;
21127
21128     // Replace each use (extract) with a load of the appropriate element.
21129     for (unsigned i = 0; i < 4; ++i) {
21130       uint64_t Offset = EltSize * i;
21131       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
21132
21133       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
21134                                        StackPtr, OffsetVal);
21135
21136       // Load the scalar.
21137       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21138                             ScalarAddr, MachinePointerInfo(),
21139                             false, false, false, 0);
21140
21141     }
21142   }
21143
21144   // Replace the extracts
21145   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21146     UE = Uses.end(); UI != UE; ++UI) {
21147     SDNode *Extract = *UI;
21148
21149     SDValue Idx = Extract->getOperand(1);
21150     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21151     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21152   }
21153
21154   // The replacement was made in place; don't return anything.
21155   return SDValue();
21156 }
21157
21158 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21159 static std::pair<unsigned, bool>
21160 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21161                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21162   if (!VT.isVector())
21163     return std::make_pair(0, false);
21164
21165   bool NeedSplit = false;
21166   switch (VT.getSimpleVT().SimpleTy) {
21167   default: return std::make_pair(0, false);
21168   case MVT::v4i64:
21169   case MVT::v2i64:
21170     if (!Subtarget->hasVLX())
21171       return std::make_pair(0, false);
21172     break;
21173   case MVT::v64i8:
21174   case MVT::v32i16:
21175     if (!Subtarget->hasBWI())
21176       return std::make_pair(0, false);
21177     break;
21178   case MVT::v16i32:
21179   case MVT::v8i64:
21180     if (!Subtarget->hasAVX512())
21181       return std::make_pair(0, false);
21182     break;
21183   case MVT::v32i8:
21184   case MVT::v16i16:
21185   case MVT::v8i32:
21186     if (!Subtarget->hasAVX2())
21187       NeedSplit = true;
21188     if (!Subtarget->hasAVX())
21189       return std::make_pair(0, false);
21190     break;
21191   case MVT::v16i8:
21192   case MVT::v8i16:
21193   case MVT::v4i32:
21194     if (!Subtarget->hasSSE2())
21195       return std::make_pair(0, false);
21196   }
21197
21198   // SSE2 has only a small subset of the operations.
21199   bool hasUnsigned = Subtarget->hasSSE41() ||
21200                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21201   bool hasSigned = Subtarget->hasSSE41() ||
21202                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21203
21204   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21205
21206   unsigned Opc = 0;
21207   // Check for x CC y ? x : y.
21208   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21209       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21210     switch (CC) {
21211     default: break;
21212     case ISD::SETULT:
21213     case ISD::SETULE:
21214       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21215     case ISD::SETUGT:
21216     case ISD::SETUGE:
21217       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21218     case ISD::SETLT:
21219     case ISD::SETLE:
21220       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21221     case ISD::SETGT:
21222     case ISD::SETGE:
21223       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21224     }
21225   // Check for x CC y ? y : x -- a min/max with reversed arms.
21226   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21227              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21228     switch (CC) {
21229     default: break;
21230     case ISD::SETULT:
21231     case ISD::SETULE:
21232       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21233     case ISD::SETUGT:
21234     case ISD::SETUGE:
21235       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21236     case ISD::SETLT:
21237     case ISD::SETLE:
21238       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21239     case ISD::SETGT:
21240     case ISD::SETGE:
21241       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21242     }
21243   }
21244
21245   return std::make_pair(Opc, NeedSplit);
21246 }
21247
21248 static SDValue
21249 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21250                                       const X86Subtarget *Subtarget) {
21251   SDLoc dl(N);
21252   SDValue Cond = N->getOperand(0);
21253   SDValue LHS = N->getOperand(1);
21254   SDValue RHS = N->getOperand(2);
21255
21256   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21257     SDValue CondSrc = Cond->getOperand(0);
21258     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21259       Cond = CondSrc->getOperand(0);
21260   }
21261
21262   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21263     return SDValue();
21264
21265   // A vselect where all conditions and data are constants can be optimized into
21266   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21267   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21268       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21269     return SDValue();
21270
21271   unsigned MaskValue = 0;
21272   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21273     return SDValue();
21274
21275   MVT VT = N->getSimpleValueType(0);
21276   unsigned NumElems = VT.getVectorNumElements();
21277   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21278   for (unsigned i = 0; i < NumElems; ++i) {
21279     // Be sure we emit undef where we can.
21280     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21281       ShuffleMask[i] = -1;
21282     else
21283       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21284   }
21285
21286   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21287   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21288     return SDValue();
21289   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21290 }
21291
21292 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21293 /// nodes.
21294 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21295                                     TargetLowering::DAGCombinerInfo &DCI,
21296                                     const X86Subtarget *Subtarget) {
21297   SDLoc DL(N);
21298   SDValue Cond = N->getOperand(0);
21299   // Get the LHS/RHS of the select.
21300   SDValue LHS = N->getOperand(1);
21301   SDValue RHS = N->getOperand(2);
21302   EVT VT = LHS.getValueType();
21303   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21304
21305   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21306   // instructions match the semantics of the common C idiom x<y?x:y but not
21307   // x<=y?x:y, because of how they handle negative zero (which can be
21308   // ignored in unsafe-math mode).
21309   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21310   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21311       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21312       (Subtarget->hasSSE2() ||
21313        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21314     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21315
21316     unsigned Opcode = 0;
21317     // Check for x CC y ? x : y.
21318     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21319         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21320       switch (CC) {
21321       default: break;
21322       case ISD::SETULT:
21323         // Converting this to a min would handle NaNs incorrectly, and swapping
21324         // the operands would cause it to handle comparisons between positive
21325         // and negative zero incorrectly.
21326         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21327           if (!DAG.getTarget().Options.UnsafeFPMath &&
21328               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21329             break;
21330           std::swap(LHS, RHS);
21331         }
21332         Opcode = X86ISD::FMIN;
21333         break;
21334       case ISD::SETOLE:
21335         // Converting this to a min would handle comparisons between positive
21336         // and negative zero incorrectly.
21337         if (!DAG.getTarget().Options.UnsafeFPMath &&
21338             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21339           break;
21340         Opcode = X86ISD::FMIN;
21341         break;
21342       case ISD::SETULE:
21343         // Converting this to a min would handle both negative zeros and NaNs
21344         // incorrectly, but we can swap the operands to fix both.
21345         std::swap(LHS, RHS);
21346       case ISD::SETOLT:
21347       case ISD::SETLT:
21348       case ISD::SETLE:
21349         Opcode = X86ISD::FMIN;
21350         break;
21351
21352       case ISD::SETOGE:
21353         // Converting this to a max would handle comparisons between positive
21354         // and negative zero incorrectly.
21355         if (!DAG.getTarget().Options.UnsafeFPMath &&
21356             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21357           break;
21358         Opcode = X86ISD::FMAX;
21359         break;
21360       case ISD::SETUGT:
21361         // Converting this to a max would handle NaNs incorrectly, and swapping
21362         // the operands would cause it to handle comparisons between positive
21363         // and negative zero incorrectly.
21364         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21365           if (!DAG.getTarget().Options.UnsafeFPMath &&
21366               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21367             break;
21368           std::swap(LHS, RHS);
21369         }
21370         Opcode = X86ISD::FMAX;
21371         break;
21372       case ISD::SETUGE:
21373         // Converting this to a max would handle both negative zeros and NaNs
21374         // incorrectly, but we can swap the operands to fix both.
21375         std::swap(LHS, RHS);
21376       case ISD::SETOGT:
21377       case ISD::SETGT:
21378       case ISD::SETGE:
21379         Opcode = X86ISD::FMAX;
21380         break;
21381       }
21382     // Check for x CC y ? y : x -- a min/max with reversed arms.
21383     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21384                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21385       switch (CC) {
21386       default: break;
21387       case ISD::SETOGE:
21388         // Converting this to a min would handle comparisons between positive
21389         // and negative zero incorrectly, and swapping the operands would
21390         // cause it to handle NaNs incorrectly.
21391         if (!DAG.getTarget().Options.UnsafeFPMath &&
21392             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21393           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21394             break;
21395           std::swap(LHS, RHS);
21396         }
21397         Opcode = X86ISD::FMIN;
21398         break;
21399       case ISD::SETUGT:
21400         // Converting this to a min would handle NaNs incorrectly.
21401         if (!DAG.getTarget().Options.UnsafeFPMath &&
21402             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21403           break;
21404         Opcode = X86ISD::FMIN;
21405         break;
21406       case ISD::SETUGE:
21407         // Converting this to a min would handle both negative zeros and NaNs
21408         // incorrectly, but we can swap the operands to fix both.
21409         std::swap(LHS, RHS);
21410       case ISD::SETOGT:
21411       case ISD::SETGT:
21412       case ISD::SETGE:
21413         Opcode = X86ISD::FMIN;
21414         break;
21415
21416       case ISD::SETULT:
21417         // Converting this to a max would handle NaNs incorrectly.
21418         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21419           break;
21420         Opcode = X86ISD::FMAX;
21421         break;
21422       case ISD::SETOLE:
21423         // Converting this to a max would handle comparisons between positive
21424         // and negative zero incorrectly, and swapping the operands would
21425         // cause it to handle NaNs incorrectly.
21426         if (!DAG.getTarget().Options.UnsafeFPMath &&
21427             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21428           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21429             break;
21430           std::swap(LHS, RHS);
21431         }
21432         Opcode = X86ISD::FMAX;
21433         break;
21434       case ISD::SETULE:
21435         // Converting this to a max would handle both negative zeros and NaNs
21436         // incorrectly, but we can swap the operands to fix both.
21437         std::swap(LHS, RHS);
21438       case ISD::SETOLT:
21439       case ISD::SETLT:
21440       case ISD::SETLE:
21441         Opcode = X86ISD::FMAX;
21442         break;
21443       }
21444     }
21445
21446     if (Opcode)
21447       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21448   }
21449
21450   EVT CondVT = Cond.getValueType();
21451   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21452       CondVT.getVectorElementType() == MVT::i1) {
21453     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21454     // lowering on KNL. In this case we convert it to
21455     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21456     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21457     // Since SKX these selects have a proper lowering.
21458     EVT OpVT = LHS.getValueType();
21459     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21460         (OpVT.getVectorElementType() == MVT::i8 ||
21461          OpVT.getVectorElementType() == MVT::i16) &&
21462         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21463       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21464       DCI.AddToWorklist(Cond.getNode());
21465       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21466     }
21467   }
21468   // If this is a select between two integer constants, try to do some
21469   // optimizations.
21470   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21471     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21472       // Don't do this for crazy integer types.
21473       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21474         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21475         // so that TrueC (the true value) is larger than FalseC.
21476         bool NeedsCondInvert = false;
21477
21478         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21479             // Efficiently invertible.
21480             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21481              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21482               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21483           NeedsCondInvert = true;
21484           std::swap(TrueC, FalseC);
21485         }
21486
21487         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21488         if (FalseC->getAPIntValue() == 0 &&
21489             TrueC->getAPIntValue().isPowerOf2()) {
21490           if (NeedsCondInvert) // Invert the condition if needed.
21491             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21492                                DAG.getConstant(1, DL, Cond.getValueType()));
21493
21494           // Zero extend the condition if needed.
21495           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21496
21497           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21498           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21499                              DAG.getConstant(ShAmt, DL, MVT::i8));
21500         }
21501
21502         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21503         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21504           if (NeedsCondInvert) // Invert the condition if needed.
21505             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21506                                DAG.getConstant(1, DL, Cond.getValueType()));
21507
21508           // Zero extend the condition if needed.
21509           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21510                              FalseC->getValueType(0), Cond);
21511           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21512                              SDValue(FalseC, 0));
21513         }
21514
21515         // Optimize cases that will turn into an LEA instruction.  This requires
21516         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21517         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21518           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21519           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21520
21521           bool isFastMultiplier = false;
21522           if (Diff < 10) {
21523             switch ((unsigned char)Diff) {
21524               default: break;
21525               case 1:  // result = add base, cond
21526               case 2:  // result = lea base(    , cond*2)
21527               case 3:  // result = lea base(cond, cond*2)
21528               case 4:  // result = lea base(    , cond*4)
21529               case 5:  // result = lea base(cond, cond*4)
21530               case 8:  // result = lea base(    , cond*8)
21531               case 9:  // result = lea base(cond, cond*8)
21532                 isFastMultiplier = true;
21533                 break;
21534             }
21535           }
21536
21537           if (isFastMultiplier) {
21538             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21539             if (NeedsCondInvert) // Invert the condition if needed.
21540               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21541                                  DAG.getConstant(1, DL, Cond.getValueType()));
21542
21543             // Zero extend the condition if needed.
21544             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21545                                Cond);
21546             // Scale the condition by the difference.
21547             if (Diff != 1)
21548               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21549                                  DAG.getConstant(Diff, DL,
21550                                                  Cond.getValueType()));
21551
21552             // Add the base if non-zero.
21553             if (FalseC->getAPIntValue() != 0)
21554               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21555                                  SDValue(FalseC, 0));
21556             return Cond;
21557           }
21558         }
21559       }
21560   }
21561
21562   // Canonicalize max and min:
21563   // (x > y) ? x : y -> (x >= y) ? x : y
21564   // (x < y) ? x : y -> (x <= y) ? x : y
21565   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21566   // the need for an extra compare
21567   // against zero. e.g.
21568   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21569   // subl   %esi, %edi
21570   // testl  %edi, %edi
21571   // movl   $0, %eax
21572   // cmovgl %edi, %eax
21573   // =>
21574   // xorl   %eax, %eax
21575   // subl   %esi, $edi
21576   // cmovsl %eax, %edi
21577   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21578       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21579       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21580     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21581     switch (CC) {
21582     default: break;
21583     case ISD::SETLT:
21584     case ISD::SETGT: {
21585       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21586       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21587                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21588       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21589     }
21590     }
21591   }
21592
21593   // Early exit check
21594   if (!TLI.isTypeLegal(VT))
21595     return SDValue();
21596
21597   // Match VSELECTs into subs with unsigned saturation.
21598   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21599       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21600       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21601        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21602     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21603
21604     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21605     // left side invert the predicate to simplify logic below.
21606     SDValue Other;
21607     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21608       Other = RHS;
21609       CC = ISD::getSetCCInverse(CC, true);
21610     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21611       Other = LHS;
21612     }
21613
21614     if (Other.getNode() && Other->getNumOperands() == 2 &&
21615         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21616       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21617       SDValue CondRHS = Cond->getOperand(1);
21618
21619       // Look for a general sub with unsigned saturation first.
21620       // x >= y ? x-y : 0 --> subus x, y
21621       // x >  y ? x-y : 0 --> subus x, y
21622       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21623           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21624         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21625
21626       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21627         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21628           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21629             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21630               // If the RHS is a constant we have to reverse the const
21631               // canonicalization.
21632               // x > C-1 ? x+-C : 0 --> subus x, C
21633               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21634                   CondRHSConst->getAPIntValue() ==
21635                       (-OpRHSConst->getAPIntValue() - 1))
21636                 return DAG.getNode(
21637                     X86ISD::SUBUS, DL, VT, OpLHS,
21638                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21639
21640           // Another special case: If C was a sign bit, the sub has been
21641           // canonicalized into a xor.
21642           // FIXME: Would it be better to use computeKnownBits to determine
21643           //        whether it's safe to decanonicalize the xor?
21644           // x s< 0 ? x^C : 0 --> subus x, C
21645           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21646               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21647               OpRHSConst->getAPIntValue().isSignBit())
21648             // Note that we have to rebuild the RHS constant here to ensure we
21649             // don't rely on particular values of undef lanes.
21650             return DAG.getNode(
21651                 X86ISD::SUBUS, DL, VT, OpLHS,
21652                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21653         }
21654     }
21655   }
21656
21657   // Try to match a min/max vector operation.
21658   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21659     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21660     unsigned Opc = ret.first;
21661     bool NeedSplit = ret.second;
21662
21663     if (Opc && NeedSplit) {
21664       unsigned NumElems = VT.getVectorNumElements();
21665       // Extract the LHS vectors
21666       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21667       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21668
21669       // Extract the RHS vectors
21670       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21671       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21672
21673       // Create min/max for each subvector
21674       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21675       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21676
21677       // Merge the result
21678       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21679     } else if (Opc)
21680       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21681   }
21682
21683   // Simplify vector selection if condition value type matches vselect
21684   // operand type
21685   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21686     assert(Cond.getValueType().isVector() &&
21687            "vector select expects a vector selector!");
21688
21689     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21690     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21691
21692     // Try invert the condition if true value is not all 1s and false value
21693     // is not all 0s.
21694     if (!TValIsAllOnes && !FValIsAllZeros &&
21695         // Check if the selector will be produced by CMPP*/PCMP*
21696         Cond.getOpcode() == ISD::SETCC &&
21697         // Check if SETCC has already been promoted
21698         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21699       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21700       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21701
21702       if (TValIsAllZeros || FValIsAllOnes) {
21703         SDValue CC = Cond.getOperand(2);
21704         ISD::CondCode NewCC =
21705           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21706                                Cond.getOperand(0).getValueType().isInteger());
21707         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21708         std::swap(LHS, RHS);
21709         TValIsAllOnes = FValIsAllOnes;
21710         FValIsAllZeros = TValIsAllZeros;
21711       }
21712     }
21713
21714     if (TValIsAllOnes || FValIsAllZeros) {
21715       SDValue Ret;
21716
21717       if (TValIsAllOnes && FValIsAllZeros)
21718         Ret = Cond;
21719       else if (TValIsAllOnes)
21720         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21721                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21722       else if (FValIsAllZeros)
21723         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21724                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21725
21726       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21727     }
21728   }
21729
21730   // We should generate an X86ISD::BLENDI from a vselect if its argument
21731   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21732   // constants. This specific pattern gets generated when we split a
21733   // selector for a 512 bit vector in a machine without AVX512 (but with
21734   // 256-bit vectors), during legalization:
21735   //
21736   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21737   //
21738   // Iff we find this pattern and the build_vectors are built from
21739   // constants, we translate the vselect into a shuffle_vector that we
21740   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21741   if ((N->getOpcode() == ISD::VSELECT ||
21742        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21743       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
21744     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21745     if (Shuffle.getNode())
21746       return Shuffle;
21747   }
21748
21749   // If this is a *dynamic* select (non-constant condition) and we can match
21750   // this node with one of the variable blend instructions, restructure the
21751   // condition so that the blends can use the high bit of each element and use
21752   // SimplifyDemandedBits to simplify the condition operand.
21753   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21754       !DCI.isBeforeLegalize() &&
21755       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21756     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21757
21758     // Don't optimize vector selects that map to mask-registers.
21759     if (BitWidth == 1)
21760       return SDValue();
21761
21762     // We can only handle the cases where VSELECT is directly legal on the
21763     // subtarget. We custom lower VSELECT nodes with constant conditions and
21764     // this makes it hard to see whether a dynamic VSELECT will correctly
21765     // lower, so we both check the operation's status and explicitly handle the
21766     // cases where a *dynamic* blend will fail even though a constant-condition
21767     // blend could be custom lowered.
21768     // FIXME: We should find a better way to handle this class of problems.
21769     // Potentially, we should combine constant-condition vselect nodes
21770     // pre-legalization into shuffles and not mark as many types as custom
21771     // lowered.
21772     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21773       return SDValue();
21774     // FIXME: We don't support i16-element blends currently. We could and
21775     // should support them by making *all* the bits in the condition be set
21776     // rather than just the high bit and using an i8-element blend.
21777     if (VT.getScalarType() == MVT::i16)
21778       return SDValue();
21779     // Dynamic blending was only available from SSE4.1 onward.
21780     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21781       return SDValue();
21782     // Byte blends are only available in AVX2
21783     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21784         !Subtarget->hasAVX2())
21785       return SDValue();
21786
21787     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21788     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21789
21790     APInt KnownZero, KnownOne;
21791     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21792                                           DCI.isBeforeLegalizeOps());
21793     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21794         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21795                                  TLO)) {
21796       // If we changed the computation somewhere in the DAG, this change
21797       // will affect all users of Cond.
21798       // Make sure it is fine and update all the nodes so that we do not
21799       // use the generic VSELECT anymore. Otherwise, we may perform
21800       // wrong optimizations as we messed up with the actual expectation
21801       // for the vector boolean values.
21802       if (Cond != TLO.Old) {
21803         // Check all uses of that condition operand to check whether it will be
21804         // consumed by non-BLEND instructions, which may depend on all bits are
21805         // set properly.
21806         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21807              I != E; ++I)
21808           if (I->getOpcode() != ISD::VSELECT)
21809             // TODO: Add other opcodes eventually lowered into BLEND.
21810             return SDValue();
21811
21812         // Update all the users of the condition, before committing the change,
21813         // so that the VSELECT optimizations that expect the correct vector
21814         // boolean value will not be triggered.
21815         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21816              I != E; ++I)
21817           DAG.ReplaceAllUsesOfValueWith(
21818               SDValue(*I, 0),
21819               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21820                           Cond, I->getOperand(1), I->getOperand(2)));
21821         DCI.CommitTargetLoweringOpt(TLO);
21822         return SDValue();
21823       }
21824       // At this point, only Cond is changed. Change the condition
21825       // just for N to keep the opportunity to optimize all other
21826       // users their own way.
21827       DAG.ReplaceAllUsesOfValueWith(
21828           SDValue(N, 0),
21829           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21830                       TLO.New, N->getOperand(1), N->getOperand(2)));
21831       return SDValue();
21832     }
21833   }
21834
21835   return SDValue();
21836 }
21837
21838 // Check whether a boolean test is testing a boolean value generated by
21839 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21840 // code.
21841 //
21842 // Simplify the following patterns:
21843 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21844 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21845 // to (Op EFLAGS Cond)
21846 //
21847 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21848 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21849 // to (Op EFLAGS !Cond)
21850 //
21851 // where Op could be BRCOND or CMOV.
21852 //
21853 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21854   // Quit if not CMP and SUB with its value result used.
21855   if (Cmp.getOpcode() != X86ISD::CMP &&
21856       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21857       return SDValue();
21858
21859   // Quit if not used as a boolean value.
21860   if (CC != X86::COND_E && CC != X86::COND_NE)
21861     return SDValue();
21862
21863   // Check CMP operands. One of them should be 0 or 1 and the other should be
21864   // an SetCC or extended from it.
21865   SDValue Op1 = Cmp.getOperand(0);
21866   SDValue Op2 = Cmp.getOperand(1);
21867
21868   SDValue SetCC;
21869   const ConstantSDNode* C = nullptr;
21870   bool needOppositeCond = (CC == X86::COND_E);
21871   bool checkAgainstTrue = false; // Is it a comparison against 1?
21872
21873   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21874     SetCC = Op2;
21875   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21876     SetCC = Op1;
21877   else // Quit if all operands are not constants.
21878     return SDValue();
21879
21880   if (C->getZExtValue() == 1) {
21881     needOppositeCond = !needOppositeCond;
21882     checkAgainstTrue = true;
21883   } else if (C->getZExtValue() != 0)
21884     // Quit if the constant is neither 0 or 1.
21885     return SDValue();
21886
21887   bool truncatedToBoolWithAnd = false;
21888   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21889   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21890          SetCC.getOpcode() == ISD::TRUNCATE ||
21891          SetCC.getOpcode() == ISD::AND) {
21892     if (SetCC.getOpcode() == ISD::AND) {
21893       int OpIdx = -1;
21894       ConstantSDNode *CS;
21895       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21896           CS->getZExtValue() == 1)
21897         OpIdx = 1;
21898       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21899           CS->getZExtValue() == 1)
21900         OpIdx = 0;
21901       if (OpIdx == -1)
21902         break;
21903       SetCC = SetCC.getOperand(OpIdx);
21904       truncatedToBoolWithAnd = true;
21905     } else
21906       SetCC = SetCC.getOperand(0);
21907   }
21908
21909   switch (SetCC.getOpcode()) {
21910   case X86ISD::SETCC_CARRY:
21911     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21912     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21913     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21914     // truncated to i1 using 'and'.
21915     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21916       break;
21917     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21918            "Invalid use of SETCC_CARRY!");
21919     // FALL THROUGH
21920   case X86ISD::SETCC:
21921     // Set the condition code or opposite one if necessary.
21922     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21923     if (needOppositeCond)
21924       CC = X86::GetOppositeBranchCondition(CC);
21925     return SetCC.getOperand(1);
21926   case X86ISD::CMOV: {
21927     // Check whether false/true value has canonical one, i.e. 0 or 1.
21928     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21929     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21930     // Quit if true value is not a constant.
21931     if (!TVal)
21932       return SDValue();
21933     // Quit if false value is not a constant.
21934     if (!FVal) {
21935       SDValue Op = SetCC.getOperand(0);
21936       // Skip 'zext' or 'trunc' node.
21937       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21938           Op.getOpcode() == ISD::TRUNCATE)
21939         Op = Op.getOperand(0);
21940       // A special case for rdrand/rdseed, where 0 is set if false cond is
21941       // found.
21942       if ((Op.getOpcode() != X86ISD::RDRAND &&
21943            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21944         return SDValue();
21945     }
21946     // Quit if false value is not the constant 0 or 1.
21947     bool FValIsFalse = true;
21948     if (FVal && FVal->getZExtValue() != 0) {
21949       if (FVal->getZExtValue() != 1)
21950         return SDValue();
21951       // If FVal is 1, opposite cond is needed.
21952       needOppositeCond = !needOppositeCond;
21953       FValIsFalse = false;
21954     }
21955     // Quit if TVal is not the constant opposite of FVal.
21956     if (FValIsFalse && TVal->getZExtValue() != 1)
21957       return SDValue();
21958     if (!FValIsFalse && TVal->getZExtValue() != 0)
21959       return SDValue();
21960     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21961     if (needOppositeCond)
21962       CC = X86::GetOppositeBranchCondition(CC);
21963     return SetCC.getOperand(3);
21964   }
21965   }
21966
21967   return SDValue();
21968 }
21969
21970 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21971 /// Match:
21972 ///   (X86or (X86setcc) (X86setcc))
21973 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21974 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21975                                            X86::CondCode &CC1, SDValue &Flags,
21976                                            bool &isAnd) {
21977   if (Cond->getOpcode() == X86ISD::CMP) {
21978     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21979     if (!CondOp1C || !CondOp1C->isNullValue())
21980       return false;
21981
21982     Cond = Cond->getOperand(0);
21983   }
21984
21985   isAnd = false;
21986
21987   SDValue SetCC0, SetCC1;
21988   switch (Cond->getOpcode()) {
21989   default: return false;
21990   case ISD::AND:
21991   case X86ISD::AND:
21992     isAnd = true;
21993     // fallthru
21994   case ISD::OR:
21995   case X86ISD::OR:
21996     SetCC0 = Cond->getOperand(0);
21997     SetCC1 = Cond->getOperand(1);
21998     break;
21999   };
22000
22001   // Make sure we have SETCC nodes, using the same flags value.
22002   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22003       SetCC1.getOpcode() != X86ISD::SETCC ||
22004       SetCC0->getOperand(1) != SetCC1->getOperand(1))
22005     return false;
22006
22007   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22008   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22009   Flags = SetCC0->getOperand(1);
22010   return true;
22011 }
22012
22013 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22014 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22015                                   TargetLowering::DAGCombinerInfo &DCI,
22016                                   const X86Subtarget *Subtarget) {
22017   SDLoc DL(N);
22018
22019   // If the flag operand isn't dead, don't touch this CMOV.
22020   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22021     return SDValue();
22022
22023   SDValue FalseOp = N->getOperand(0);
22024   SDValue TrueOp = N->getOperand(1);
22025   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22026   SDValue Cond = N->getOperand(3);
22027
22028   if (CC == X86::COND_E || CC == X86::COND_NE) {
22029     switch (Cond.getOpcode()) {
22030     default: break;
22031     case X86ISD::BSR:
22032     case X86ISD::BSF:
22033       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22034       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22035         return (CC == X86::COND_E) ? FalseOp : TrueOp;
22036     }
22037   }
22038
22039   SDValue Flags;
22040
22041   Flags = checkBoolTestSetCCCombine(Cond, CC);
22042   if (Flags.getNode() &&
22043       // Extra check as FCMOV only supports a subset of X86 cond.
22044       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22045     SDValue Ops[] = { FalseOp, TrueOp,
22046                       DAG.getConstant(CC, DL, MVT::i8), Flags };
22047     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22048   }
22049
22050   // If this is a select between two integer constants, try to do some
22051   // optimizations.  Note that the operands are ordered the opposite of SELECT
22052   // operands.
22053   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22054     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22055       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22056       // larger than FalseC (the false value).
22057       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22058         CC = X86::GetOppositeBranchCondition(CC);
22059         std::swap(TrueC, FalseC);
22060         std::swap(TrueOp, FalseOp);
22061       }
22062
22063       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22064       // This is efficient for any integer data type (including i8/i16) and
22065       // shift amount.
22066       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22067         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22068                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22069
22070         // Zero extend the condition if needed.
22071         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22072
22073         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22074         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22075                            DAG.getConstant(ShAmt, DL, MVT::i8));
22076         if (N->getNumValues() == 2)  // Dead flag value?
22077           return DCI.CombineTo(N, Cond, SDValue());
22078         return Cond;
22079       }
22080
22081       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22082       // for any integer data type, including i8/i16.
22083       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22084         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22085                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22086
22087         // Zero extend the condition if needed.
22088         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22089                            FalseC->getValueType(0), Cond);
22090         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22091                            SDValue(FalseC, 0));
22092
22093         if (N->getNumValues() == 2)  // Dead flag value?
22094           return DCI.CombineTo(N, Cond, SDValue());
22095         return Cond;
22096       }
22097
22098       // Optimize cases that will turn into an LEA instruction.  This requires
22099       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22100       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22101         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22102         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22103
22104         bool isFastMultiplier = false;
22105         if (Diff < 10) {
22106           switch ((unsigned char)Diff) {
22107           default: break;
22108           case 1:  // result = add base, cond
22109           case 2:  // result = lea base(    , cond*2)
22110           case 3:  // result = lea base(cond, cond*2)
22111           case 4:  // result = lea base(    , cond*4)
22112           case 5:  // result = lea base(cond, cond*4)
22113           case 8:  // result = lea base(    , cond*8)
22114           case 9:  // result = lea base(cond, cond*8)
22115             isFastMultiplier = true;
22116             break;
22117           }
22118         }
22119
22120         if (isFastMultiplier) {
22121           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22122           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22123                              DAG.getConstant(CC, DL, MVT::i8), Cond);
22124           // Zero extend the condition if needed.
22125           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22126                              Cond);
22127           // Scale the condition by the difference.
22128           if (Diff != 1)
22129             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22130                                DAG.getConstant(Diff, DL, Cond.getValueType()));
22131
22132           // Add the base if non-zero.
22133           if (FalseC->getAPIntValue() != 0)
22134             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22135                                SDValue(FalseC, 0));
22136           if (N->getNumValues() == 2)  // Dead flag value?
22137             return DCI.CombineTo(N, Cond, SDValue());
22138           return Cond;
22139         }
22140       }
22141     }
22142   }
22143
22144   // Handle these cases:
22145   //   (select (x != c), e, c) -> select (x != c), e, x),
22146   //   (select (x == c), c, e) -> select (x == c), x, e)
22147   // where the c is an integer constant, and the "select" is the combination
22148   // of CMOV and CMP.
22149   //
22150   // The rationale for this change is that the conditional-move from a constant
22151   // needs two instructions, however, conditional-move from a register needs
22152   // only one instruction.
22153   //
22154   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22155   //  some instruction-combining opportunities. This opt needs to be
22156   //  postponed as late as possible.
22157   //
22158   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22159     // the DCI.xxxx conditions are provided to postpone the optimization as
22160     // late as possible.
22161
22162     ConstantSDNode *CmpAgainst = nullptr;
22163     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22164         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22165         !isa<ConstantSDNode>(Cond.getOperand(0))) {
22166
22167       if (CC == X86::COND_NE &&
22168           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22169         CC = X86::GetOppositeBranchCondition(CC);
22170         std::swap(TrueOp, FalseOp);
22171       }
22172
22173       if (CC == X86::COND_E &&
22174           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22175         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22176                           DAG.getConstant(CC, DL, MVT::i8), Cond };
22177         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22178       }
22179     }
22180   }
22181
22182   // Fold and/or of setcc's to double CMOV:
22183   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22184   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22185   //
22186   // This combine lets us generate:
22187   //   cmovcc1 (jcc1 if we don't have CMOV)
22188   //   cmovcc2 (same)
22189   // instead of:
22190   //   setcc1
22191   //   setcc2
22192   //   and/or
22193   //   cmovne (jne if we don't have CMOV)
22194   // When we can't use the CMOV instruction, it might increase branch
22195   // mispredicts.
22196   // When we can use CMOV, or when there is no mispredict, this improves
22197   // throughput and reduces register pressure.
22198   //
22199   if (CC == X86::COND_NE) {
22200     SDValue Flags;
22201     X86::CondCode CC0, CC1;
22202     bool isAndSetCC;
22203     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22204       if (isAndSetCC) {
22205         std::swap(FalseOp, TrueOp);
22206         CC0 = X86::GetOppositeBranchCondition(CC0);
22207         CC1 = X86::GetOppositeBranchCondition(CC1);
22208       }
22209
22210       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22211         Flags};
22212       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22213       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22214       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22215       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22216       return CMOV;
22217     }
22218   }
22219
22220   return SDValue();
22221 }
22222
22223 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22224                                                 const X86Subtarget *Subtarget) {
22225   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22226   switch (IntNo) {
22227   default: return SDValue();
22228   // SSE/AVX/AVX2 blend intrinsics.
22229   case Intrinsic::x86_avx2_pblendvb:
22230     // Don't try to simplify this intrinsic if we don't have AVX2.
22231     if (!Subtarget->hasAVX2())
22232       return SDValue();
22233     // FALL-THROUGH
22234   case Intrinsic::x86_avx_blendv_pd_256:
22235   case Intrinsic::x86_avx_blendv_ps_256:
22236     // Don't try to simplify this intrinsic if we don't have AVX.
22237     if (!Subtarget->hasAVX())
22238       return SDValue();
22239     // FALL-THROUGH
22240   case Intrinsic::x86_sse41_blendvps:
22241   case Intrinsic::x86_sse41_blendvpd:
22242   case Intrinsic::x86_sse41_pblendvb: {
22243     SDValue Op0 = N->getOperand(1);
22244     SDValue Op1 = N->getOperand(2);
22245     SDValue Mask = N->getOperand(3);
22246
22247     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22248     if (!Subtarget->hasSSE41())
22249       return SDValue();
22250
22251     // fold (blend A, A, Mask) -> A
22252     if (Op0 == Op1)
22253       return Op0;
22254     // fold (blend A, B, allZeros) -> A
22255     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22256       return Op0;
22257     // fold (blend A, B, allOnes) -> B
22258     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22259       return Op1;
22260
22261     // Simplify the case where the mask is a constant i32 value.
22262     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22263       if (C->isNullValue())
22264         return Op0;
22265       if (C->isAllOnesValue())
22266         return Op1;
22267     }
22268
22269     return SDValue();
22270   }
22271
22272   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22273   case Intrinsic::x86_sse2_psrai_w:
22274   case Intrinsic::x86_sse2_psrai_d:
22275   case Intrinsic::x86_avx2_psrai_w:
22276   case Intrinsic::x86_avx2_psrai_d:
22277   case Intrinsic::x86_sse2_psra_w:
22278   case Intrinsic::x86_sse2_psra_d:
22279   case Intrinsic::x86_avx2_psra_w:
22280   case Intrinsic::x86_avx2_psra_d: {
22281     SDValue Op0 = N->getOperand(1);
22282     SDValue Op1 = N->getOperand(2);
22283     EVT VT = Op0.getValueType();
22284     assert(VT.isVector() && "Expected a vector type!");
22285
22286     if (isa<BuildVectorSDNode>(Op1))
22287       Op1 = Op1.getOperand(0);
22288
22289     if (!isa<ConstantSDNode>(Op1))
22290       return SDValue();
22291
22292     EVT SVT = VT.getVectorElementType();
22293     unsigned SVTBits = SVT.getSizeInBits();
22294
22295     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22296     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22297     uint64_t ShAmt = C.getZExtValue();
22298
22299     // Don't try to convert this shift into a ISD::SRA if the shift
22300     // count is bigger than or equal to the element size.
22301     if (ShAmt >= SVTBits)
22302       return SDValue();
22303
22304     // Trivial case: if the shift count is zero, then fold this
22305     // into the first operand.
22306     if (ShAmt == 0)
22307       return Op0;
22308
22309     // Replace this packed shift intrinsic with a target independent
22310     // shift dag node.
22311     SDLoc DL(N);
22312     SDValue Splat = DAG.getConstant(C, DL, VT);
22313     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22314   }
22315   }
22316 }
22317
22318 /// PerformMulCombine - Optimize a single multiply with constant into two
22319 /// in order to implement it with two cheaper instructions, e.g.
22320 /// LEA + SHL, LEA + LEA.
22321 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22322                                  TargetLowering::DAGCombinerInfo &DCI) {
22323   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22324     return SDValue();
22325
22326   EVT VT = N->getValueType(0);
22327   if (VT != MVT::i64 && VT != MVT::i32)
22328     return SDValue();
22329
22330   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22331   if (!C)
22332     return SDValue();
22333   uint64_t MulAmt = C->getZExtValue();
22334   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22335     return SDValue();
22336
22337   uint64_t MulAmt1 = 0;
22338   uint64_t MulAmt2 = 0;
22339   if ((MulAmt % 9) == 0) {
22340     MulAmt1 = 9;
22341     MulAmt2 = MulAmt / 9;
22342   } else if ((MulAmt % 5) == 0) {
22343     MulAmt1 = 5;
22344     MulAmt2 = MulAmt / 5;
22345   } else if ((MulAmt % 3) == 0) {
22346     MulAmt1 = 3;
22347     MulAmt2 = MulAmt / 3;
22348   }
22349   if (MulAmt2 &&
22350       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22351     SDLoc DL(N);
22352
22353     if (isPowerOf2_64(MulAmt2) &&
22354         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22355       // If second multiplifer is pow2, issue it first. We want the multiply by
22356       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22357       // is an add.
22358       std::swap(MulAmt1, MulAmt2);
22359
22360     SDValue NewMul;
22361     if (isPowerOf2_64(MulAmt1))
22362       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22363                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22364     else
22365       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22366                            DAG.getConstant(MulAmt1, DL, VT));
22367
22368     if (isPowerOf2_64(MulAmt2))
22369       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22370                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22371     else
22372       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22373                            DAG.getConstant(MulAmt2, DL, VT));
22374
22375     // Do not add new nodes to DAG combiner worklist.
22376     DCI.CombineTo(N, NewMul, false);
22377   }
22378   return SDValue();
22379 }
22380
22381 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22382   SDValue N0 = N->getOperand(0);
22383   SDValue N1 = N->getOperand(1);
22384   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22385   EVT VT = N0.getValueType();
22386
22387   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22388   // since the result of setcc_c is all zero's or all ones.
22389   if (VT.isInteger() && !VT.isVector() &&
22390       N1C && N0.getOpcode() == ISD::AND &&
22391       N0.getOperand(1).getOpcode() == ISD::Constant) {
22392     SDValue N00 = N0.getOperand(0);
22393     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22394         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22395           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22396          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22397       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22398       APInt ShAmt = N1C->getAPIntValue();
22399       Mask = Mask.shl(ShAmt);
22400       if (Mask != 0) {
22401         SDLoc DL(N);
22402         return DAG.getNode(ISD::AND, DL, VT,
22403                            N00, DAG.getConstant(Mask, DL, VT));
22404       }
22405     }
22406   }
22407
22408   // Hardware support for vector shifts is sparse which makes us scalarize the
22409   // vector operations in many cases. Also, on sandybridge ADD is faster than
22410   // shl.
22411   // (shl V, 1) -> add V,V
22412   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22413     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22414       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22415       // We shift all of the values by one. In many cases we do not have
22416       // hardware support for this operation. This is better expressed as an ADD
22417       // of two values.
22418       if (N1SplatC->getZExtValue() == 1)
22419         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22420     }
22421
22422   return SDValue();
22423 }
22424
22425 /// \brief Returns a vector of 0s if the node in input is a vector logical
22426 /// shift by a constant amount which is known to be bigger than or equal
22427 /// to the vector element size in bits.
22428 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22429                                       const X86Subtarget *Subtarget) {
22430   EVT VT = N->getValueType(0);
22431
22432   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22433       (!Subtarget->hasInt256() ||
22434        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22435     return SDValue();
22436
22437   SDValue Amt = N->getOperand(1);
22438   SDLoc DL(N);
22439   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22440     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22441       APInt ShiftAmt = AmtSplat->getAPIntValue();
22442       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22443
22444       // SSE2/AVX2 logical shifts always return a vector of 0s
22445       // if the shift amount is bigger than or equal to
22446       // the element size. The constant shift amount will be
22447       // encoded as a 8-bit immediate.
22448       if (ShiftAmt.trunc(8).uge(MaxAmount))
22449         return getZeroVector(VT, Subtarget, DAG, DL);
22450     }
22451
22452   return SDValue();
22453 }
22454
22455 /// PerformShiftCombine - Combine shifts.
22456 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22457                                    TargetLowering::DAGCombinerInfo &DCI,
22458                                    const X86Subtarget *Subtarget) {
22459   if (N->getOpcode() == ISD::SHL) {
22460     SDValue V = PerformSHLCombine(N, DAG);
22461     if (V.getNode()) return V;
22462   }
22463
22464   if (N->getOpcode() != ISD::SRA) {
22465     // Try to fold this logical shift into a zero vector.
22466     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22467     if (V.getNode()) return V;
22468   }
22469
22470   return SDValue();
22471 }
22472
22473 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22474 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22475 // and friends.  Likewise for OR -> CMPNEQSS.
22476 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22477                             TargetLowering::DAGCombinerInfo &DCI,
22478                             const X86Subtarget *Subtarget) {
22479   unsigned opcode;
22480
22481   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22482   // we're requiring SSE2 for both.
22483   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22484     SDValue N0 = N->getOperand(0);
22485     SDValue N1 = N->getOperand(1);
22486     SDValue CMP0 = N0->getOperand(1);
22487     SDValue CMP1 = N1->getOperand(1);
22488     SDLoc DL(N);
22489
22490     // The SETCCs should both refer to the same CMP.
22491     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22492       return SDValue();
22493
22494     SDValue CMP00 = CMP0->getOperand(0);
22495     SDValue CMP01 = CMP0->getOperand(1);
22496     EVT     VT    = CMP00.getValueType();
22497
22498     if (VT == MVT::f32 || VT == MVT::f64) {
22499       bool ExpectingFlags = false;
22500       // Check for any users that want flags:
22501       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22502            !ExpectingFlags && UI != UE; ++UI)
22503         switch (UI->getOpcode()) {
22504         default:
22505         case ISD::BR_CC:
22506         case ISD::BRCOND:
22507         case ISD::SELECT:
22508           ExpectingFlags = true;
22509           break;
22510         case ISD::CopyToReg:
22511         case ISD::SIGN_EXTEND:
22512         case ISD::ZERO_EXTEND:
22513         case ISD::ANY_EXTEND:
22514           break;
22515         }
22516
22517       if (!ExpectingFlags) {
22518         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22519         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22520
22521         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22522           X86::CondCode tmp = cc0;
22523           cc0 = cc1;
22524           cc1 = tmp;
22525         }
22526
22527         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22528             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22529           // FIXME: need symbolic constants for these magic numbers.
22530           // See X86ATTInstPrinter.cpp:printSSECC().
22531           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22532           if (Subtarget->hasAVX512()) {
22533             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22534                                          CMP01,
22535                                          DAG.getConstant(x86cc, DL, MVT::i8));
22536             if (N->getValueType(0) != MVT::i1)
22537               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22538                                  FSetCC);
22539             return FSetCC;
22540           }
22541           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22542                                               CMP00.getValueType(), CMP00, CMP01,
22543                                               DAG.getConstant(x86cc, DL,
22544                                                               MVT::i8));
22545
22546           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22547           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22548
22549           if (is64BitFP && !Subtarget->is64Bit()) {
22550             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22551             // 64-bit integer, since that's not a legal type. Since
22552             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22553             // bits, but can do this little dance to extract the lowest 32 bits
22554             // and work with those going forward.
22555             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22556                                            OnesOrZeroesF);
22557             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22558                                            Vector64);
22559             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22560                                         Vector32, DAG.getIntPtrConstant(0, DL));
22561             IntVT = MVT::i32;
22562           }
22563
22564           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22565                                               OnesOrZeroesF);
22566           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22567                                       DAG.getConstant(1, DL, IntVT));
22568           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22569                                               ANDed);
22570           return OneBitOfTruth;
22571         }
22572       }
22573     }
22574   }
22575   return SDValue();
22576 }
22577
22578 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22579 /// so it can be folded inside ANDNP.
22580 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22581   EVT VT = N->getValueType(0);
22582
22583   // Match direct AllOnes for 128 and 256-bit vectors
22584   if (ISD::isBuildVectorAllOnes(N))
22585     return true;
22586
22587   // Look through a bit convert.
22588   if (N->getOpcode() == ISD::BITCAST)
22589     N = N->getOperand(0).getNode();
22590
22591   // Sometimes the operand may come from a insert_subvector building a 256-bit
22592   // allones vector
22593   if (VT.is256BitVector() &&
22594       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22595     SDValue V1 = N->getOperand(0);
22596     SDValue V2 = N->getOperand(1);
22597
22598     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22599         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22600         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22601         ISD::isBuildVectorAllOnes(V2.getNode()))
22602       return true;
22603   }
22604
22605   return false;
22606 }
22607
22608 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22609 // register. In most cases we actually compare or select YMM-sized registers
22610 // and mixing the two types creates horrible code. This method optimizes
22611 // some of the transition sequences.
22612 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22613                                  TargetLowering::DAGCombinerInfo &DCI,
22614                                  const X86Subtarget *Subtarget) {
22615   EVT VT = N->getValueType(0);
22616   if (!VT.is256BitVector())
22617     return SDValue();
22618
22619   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22620           N->getOpcode() == ISD::ZERO_EXTEND ||
22621           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22622
22623   SDValue Narrow = N->getOperand(0);
22624   EVT NarrowVT = Narrow->getValueType(0);
22625   if (!NarrowVT.is128BitVector())
22626     return SDValue();
22627
22628   if (Narrow->getOpcode() != ISD::XOR &&
22629       Narrow->getOpcode() != ISD::AND &&
22630       Narrow->getOpcode() != ISD::OR)
22631     return SDValue();
22632
22633   SDValue N0  = Narrow->getOperand(0);
22634   SDValue N1  = Narrow->getOperand(1);
22635   SDLoc DL(Narrow);
22636
22637   // The Left side has to be a trunc.
22638   if (N0.getOpcode() != ISD::TRUNCATE)
22639     return SDValue();
22640
22641   // The type of the truncated inputs.
22642   EVT WideVT = N0->getOperand(0)->getValueType(0);
22643   if (WideVT != VT)
22644     return SDValue();
22645
22646   // The right side has to be a 'trunc' or a constant vector.
22647   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22648   ConstantSDNode *RHSConstSplat = nullptr;
22649   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22650     RHSConstSplat = RHSBV->getConstantSplatNode();
22651   if (!RHSTrunc && !RHSConstSplat)
22652     return SDValue();
22653
22654   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22655
22656   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22657     return SDValue();
22658
22659   // Set N0 and N1 to hold the inputs to the new wide operation.
22660   N0 = N0->getOperand(0);
22661   if (RHSConstSplat) {
22662     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22663                      SDValue(RHSConstSplat, 0));
22664     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22665     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22666   } else if (RHSTrunc) {
22667     N1 = N1->getOperand(0);
22668   }
22669
22670   // Generate the wide operation.
22671   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22672   unsigned Opcode = N->getOpcode();
22673   switch (Opcode) {
22674   case ISD::ANY_EXTEND:
22675     return Op;
22676   case ISD::ZERO_EXTEND: {
22677     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22678     APInt Mask = APInt::getAllOnesValue(InBits);
22679     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22680     return DAG.getNode(ISD::AND, DL, VT,
22681                        Op, DAG.getConstant(Mask, DL, VT));
22682   }
22683   case ISD::SIGN_EXTEND:
22684     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22685                        Op, DAG.getValueType(NarrowVT));
22686   default:
22687     llvm_unreachable("Unexpected opcode");
22688   }
22689 }
22690
22691 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22692                                  TargetLowering::DAGCombinerInfo &DCI,
22693                                  const X86Subtarget *Subtarget) {
22694   SDValue N0 = N->getOperand(0);
22695   SDValue N1 = N->getOperand(1);
22696   SDLoc DL(N);
22697
22698   // A vector zext_in_reg may be represented as a shuffle,
22699   // feeding into a bitcast (this represents anyext) feeding into
22700   // an and with a mask.
22701   // We'd like to try to combine that into a shuffle with zero
22702   // plus a bitcast, removing the and.
22703   if (N0.getOpcode() != ISD::BITCAST ||
22704       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22705     return SDValue();
22706
22707   // The other side of the AND should be a splat of 2^C, where C
22708   // is the number of bits in the source type.
22709   if (N1.getOpcode() == ISD::BITCAST)
22710     N1 = N1.getOperand(0);
22711   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22712     return SDValue();
22713   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22714
22715   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22716   EVT SrcType = Shuffle->getValueType(0);
22717
22718   // We expect a single-source shuffle
22719   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22720     return SDValue();
22721
22722   unsigned SrcSize = SrcType.getScalarSizeInBits();
22723
22724   APInt SplatValue, SplatUndef;
22725   unsigned SplatBitSize;
22726   bool HasAnyUndefs;
22727   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22728                                 SplatBitSize, HasAnyUndefs))
22729     return SDValue();
22730
22731   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22732   // Make sure the splat matches the mask we expect
22733   if (SplatBitSize > ResSize ||
22734       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22735     return SDValue();
22736
22737   // Make sure the input and output size make sense
22738   if (SrcSize >= ResSize || ResSize % SrcSize)
22739     return SDValue();
22740
22741   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22742   // The number of u's between each two values depends on the ratio between
22743   // the source and dest type.
22744   unsigned ZextRatio = ResSize / SrcSize;
22745   bool IsZext = true;
22746   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22747     if (i % ZextRatio) {
22748       if (Shuffle->getMaskElt(i) > 0) {
22749         // Expected undef
22750         IsZext = false;
22751         break;
22752       }
22753     } else {
22754       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22755         // Expected element number
22756         IsZext = false;
22757         break;
22758       }
22759     }
22760   }
22761
22762   if (!IsZext)
22763     return SDValue();
22764
22765   // Ok, perform the transformation - replace the shuffle with
22766   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22767   // (instead of undef) where the k elements come from the zero vector.
22768   SmallVector<int, 8> Mask;
22769   unsigned NumElems = SrcType.getVectorNumElements();
22770   for (unsigned i = 0; i < NumElems; ++i)
22771     if (i % ZextRatio)
22772       Mask.push_back(NumElems);
22773     else
22774       Mask.push_back(i / ZextRatio);
22775
22776   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22777     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22778   return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22779 }
22780
22781 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22782                                  TargetLowering::DAGCombinerInfo &DCI,
22783                                  const X86Subtarget *Subtarget) {
22784   if (DCI.isBeforeLegalizeOps())
22785     return SDValue();
22786
22787   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22788     return Zext;
22789
22790   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22791     return R;
22792
22793   EVT VT = N->getValueType(0);
22794   SDValue N0 = N->getOperand(0);
22795   SDValue N1 = N->getOperand(1);
22796   SDLoc DL(N);
22797
22798   // Create BEXTR instructions
22799   // BEXTR is ((X >> imm) & (2**size-1))
22800   if (VT == MVT::i32 || VT == MVT::i64) {
22801     // Check for BEXTR.
22802     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22803         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22804       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22805       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22806       if (MaskNode && ShiftNode) {
22807         uint64_t Mask = MaskNode->getZExtValue();
22808         uint64_t Shift = ShiftNode->getZExtValue();
22809         if (isMask_64(Mask)) {
22810           uint64_t MaskSize = countPopulation(Mask);
22811           if (Shift + MaskSize <= VT.getSizeInBits())
22812             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22813                                DAG.getConstant(Shift | (MaskSize << 8), DL,
22814                                                VT));
22815         }
22816       }
22817     } // BEXTR
22818
22819     return SDValue();
22820   }
22821
22822   // Want to form ANDNP nodes:
22823   // 1) In the hopes of then easily combining them with OR and AND nodes
22824   //    to form PBLEND/PSIGN.
22825   // 2) To match ANDN packed intrinsics
22826   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22827     return SDValue();
22828
22829   // Check LHS for vnot
22830   if (N0.getOpcode() == ISD::XOR &&
22831       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22832       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22833     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22834
22835   // Check RHS for vnot
22836   if (N1.getOpcode() == ISD::XOR &&
22837       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22838       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22839     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22840
22841   return SDValue();
22842 }
22843
22844 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22845                                 TargetLowering::DAGCombinerInfo &DCI,
22846                                 const X86Subtarget *Subtarget) {
22847   if (DCI.isBeforeLegalizeOps())
22848     return SDValue();
22849
22850   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22851   if (R.getNode())
22852     return R;
22853
22854   SDValue N0 = N->getOperand(0);
22855   SDValue N1 = N->getOperand(1);
22856   EVT VT = N->getValueType(0);
22857
22858   // look for psign/blend
22859   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22860     if (!Subtarget->hasSSSE3() ||
22861         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22862       return SDValue();
22863
22864     // Canonicalize pandn to RHS
22865     if (N0.getOpcode() == X86ISD::ANDNP)
22866       std::swap(N0, N1);
22867     // or (and (m, y), (pandn m, x))
22868     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22869       SDValue Mask = N1.getOperand(0);
22870       SDValue X    = N1.getOperand(1);
22871       SDValue Y;
22872       if (N0.getOperand(0) == Mask)
22873         Y = N0.getOperand(1);
22874       if (N0.getOperand(1) == Mask)
22875         Y = N0.getOperand(0);
22876
22877       // Check to see if the mask appeared in both the AND and ANDNP and
22878       if (!Y.getNode())
22879         return SDValue();
22880
22881       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22882       // Look through mask bitcast.
22883       if (Mask.getOpcode() == ISD::BITCAST)
22884         Mask = Mask.getOperand(0);
22885       if (X.getOpcode() == ISD::BITCAST)
22886         X = X.getOperand(0);
22887       if (Y.getOpcode() == ISD::BITCAST)
22888         Y = Y.getOperand(0);
22889
22890       EVT MaskVT = Mask.getValueType();
22891
22892       // Validate that the Mask operand is a vector sra node.
22893       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22894       // there is no psrai.b
22895       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22896       unsigned SraAmt = ~0;
22897       if (Mask.getOpcode() == ISD::SRA) {
22898         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22899           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22900             SraAmt = AmtConst->getZExtValue();
22901       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22902         SDValue SraC = Mask.getOperand(1);
22903         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22904       }
22905       if ((SraAmt + 1) != EltBits)
22906         return SDValue();
22907
22908       SDLoc DL(N);
22909
22910       // Now we know we at least have a plendvb with the mask val.  See if
22911       // we can form a psignb/w/d.
22912       // psign = x.type == y.type == mask.type && y = sub(0, x);
22913       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22914           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22915           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22916         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22917                "Unsupported VT for PSIGN");
22918         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22919         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22920       }
22921       // PBLENDVB only available on SSE 4.1
22922       if (!Subtarget->hasSSE41())
22923         return SDValue();
22924
22925       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22926
22927       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22928       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22929       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22930       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22931       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22932     }
22933   }
22934
22935   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22936     return SDValue();
22937
22938   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22939   MachineFunction &MF = DAG.getMachineFunction();
22940   bool OptForSize =
22941       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22942
22943   // SHLD/SHRD instructions have lower register pressure, but on some
22944   // platforms they have higher latency than the equivalent
22945   // series of shifts/or that would otherwise be generated.
22946   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22947   // have higher latencies and we are not optimizing for size.
22948   if (!OptForSize && Subtarget->isSHLDSlow())
22949     return SDValue();
22950
22951   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22952     std::swap(N0, N1);
22953   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22954     return SDValue();
22955   if (!N0.hasOneUse() || !N1.hasOneUse())
22956     return SDValue();
22957
22958   SDValue ShAmt0 = N0.getOperand(1);
22959   if (ShAmt0.getValueType() != MVT::i8)
22960     return SDValue();
22961   SDValue ShAmt1 = N1.getOperand(1);
22962   if (ShAmt1.getValueType() != MVT::i8)
22963     return SDValue();
22964   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22965     ShAmt0 = ShAmt0.getOperand(0);
22966   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22967     ShAmt1 = ShAmt1.getOperand(0);
22968
22969   SDLoc DL(N);
22970   unsigned Opc = X86ISD::SHLD;
22971   SDValue Op0 = N0.getOperand(0);
22972   SDValue Op1 = N1.getOperand(0);
22973   if (ShAmt0.getOpcode() == ISD::SUB) {
22974     Opc = X86ISD::SHRD;
22975     std::swap(Op0, Op1);
22976     std::swap(ShAmt0, ShAmt1);
22977   }
22978
22979   unsigned Bits = VT.getSizeInBits();
22980   if (ShAmt1.getOpcode() == ISD::SUB) {
22981     SDValue Sum = ShAmt1.getOperand(0);
22982     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22983       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22984       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22985         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22986       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22987         return DAG.getNode(Opc, DL, VT,
22988                            Op0, Op1,
22989                            DAG.getNode(ISD::TRUNCATE, DL,
22990                                        MVT::i8, ShAmt0));
22991     }
22992   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22993     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22994     if (ShAmt0C &&
22995         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22996       return DAG.getNode(Opc, DL, VT,
22997                          N0.getOperand(0), N1.getOperand(0),
22998                          DAG.getNode(ISD::TRUNCATE, DL,
22999                                        MVT::i8, ShAmt0));
23000   }
23001
23002   return SDValue();
23003 }
23004
23005 // Generate NEG and CMOV for integer abs.
23006 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23007   EVT VT = N->getValueType(0);
23008
23009   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23010   // 8-bit integer abs to NEG and CMOV.
23011   if (VT.isInteger() && VT.getSizeInBits() == 8)
23012     return SDValue();
23013
23014   SDValue N0 = N->getOperand(0);
23015   SDValue N1 = N->getOperand(1);
23016   SDLoc DL(N);
23017
23018   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23019   // and change it to SUB and CMOV.
23020   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23021       N0.getOpcode() == ISD::ADD &&
23022       N0.getOperand(1) == N1 &&
23023       N1.getOpcode() == ISD::SRA &&
23024       N1.getOperand(0) == N0.getOperand(0))
23025     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23026       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23027         // Generate SUB & CMOV.
23028         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23029                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
23030
23031         SDValue Ops[] = { N0.getOperand(0), Neg,
23032                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23033                           SDValue(Neg.getNode(), 1) };
23034         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23035       }
23036   return SDValue();
23037 }
23038
23039 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23040 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23041                                  TargetLowering::DAGCombinerInfo &DCI,
23042                                  const X86Subtarget *Subtarget) {
23043   if (DCI.isBeforeLegalizeOps())
23044     return SDValue();
23045
23046   if (Subtarget->hasCMov()) {
23047     SDValue RV = performIntegerAbsCombine(N, DAG);
23048     if (RV.getNode())
23049       return RV;
23050   }
23051
23052   return SDValue();
23053 }
23054
23055 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23056 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23057                                   TargetLowering::DAGCombinerInfo &DCI,
23058                                   const X86Subtarget *Subtarget) {
23059   LoadSDNode *Ld = cast<LoadSDNode>(N);
23060   EVT RegVT = Ld->getValueType(0);
23061   EVT MemVT = Ld->getMemoryVT();
23062   SDLoc dl(Ld);
23063   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23064
23065   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23066   // into two 16-byte operations.
23067   ISD::LoadExtType Ext = Ld->getExtensionType();
23068   unsigned Alignment = Ld->getAlignment();
23069   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23070   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23071       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23072     unsigned NumElems = RegVT.getVectorNumElements();
23073     if (NumElems < 2)
23074       return SDValue();
23075
23076     SDValue Ptr = Ld->getBasePtr();
23077     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
23078
23079     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23080                                   NumElems/2);
23081     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23082                                 Ld->getPointerInfo(), Ld->isVolatile(),
23083                                 Ld->isNonTemporal(), Ld->isInvariant(),
23084                                 Alignment);
23085     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23086     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23087                                 Ld->getPointerInfo(), Ld->isVolatile(),
23088                                 Ld->isNonTemporal(), Ld->isInvariant(),
23089                                 std::min(16U, Alignment));
23090     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23091                              Load1.getValue(1),
23092                              Load2.getValue(1));
23093
23094     SDValue NewVec = DAG.getUNDEF(RegVT);
23095     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23096     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23097     return DCI.CombineTo(N, NewVec, TF, true);
23098   }
23099
23100   return SDValue();
23101 }
23102
23103 /// PerformMLOADCombine - Resolve extending loads
23104 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23105                                    TargetLowering::DAGCombinerInfo &DCI,
23106                                    const X86Subtarget *Subtarget) {
23107   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23108   if (Mld->getExtensionType() != ISD::SEXTLOAD)
23109     return SDValue();
23110
23111   EVT VT = Mld->getValueType(0);
23112   unsigned NumElems = VT.getVectorNumElements();
23113   EVT LdVT = Mld->getMemoryVT();
23114   SDLoc dl(Mld);
23115
23116   assert(LdVT != VT && "Cannot extend to the same type");
23117   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23118   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23119   // From, To sizes and ElemCount must be pow of two
23120   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23121     "Unexpected size for extending masked load");
23122
23123   unsigned SizeRatio  = ToSz / FromSz;
23124   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23125
23126   // Create a type on which we perform the shuffle
23127   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23128           LdVT.getScalarType(), NumElems*SizeRatio);
23129   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23130
23131   // Convert Src0 value
23132   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
23133   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23134     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23135     for (unsigned i = 0; i != NumElems; ++i)
23136       ShuffleVec[i] = i * SizeRatio;
23137
23138     // Can't shuffle using an illegal type.
23139     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23140             && "WideVecVT should be legal");
23141     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23142                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23143   }
23144   // Prepare the new mask
23145   SDValue NewMask;
23146   SDValue Mask = Mld->getMask();
23147   if (Mask.getValueType() == VT) {
23148     // Mask and original value have the same type
23149     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23150     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23151     for (unsigned i = 0; i != NumElems; ++i)
23152       ShuffleVec[i] = i * SizeRatio;
23153     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23154       ShuffleVec[i] = NumElems*SizeRatio;
23155     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23156                                    DAG.getConstant(0, dl, WideVecVT),
23157                                    &ShuffleVec[0]);
23158   }
23159   else {
23160     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23161     unsigned WidenNumElts = NumElems*SizeRatio;
23162     unsigned MaskNumElts = VT.getVectorNumElements();
23163     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23164                                      WidenNumElts);
23165
23166     unsigned NumConcat = WidenNumElts / MaskNumElts;
23167     SmallVector<SDValue, 16> Ops(NumConcat);
23168     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23169     Ops[0] = Mask;
23170     for (unsigned i = 1; i != NumConcat; ++i)
23171       Ops[i] = ZeroVal;
23172
23173     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23174   }
23175
23176   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23177                                      Mld->getBasePtr(), NewMask, WideSrc0,
23178                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23179                                      ISD::NON_EXTLOAD);
23180   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23181   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23182
23183 }
23184 /// PerformMSTORECombine - Resolve truncating stores
23185 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23186                                     const X86Subtarget *Subtarget) {
23187   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23188   if (!Mst->isTruncatingStore())
23189     return SDValue();
23190
23191   EVT VT = Mst->getValue().getValueType();
23192   unsigned NumElems = VT.getVectorNumElements();
23193   EVT StVT = Mst->getMemoryVT();
23194   SDLoc dl(Mst);
23195
23196   assert(StVT != VT && "Cannot truncate to the same type");
23197   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23198   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23199
23200   // From, To sizes and ElemCount must be pow of two
23201   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23202     "Unexpected size for truncating masked store");
23203   // We are going to use the original vector elt for storing.
23204   // Accumulated smaller vector elements must be a multiple of the store size.
23205   assert (((NumElems * FromSz) % ToSz) == 0 &&
23206           "Unexpected ratio for truncating masked store");
23207
23208   unsigned SizeRatio  = FromSz / ToSz;
23209   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23210
23211   // Create a type on which we perform the shuffle
23212   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23213           StVT.getScalarType(), NumElems*SizeRatio);
23214
23215   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23216
23217   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23218   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23219   for (unsigned i = 0; i != NumElems; ++i)
23220     ShuffleVec[i] = i * SizeRatio;
23221
23222   // Can't shuffle using an illegal type.
23223   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23224           && "WideVecVT should be legal");
23225
23226   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23227                                         DAG.getUNDEF(WideVecVT),
23228                                         &ShuffleVec[0]);
23229
23230   SDValue NewMask;
23231   SDValue Mask = Mst->getMask();
23232   if (Mask.getValueType() == VT) {
23233     // Mask and original value have the same type
23234     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23235     for (unsigned i = 0; i != NumElems; ++i)
23236       ShuffleVec[i] = i * SizeRatio;
23237     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23238       ShuffleVec[i] = NumElems*SizeRatio;
23239     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23240                                    DAG.getConstant(0, dl, WideVecVT),
23241                                    &ShuffleVec[0]);
23242   }
23243   else {
23244     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23245     unsigned WidenNumElts = NumElems*SizeRatio;
23246     unsigned MaskNumElts = VT.getVectorNumElements();
23247     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23248                                      WidenNumElts);
23249
23250     unsigned NumConcat = WidenNumElts / MaskNumElts;
23251     SmallVector<SDValue, 16> Ops(NumConcat);
23252     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23253     Ops[0] = Mask;
23254     for (unsigned i = 1; i != NumConcat; ++i)
23255       Ops[i] = ZeroVal;
23256
23257     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23258   }
23259
23260   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23261                             NewMask, StVT, Mst->getMemOperand(), false);
23262 }
23263 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23264 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23265                                    const X86Subtarget *Subtarget) {
23266   StoreSDNode *St = cast<StoreSDNode>(N);
23267   EVT VT = St->getValue().getValueType();
23268   EVT StVT = St->getMemoryVT();
23269   SDLoc dl(St);
23270   SDValue StoredVal = St->getOperand(1);
23271   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23272
23273   // If we are saving a concatenation of two XMM registers and 32-byte stores
23274   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23275   unsigned Alignment = St->getAlignment();
23276   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23277   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23278       StVT == VT && !IsAligned) {
23279     unsigned NumElems = VT.getVectorNumElements();
23280     if (NumElems < 2)
23281       return SDValue();
23282
23283     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23284     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23285
23286     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23287     SDValue Ptr0 = St->getBasePtr();
23288     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23289
23290     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23291                                 St->getPointerInfo(), St->isVolatile(),
23292                                 St->isNonTemporal(), Alignment);
23293     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23294                                 St->getPointerInfo(), St->isVolatile(),
23295                                 St->isNonTemporal(),
23296                                 std::min(16U, Alignment));
23297     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23298   }
23299
23300   // Optimize trunc store (of multiple scalars) to shuffle and store.
23301   // First, pack all of the elements in one place. Next, store to memory
23302   // in fewer chunks.
23303   if (St->isTruncatingStore() && VT.isVector()) {
23304     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23305     unsigned NumElems = VT.getVectorNumElements();
23306     assert(StVT != VT && "Cannot truncate to the same type");
23307     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23308     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23309
23310     // From, To sizes and ElemCount must be pow of two
23311     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23312     // We are going to use the original vector elt for storing.
23313     // Accumulated smaller vector elements must be a multiple of the store size.
23314     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23315
23316     unsigned SizeRatio  = FromSz / ToSz;
23317
23318     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23319
23320     // Create a type on which we perform the shuffle
23321     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23322             StVT.getScalarType(), NumElems*SizeRatio);
23323
23324     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23325
23326     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23327     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23328     for (unsigned i = 0; i != NumElems; ++i)
23329       ShuffleVec[i] = i * SizeRatio;
23330
23331     // Can't shuffle using an illegal type.
23332     if (!TLI.isTypeLegal(WideVecVT))
23333       return SDValue();
23334
23335     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23336                                          DAG.getUNDEF(WideVecVT),
23337                                          &ShuffleVec[0]);
23338     // At this point all of the data is stored at the bottom of the
23339     // register. We now need to save it to mem.
23340
23341     // Find the largest store unit
23342     MVT StoreType = MVT::i8;
23343     for (MVT Tp : MVT::integer_valuetypes()) {
23344       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23345         StoreType = Tp;
23346     }
23347
23348     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23349     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23350         (64 <= NumElems * ToSz))
23351       StoreType = MVT::f64;
23352
23353     // Bitcast the original vector into a vector of store-size units
23354     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23355             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23356     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23357     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23358     SmallVector<SDValue, 8> Chains;
23359     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23360                                         TLI.getPointerTy());
23361     SDValue Ptr = St->getBasePtr();
23362
23363     // Perform one or more big stores into memory.
23364     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23365       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23366                                    StoreType, ShuffWide,
23367                                    DAG.getIntPtrConstant(i, dl));
23368       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23369                                 St->getPointerInfo(), St->isVolatile(),
23370                                 St->isNonTemporal(), St->getAlignment());
23371       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23372       Chains.push_back(Ch);
23373     }
23374
23375     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23376   }
23377
23378   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23379   // the FP state in cases where an emms may be missing.
23380   // A preferable solution to the general problem is to figure out the right
23381   // places to insert EMMS.  This qualifies as a quick hack.
23382
23383   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23384   if (VT.getSizeInBits() != 64)
23385     return SDValue();
23386
23387   const Function *F = DAG.getMachineFunction().getFunction();
23388   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23389   bool F64IsLegal =
23390       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23391   if ((VT.isVector() ||
23392        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23393       isa<LoadSDNode>(St->getValue()) &&
23394       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23395       St->getChain().hasOneUse() && !St->isVolatile()) {
23396     SDNode* LdVal = St->getValue().getNode();
23397     LoadSDNode *Ld = nullptr;
23398     int TokenFactorIndex = -1;
23399     SmallVector<SDValue, 8> Ops;
23400     SDNode* ChainVal = St->getChain().getNode();
23401     // Must be a store of a load.  We currently handle two cases:  the load
23402     // is a direct child, and it's under an intervening TokenFactor.  It is
23403     // possible to dig deeper under nested TokenFactors.
23404     if (ChainVal == LdVal)
23405       Ld = cast<LoadSDNode>(St->getChain());
23406     else if (St->getValue().hasOneUse() &&
23407              ChainVal->getOpcode() == ISD::TokenFactor) {
23408       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23409         if (ChainVal->getOperand(i).getNode() == LdVal) {
23410           TokenFactorIndex = i;
23411           Ld = cast<LoadSDNode>(St->getValue());
23412         } else
23413           Ops.push_back(ChainVal->getOperand(i));
23414       }
23415     }
23416
23417     if (!Ld || !ISD::isNormalLoad(Ld))
23418       return SDValue();
23419
23420     // If this is not the MMX case, i.e. we are just turning i64 load/store
23421     // into f64 load/store, avoid the transformation if there are multiple
23422     // uses of the loaded value.
23423     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23424       return SDValue();
23425
23426     SDLoc LdDL(Ld);
23427     SDLoc StDL(N);
23428     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23429     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23430     // pair instead.
23431     if (Subtarget->is64Bit() || F64IsLegal) {
23432       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23433       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23434                                   Ld->getPointerInfo(), Ld->isVolatile(),
23435                                   Ld->isNonTemporal(), Ld->isInvariant(),
23436                                   Ld->getAlignment());
23437       SDValue NewChain = NewLd.getValue(1);
23438       if (TokenFactorIndex != -1) {
23439         Ops.push_back(NewChain);
23440         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23441       }
23442       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23443                           St->getPointerInfo(),
23444                           St->isVolatile(), St->isNonTemporal(),
23445                           St->getAlignment());
23446     }
23447
23448     // Otherwise, lower to two pairs of 32-bit loads / stores.
23449     SDValue LoAddr = Ld->getBasePtr();
23450     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23451                                  DAG.getConstant(4, LdDL, MVT::i32));
23452
23453     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23454                                Ld->getPointerInfo(),
23455                                Ld->isVolatile(), Ld->isNonTemporal(),
23456                                Ld->isInvariant(), Ld->getAlignment());
23457     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23458                                Ld->getPointerInfo().getWithOffset(4),
23459                                Ld->isVolatile(), Ld->isNonTemporal(),
23460                                Ld->isInvariant(),
23461                                MinAlign(Ld->getAlignment(), 4));
23462
23463     SDValue NewChain = LoLd.getValue(1);
23464     if (TokenFactorIndex != -1) {
23465       Ops.push_back(LoLd);
23466       Ops.push_back(HiLd);
23467       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23468     }
23469
23470     LoAddr = St->getBasePtr();
23471     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23472                          DAG.getConstant(4, StDL, MVT::i32));
23473
23474     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23475                                 St->getPointerInfo(),
23476                                 St->isVolatile(), St->isNonTemporal(),
23477                                 St->getAlignment());
23478     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23479                                 St->getPointerInfo().getWithOffset(4),
23480                                 St->isVolatile(),
23481                                 St->isNonTemporal(),
23482                                 MinAlign(St->getAlignment(), 4));
23483     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23484   }
23485
23486   // This is similar to the above case, but here we handle a scalar 64-bit
23487   // integer store that is extracted from a vector on a 32-bit target.
23488   // If we have SSE2, then we can treat it like a floating-point double
23489   // to get past legalization. The execution dependencies fixup pass will
23490   // choose the optimal machine instruction for the store if this really is
23491   // an integer or v2f32 rather than an f64.
23492   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23493       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23494     SDValue OldExtract = St->getOperand(1);
23495     SDValue ExtOp0 = OldExtract.getOperand(0);
23496     unsigned VecSize = ExtOp0.getValueSizeInBits();
23497     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23498     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23499     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23500                                      BitCast, OldExtract.getOperand(1));
23501     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23502                         St->getPointerInfo(), St->isVolatile(),
23503                         St->isNonTemporal(), St->getAlignment());
23504   }
23505
23506   return SDValue();
23507 }
23508
23509 /// Return 'true' if this vector operation is "horizontal"
23510 /// and return the operands for the horizontal operation in LHS and RHS.  A
23511 /// horizontal operation performs the binary operation on successive elements
23512 /// of its first operand, then on successive elements of its second operand,
23513 /// returning the resulting values in a vector.  For example, if
23514 ///   A = < float a0, float a1, float a2, float a3 >
23515 /// and
23516 ///   B = < float b0, float b1, float b2, float b3 >
23517 /// then the result of doing a horizontal operation on A and B is
23518 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23519 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23520 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23521 /// set to A, RHS to B, and the routine returns 'true'.
23522 /// Note that the binary operation should have the property that if one of the
23523 /// operands is UNDEF then the result is UNDEF.
23524 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23525   // Look for the following pattern: if
23526   //   A = < float a0, float a1, float a2, float a3 >
23527   //   B = < float b0, float b1, float b2, float b3 >
23528   // and
23529   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23530   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23531   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23532   // which is A horizontal-op B.
23533
23534   // At least one of the operands should be a vector shuffle.
23535   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23536       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23537     return false;
23538
23539   MVT VT = LHS.getSimpleValueType();
23540
23541   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23542          "Unsupported vector type for horizontal add/sub");
23543
23544   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23545   // operate independently on 128-bit lanes.
23546   unsigned NumElts = VT.getVectorNumElements();
23547   unsigned NumLanes = VT.getSizeInBits()/128;
23548   unsigned NumLaneElts = NumElts / NumLanes;
23549   assert((NumLaneElts % 2 == 0) &&
23550          "Vector type should have an even number of elements in each lane");
23551   unsigned HalfLaneElts = NumLaneElts/2;
23552
23553   // View LHS in the form
23554   //   LHS = VECTOR_SHUFFLE A, B, LMask
23555   // If LHS is not a shuffle then pretend it is the shuffle
23556   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23557   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23558   // type VT.
23559   SDValue A, B;
23560   SmallVector<int, 16> LMask(NumElts);
23561   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23562     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23563       A = LHS.getOperand(0);
23564     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23565       B = LHS.getOperand(1);
23566     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23567     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23568   } else {
23569     if (LHS.getOpcode() != ISD::UNDEF)
23570       A = LHS;
23571     for (unsigned i = 0; i != NumElts; ++i)
23572       LMask[i] = i;
23573   }
23574
23575   // Likewise, view RHS in the form
23576   //   RHS = VECTOR_SHUFFLE C, D, RMask
23577   SDValue C, D;
23578   SmallVector<int, 16> RMask(NumElts);
23579   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23580     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23581       C = RHS.getOperand(0);
23582     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23583       D = RHS.getOperand(1);
23584     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23585     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23586   } else {
23587     if (RHS.getOpcode() != ISD::UNDEF)
23588       C = RHS;
23589     for (unsigned i = 0; i != NumElts; ++i)
23590       RMask[i] = i;
23591   }
23592
23593   // Check that the shuffles are both shuffling the same vectors.
23594   if (!(A == C && B == D) && !(A == D && B == C))
23595     return false;
23596
23597   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23598   if (!A.getNode() && !B.getNode())
23599     return false;
23600
23601   // If A and B occur in reverse order in RHS, then "swap" them (which means
23602   // rewriting the mask).
23603   if (A != C)
23604     ShuffleVectorSDNode::commuteMask(RMask);
23605
23606   // At this point LHS and RHS are equivalent to
23607   //   LHS = VECTOR_SHUFFLE A, B, LMask
23608   //   RHS = VECTOR_SHUFFLE A, B, RMask
23609   // Check that the masks correspond to performing a horizontal operation.
23610   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23611     for (unsigned i = 0; i != NumLaneElts; ++i) {
23612       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23613
23614       // Ignore any UNDEF components.
23615       if (LIdx < 0 || RIdx < 0 ||
23616           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23617           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23618         continue;
23619
23620       // Check that successive elements are being operated on.  If not, this is
23621       // not a horizontal operation.
23622       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23623       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23624       if (!(LIdx == Index && RIdx == Index + 1) &&
23625           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23626         return false;
23627     }
23628   }
23629
23630   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23631   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23632   return true;
23633 }
23634
23635 /// Do target-specific dag combines on floating point adds.
23636 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23637                                   const X86Subtarget *Subtarget) {
23638   EVT VT = N->getValueType(0);
23639   SDValue LHS = N->getOperand(0);
23640   SDValue RHS = N->getOperand(1);
23641
23642   // Try to synthesize horizontal adds from adds of shuffles.
23643   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23644        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23645       isHorizontalBinOp(LHS, RHS, true))
23646     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23647   return SDValue();
23648 }
23649
23650 /// Do target-specific dag combines on floating point subs.
23651 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23652                                   const X86Subtarget *Subtarget) {
23653   EVT VT = N->getValueType(0);
23654   SDValue LHS = N->getOperand(0);
23655   SDValue RHS = N->getOperand(1);
23656
23657   // Try to synthesize horizontal subs from subs of shuffles.
23658   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23659        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23660       isHorizontalBinOp(LHS, RHS, false))
23661     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23662   return SDValue();
23663 }
23664
23665 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23666 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23667   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23668
23669   // F[X]OR(0.0, x) -> x
23670   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23671     if (C->getValueAPF().isPosZero())
23672       return N->getOperand(1);
23673
23674   // F[X]OR(x, 0.0) -> x
23675   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23676     if (C->getValueAPF().isPosZero())
23677       return N->getOperand(0);
23678   return SDValue();
23679 }
23680
23681 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23682 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23683   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23684
23685   // Only perform optimizations if UnsafeMath is used.
23686   if (!DAG.getTarget().Options.UnsafeFPMath)
23687     return SDValue();
23688
23689   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23690   // into FMINC and FMAXC, which are Commutative operations.
23691   unsigned NewOp = 0;
23692   switch (N->getOpcode()) {
23693     default: llvm_unreachable("unknown opcode");
23694     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23695     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23696   }
23697
23698   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23699                      N->getOperand(0), N->getOperand(1));
23700 }
23701
23702 /// Do target-specific dag combines on X86ISD::FAND nodes.
23703 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23704   // FAND(0.0, x) -> 0.0
23705   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23706     if (C->getValueAPF().isPosZero())
23707       return N->getOperand(0);
23708
23709   // FAND(x, 0.0) -> 0.0
23710   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23711     if (C->getValueAPF().isPosZero())
23712       return N->getOperand(1);
23713
23714   return SDValue();
23715 }
23716
23717 /// Do target-specific dag combines on X86ISD::FANDN nodes
23718 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23719   // FANDN(0.0, x) -> x
23720   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23721     if (C->getValueAPF().isPosZero())
23722       return N->getOperand(1);
23723
23724   // FANDN(x, 0.0) -> 0.0
23725   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23726     if (C->getValueAPF().isPosZero())
23727       return N->getOperand(1);
23728
23729   return SDValue();
23730 }
23731
23732 static SDValue PerformBTCombine(SDNode *N,
23733                                 SelectionDAG &DAG,
23734                                 TargetLowering::DAGCombinerInfo &DCI) {
23735   // BT ignores high bits in the bit index operand.
23736   SDValue Op1 = N->getOperand(1);
23737   if (Op1.hasOneUse()) {
23738     unsigned BitWidth = Op1.getValueSizeInBits();
23739     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23740     APInt KnownZero, KnownOne;
23741     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23742                                           !DCI.isBeforeLegalizeOps());
23743     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23744     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23745         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23746       DCI.CommitTargetLoweringOpt(TLO);
23747   }
23748   return SDValue();
23749 }
23750
23751 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23752   SDValue Op = N->getOperand(0);
23753   if (Op.getOpcode() == ISD::BITCAST)
23754     Op = Op.getOperand(0);
23755   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23756   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23757       VT.getVectorElementType().getSizeInBits() ==
23758       OpVT.getVectorElementType().getSizeInBits()) {
23759     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23760   }
23761   return SDValue();
23762 }
23763
23764 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23765                                                const X86Subtarget *Subtarget) {
23766   EVT VT = N->getValueType(0);
23767   if (!VT.isVector())
23768     return SDValue();
23769
23770   SDValue N0 = N->getOperand(0);
23771   SDValue N1 = N->getOperand(1);
23772   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23773   SDLoc dl(N);
23774
23775   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23776   // both SSE and AVX2 since there is no sign-extended shift right
23777   // operation on a vector with 64-bit elements.
23778   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23779   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23780   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23781       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23782     SDValue N00 = N0.getOperand(0);
23783
23784     // EXTLOAD has a better solution on AVX2,
23785     // it may be replaced with X86ISD::VSEXT node.
23786     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23787       if (!ISD::isNormalLoad(N00.getNode()))
23788         return SDValue();
23789
23790     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23791         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23792                                   N00, N1);
23793       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23794     }
23795   }
23796   return SDValue();
23797 }
23798
23799 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23800                                   TargetLowering::DAGCombinerInfo &DCI,
23801                                   const X86Subtarget *Subtarget) {
23802   SDValue N0 = N->getOperand(0);
23803   EVT VT = N->getValueType(0);
23804   EVT SVT = VT.getScalarType();
23805   EVT InVT = N0->getValueType(0);
23806   EVT InSVT = InVT.getScalarType();
23807   SDLoc DL(N);
23808
23809   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23810   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23811   // This exposes the sext to the sdivrem lowering, so that it directly extends
23812   // from AH (which we otherwise need to do contortions to access).
23813   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23814       InVT == MVT::i8 && VT == MVT::i32) {
23815     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23816     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
23817                             N0.getOperand(0), N0.getOperand(1));
23818     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23819     return R.getValue(1);
23820   }
23821
23822   if (!DCI.isBeforeLegalizeOps()) {
23823     if (N0.getValueType() == MVT::i1) {
23824       SDValue Zero = DAG.getConstant(0, DL, VT);
23825       SDValue AllOnes =
23826         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
23827       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
23828     }
23829     return SDValue();
23830   }
23831
23832   if (VT.isVector()) {
23833     auto ExtendToVec128 = [&DAG](SDLoc DL, SDValue N) {
23834       EVT InVT = N->getValueType(0);
23835       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
23836                                    128 / InVT.getScalarSizeInBits());
23837       SmallVector<SDValue, 8> Opnds(128 / InVT.getSizeInBits(),
23838                                     DAG.getUNDEF(InVT));
23839       Opnds[0] = N;
23840       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
23841     };
23842
23843     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
23844     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
23845     if (VT.getSizeInBits() == 128 &&
23846         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
23847         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
23848       SDValue ExOp = ExtendToVec128(DL, N0);
23849       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
23850     }
23851
23852     // On pre-AVX2 targets, split into 128-bit nodes of
23853     // ISD::SIGN_EXTEND_VECTOR_INREG.
23854     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
23855         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
23856         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
23857       unsigned NumVecs = VT.getSizeInBits() / 128;
23858       unsigned NumSubElts = 128 / SVT.getSizeInBits();
23859       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
23860       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
23861
23862       SmallVector<SDValue, 8> Opnds;
23863       for (unsigned i = 0, Offset = 0; i != NumVecs;
23864            ++i, Offset += NumSubElts) {
23865         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
23866                                      DAG.getIntPtrConstant(Offset, DL));
23867         SrcVec = ExtendToVec128(DL, SrcVec);
23868         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
23869         Opnds.push_back(SrcVec);
23870       }
23871       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
23872     }
23873   }
23874
23875   if (!Subtarget->hasFp256())
23876     return SDValue();
23877
23878   if (VT.isVector() && VT.getSizeInBits() == 256) {
23879     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23880     if (R.getNode())
23881       return R;
23882   }
23883
23884   return SDValue();
23885 }
23886
23887 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23888                                  const X86Subtarget* Subtarget) {
23889   SDLoc dl(N);
23890   EVT VT = N->getValueType(0);
23891
23892   // Let legalize expand this if it isn't a legal type yet.
23893   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23894     return SDValue();
23895
23896   EVT ScalarVT = VT.getScalarType();
23897   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23898       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23899     return SDValue();
23900
23901   SDValue A = N->getOperand(0);
23902   SDValue B = N->getOperand(1);
23903   SDValue C = N->getOperand(2);
23904
23905   bool NegA = (A.getOpcode() == ISD::FNEG);
23906   bool NegB = (B.getOpcode() == ISD::FNEG);
23907   bool NegC = (C.getOpcode() == ISD::FNEG);
23908
23909   // Negative multiplication when NegA xor NegB
23910   bool NegMul = (NegA != NegB);
23911   if (NegA)
23912     A = A.getOperand(0);
23913   if (NegB)
23914     B = B.getOperand(0);
23915   if (NegC)
23916     C = C.getOperand(0);
23917
23918   unsigned Opcode;
23919   if (!NegMul)
23920     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23921   else
23922     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23923
23924   return DAG.getNode(Opcode, dl, VT, A, B, C);
23925 }
23926
23927 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23928                                   TargetLowering::DAGCombinerInfo &DCI,
23929                                   const X86Subtarget *Subtarget) {
23930   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23931   //           (and (i32 x86isd::setcc_carry), 1)
23932   // This eliminates the zext. This transformation is necessary because
23933   // ISD::SETCC is always legalized to i8.
23934   SDLoc dl(N);
23935   SDValue N0 = N->getOperand(0);
23936   EVT VT = N->getValueType(0);
23937
23938   if (N0.getOpcode() == ISD::AND &&
23939       N0.hasOneUse() &&
23940       N0.getOperand(0).hasOneUse()) {
23941     SDValue N00 = N0.getOperand(0);
23942     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23943       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23944       if (!C || C->getZExtValue() != 1)
23945         return SDValue();
23946       return DAG.getNode(ISD::AND, dl, VT,
23947                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23948                                      N00.getOperand(0), N00.getOperand(1)),
23949                          DAG.getConstant(1, dl, VT));
23950     }
23951   }
23952
23953   if (N0.getOpcode() == ISD::TRUNCATE &&
23954       N0.hasOneUse() &&
23955       N0.getOperand(0).hasOneUse()) {
23956     SDValue N00 = N0.getOperand(0);
23957     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23958       return DAG.getNode(ISD::AND, dl, VT,
23959                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23960                                      N00.getOperand(0), N00.getOperand(1)),
23961                          DAG.getConstant(1, dl, VT));
23962     }
23963   }
23964   if (VT.is256BitVector()) {
23965     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23966     if (R.getNode())
23967       return R;
23968   }
23969
23970   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23971   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23972   // This exposes the zext to the udivrem lowering, so that it directly extends
23973   // from AH (which we otherwise need to do contortions to access).
23974   if (N0.getOpcode() == ISD::UDIVREM &&
23975       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23976       (VT == MVT::i32 || VT == MVT::i64)) {
23977     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23978     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23979                             N0.getOperand(0), N0.getOperand(1));
23980     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23981     return R.getValue(1);
23982   }
23983
23984   return SDValue();
23985 }
23986
23987 // Optimize x == -y --> x+y == 0
23988 //          x != -y --> x+y != 0
23989 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23990                                       const X86Subtarget* Subtarget) {
23991   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23992   SDValue LHS = N->getOperand(0);
23993   SDValue RHS = N->getOperand(1);
23994   EVT VT = N->getValueType(0);
23995   SDLoc DL(N);
23996
23997   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23998     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23999       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24000         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
24001                                    LHS.getOperand(1));
24002         return DAG.getSetCC(DL, N->getValueType(0), addV,
24003                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24004       }
24005   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24006     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24007       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24008         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
24009                                    RHS.getOperand(1));
24010         return DAG.getSetCC(DL, N->getValueType(0), addV,
24011                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24012       }
24013
24014   if (VT.getScalarType() == MVT::i1 &&
24015       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
24016     bool IsSEXT0 =
24017         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24018         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24019     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24020
24021     if (!IsSEXT0 || !IsVZero1) {
24022       // Swap the operands and update the condition code.
24023       std::swap(LHS, RHS);
24024       CC = ISD::getSetCCSwappedOperands(CC);
24025
24026       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24027                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24028       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24029     }
24030
24031     if (IsSEXT0 && IsVZero1) {
24032       assert(VT == LHS.getOperand(0).getValueType() &&
24033              "Uexpected operand type");
24034       if (CC == ISD::SETGT)
24035         return DAG.getConstant(0, DL, VT);
24036       if (CC == ISD::SETLE)
24037         return DAG.getConstant(1, DL, VT);
24038       if (CC == ISD::SETEQ || CC == ISD::SETGE)
24039         return DAG.getNOT(DL, LHS.getOperand(0), VT);
24040
24041       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24042              "Unexpected condition code!");
24043       return LHS.getOperand(0);
24044     }
24045   }
24046
24047   return SDValue();
24048 }
24049
24050 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24051                                          SelectionDAG &DAG) {
24052   SDLoc dl(Load);
24053   MVT VT = Load->getSimpleValueType(0);
24054   MVT EVT = VT.getVectorElementType();
24055   SDValue Addr = Load->getOperand(1);
24056   SDValue NewAddr = DAG.getNode(
24057       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24058       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24059                       Addr.getSimpleValueType()));
24060
24061   SDValue NewLoad =
24062       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24063                   DAG.getMachineFunction().getMachineMemOperand(
24064                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24065   return NewLoad;
24066 }
24067
24068 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24069                                       const X86Subtarget *Subtarget) {
24070   SDLoc dl(N);
24071   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24072   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24073          "X86insertps is only defined for v4x32");
24074
24075   SDValue Ld = N->getOperand(1);
24076   if (MayFoldLoad(Ld)) {
24077     // Extract the countS bits from the immediate so we can get the proper
24078     // address when narrowing the vector load to a specific element.
24079     // When the second source op is a memory address, insertps doesn't use
24080     // countS and just gets an f32 from that address.
24081     unsigned DestIndex =
24082         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24083
24084     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24085
24086     // Create this as a scalar to vector to match the instruction pattern.
24087     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24088     // countS bits are ignored when loading from memory on insertps, which
24089     // means we don't need to explicitly set them to 0.
24090     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24091                        LoadScalarToVector, N->getOperand(2));
24092   }
24093   return SDValue();
24094 }
24095
24096 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24097   SDValue V0 = N->getOperand(0);
24098   SDValue V1 = N->getOperand(1);
24099   SDLoc DL(N);
24100   EVT VT = N->getValueType(0);
24101
24102   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24103   // operands and changing the mask to 1. This saves us a bunch of
24104   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24105   // x86InstrInfo knows how to commute this back after instruction selection
24106   // if it would help register allocation.
24107
24108   // TODO: If optimizing for size or a processor that doesn't suffer from
24109   // partial register update stalls, this should be transformed into a MOVSD
24110   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24111
24112   if (VT == MVT::v2f64)
24113     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24114       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24115         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24116         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24117       }
24118
24119   return SDValue();
24120 }
24121
24122 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24123 // as "sbb reg,reg", since it can be extended without zext and produces
24124 // an all-ones bit which is more useful than 0/1 in some cases.
24125 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24126                                MVT VT) {
24127   if (VT == MVT::i8)
24128     return DAG.getNode(ISD::AND, DL, VT,
24129                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24130                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
24131                                    EFLAGS),
24132                        DAG.getConstant(1, DL, VT));
24133   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24134   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24135                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24136                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
24137                                  EFLAGS));
24138 }
24139
24140 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24141 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24142                                    TargetLowering::DAGCombinerInfo &DCI,
24143                                    const X86Subtarget *Subtarget) {
24144   SDLoc DL(N);
24145   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24146   SDValue EFLAGS = N->getOperand(1);
24147
24148   if (CC == X86::COND_A) {
24149     // Try to convert COND_A into COND_B in an attempt to facilitate
24150     // materializing "setb reg".
24151     //
24152     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24153     // cannot take an immediate as its first operand.
24154     //
24155     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24156         EFLAGS.getValueType().isInteger() &&
24157         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
24158       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
24159                                    EFLAGS.getNode()->getVTList(),
24160                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
24161       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
24162       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
24163     }
24164   }
24165
24166   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24167   // a zext and produces an all-ones bit which is more useful than 0/1 in some
24168   // cases.
24169   if (CC == X86::COND_B)
24170     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24171
24172   SDValue Flags;
24173
24174   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24175   if (Flags.getNode()) {
24176     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24177     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24178   }
24179
24180   return SDValue();
24181 }
24182
24183 // Optimize branch condition evaluation.
24184 //
24185 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24186                                     TargetLowering::DAGCombinerInfo &DCI,
24187                                     const X86Subtarget *Subtarget) {
24188   SDLoc DL(N);
24189   SDValue Chain = N->getOperand(0);
24190   SDValue Dest = N->getOperand(1);
24191   SDValue EFLAGS = N->getOperand(3);
24192   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24193
24194   SDValue Flags;
24195
24196   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24197   if (Flags.getNode()) {
24198     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24199     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24200                        Flags);
24201   }
24202
24203   return SDValue();
24204 }
24205
24206 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24207                                                          SelectionDAG &DAG) {
24208   // Take advantage of vector comparisons producing 0 or -1 in each lane to
24209   // optimize away operation when it's from a constant.
24210   //
24211   // The general transformation is:
24212   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24213   //       AND(VECTOR_CMP(x,y), constant2)
24214   //    constant2 = UNARYOP(constant)
24215
24216   // Early exit if this isn't a vector operation, the operand of the
24217   // unary operation isn't a bitwise AND, or if the sizes of the operations
24218   // aren't the same.
24219   EVT VT = N->getValueType(0);
24220   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24221       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24222       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24223     return SDValue();
24224
24225   // Now check that the other operand of the AND is a constant. We could
24226   // make the transformation for non-constant splats as well, but it's unclear
24227   // that would be a benefit as it would not eliminate any operations, just
24228   // perform one more step in scalar code before moving to the vector unit.
24229   if (BuildVectorSDNode *BV =
24230           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24231     // Bail out if the vector isn't a constant.
24232     if (!BV->isConstant())
24233       return SDValue();
24234
24235     // Everything checks out. Build up the new and improved node.
24236     SDLoc DL(N);
24237     EVT IntVT = BV->getValueType(0);
24238     // Create a new constant of the appropriate type for the transformed
24239     // DAG.
24240     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24241     // The AND node needs bitcasts to/from an integer vector type around it.
24242     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24243     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24244                                  N->getOperand(0)->getOperand(0), MaskConst);
24245     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24246     return Res;
24247   }
24248
24249   return SDValue();
24250 }
24251
24252 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24253                                         const X86Subtarget *Subtarget) {
24254   // First try to optimize away the conversion entirely when it's
24255   // conditionally from a constant. Vectors only.
24256   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24257   if (Res != SDValue())
24258     return Res;
24259
24260   // Now move on to more general possibilities.
24261   SDValue Op0 = N->getOperand(0);
24262   EVT InVT = Op0->getValueType(0);
24263
24264   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24265   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24266     SDLoc dl(N);
24267     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24268     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24269     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24270   }
24271
24272   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24273   // a 32-bit target where SSE doesn't support i64->FP operations.
24274   if (Op0.getOpcode() == ISD::LOAD) {
24275     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24276     EVT VT = Ld->getValueType(0);
24277
24278     // This transformation is not supported if the result type is f16
24279     if (N->getValueType(0) == MVT::f16)
24280       return SDValue();
24281
24282     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24283         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24284         !Subtarget->is64Bit() && VT == MVT::i64) {
24285       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24286           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24287       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24288       return FILDChain;
24289     }
24290   }
24291   return SDValue();
24292 }
24293
24294 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24295 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24296                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24297   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24298   // the result is either zero or one (depending on the input carry bit).
24299   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24300   if (X86::isZeroNode(N->getOperand(0)) &&
24301       X86::isZeroNode(N->getOperand(1)) &&
24302       // We don't have a good way to replace an EFLAGS use, so only do this when
24303       // dead right now.
24304       SDValue(N, 1).use_empty()) {
24305     SDLoc DL(N);
24306     EVT VT = N->getValueType(0);
24307     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24308     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24309                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24310                                            DAG.getConstant(X86::COND_B, DL,
24311                                                            MVT::i8),
24312                                            N->getOperand(2)),
24313                                DAG.getConstant(1, DL, VT));
24314     return DCI.CombineTo(N, Res1, CarryOut);
24315   }
24316
24317   return SDValue();
24318 }
24319
24320 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24321 //      (add Y, (setne X, 0)) -> sbb -1, Y
24322 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24323 //      (sub (setne X, 0), Y) -> adc -1, Y
24324 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24325   SDLoc DL(N);
24326
24327   // Look through ZExts.
24328   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24329   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24330     return SDValue();
24331
24332   SDValue SetCC = Ext.getOperand(0);
24333   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24334     return SDValue();
24335
24336   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24337   if (CC != X86::COND_E && CC != X86::COND_NE)
24338     return SDValue();
24339
24340   SDValue Cmp = SetCC.getOperand(1);
24341   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24342       !X86::isZeroNode(Cmp.getOperand(1)) ||
24343       !Cmp.getOperand(0).getValueType().isInteger())
24344     return SDValue();
24345
24346   SDValue CmpOp0 = Cmp.getOperand(0);
24347   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24348                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24349
24350   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24351   if (CC == X86::COND_NE)
24352     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24353                        DL, OtherVal.getValueType(), OtherVal,
24354                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24355                        NewCmp);
24356   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24357                      DL, OtherVal.getValueType(), OtherVal,
24358                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24359 }
24360
24361 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24362 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24363                                  const X86Subtarget *Subtarget) {
24364   EVT VT = N->getValueType(0);
24365   SDValue Op0 = N->getOperand(0);
24366   SDValue Op1 = N->getOperand(1);
24367
24368   // Try to synthesize horizontal adds from adds of shuffles.
24369   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24370        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24371       isHorizontalBinOp(Op0, Op1, true))
24372     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24373
24374   return OptimizeConditionalInDecrement(N, DAG);
24375 }
24376
24377 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24378                                  const X86Subtarget *Subtarget) {
24379   SDValue Op0 = N->getOperand(0);
24380   SDValue Op1 = N->getOperand(1);
24381
24382   // X86 can't encode an immediate LHS of a sub. See if we can push the
24383   // negation into a preceding instruction.
24384   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24385     // If the RHS of the sub is a XOR with one use and a constant, invert the
24386     // immediate. Then add one to the LHS of the sub so we can turn
24387     // X-Y -> X+~Y+1, saving one register.
24388     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24389         isa<ConstantSDNode>(Op1.getOperand(1))) {
24390       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24391       EVT VT = Op0.getValueType();
24392       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24393                                    Op1.getOperand(0),
24394                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24395       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24396                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24397     }
24398   }
24399
24400   // Try to synthesize horizontal adds from adds of shuffles.
24401   EVT VT = N->getValueType(0);
24402   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24403        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24404       isHorizontalBinOp(Op0, Op1, true))
24405     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24406
24407   return OptimizeConditionalInDecrement(N, DAG);
24408 }
24409
24410 /// performVZEXTCombine - Performs build vector combines
24411 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24412                                    TargetLowering::DAGCombinerInfo &DCI,
24413                                    const X86Subtarget *Subtarget) {
24414   SDLoc DL(N);
24415   MVT VT = N->getSimpleValueType(0);
24416   SDValue Op = N->getOperand(0);
24417   MVT OpVT = Op.getSimpleValueType();
24418   MVT OpEltVT = OpVT.getVectorElementType();
24419   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24420
24421   // (vzext (bitcast (vzext (x)) -> (vzext x)
24422   SDValue V = Op;
24423   while (V.getOpcode() == ISD::BITCAST)
24424     V = V.getOperand(0);
24425
24426   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24427     MVT InnerVT = V.getSimpleValueType();
24428     MVT InnerEltVT = InnerVT.getVectorElementType();
24429
24430     // If the element sizes match exactly, we can just do one larger vzext. This
24431     // is always an exact type match as vzext operates on integer types.
24432     if (OpEltVT == InnerEltVT) {
24433       assert(OpVT == InnerVT && "Types must match for vzext!");
24434       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24435     }
24436
24437     // The only other way we can combine them is if only a single element of the
24438     // inner vzext is used in the input to the outer vzext.
24439     if (InnerEltVT.getSizeInBits() < InputBits)
24440       return SDValue();
24441
24442     // In this case, the inner vzext is completely dead because we're going to
24443     // only look at bits inside of the low element. Just do the outer vzext on
24444     // a bitcast of the input to the inner.
24445     return DAG.getNode(X86ISD::VZEXT, DL, VT,
24446                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24447   }
24448
24449   // Check if we can bypass extracting and re-inserting an element of an input
24450   // vector. Essentialy:
24451   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24452   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24453       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24454       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24455     SDValue ExtractedV = V.getOperand(0);
24456     SDValue OrigV = ExtractedV.getOperand(0);
24457     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24458       if (ExtractIdx->getZExtValue() == 0) {
24459         MVT OrigVT = OrigV.getSimpleValueType();
24460         // Extract a subvector if necessary...
24461         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24462           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24463           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24464                                     OrigVT.getVectorNumElements() / Ratio);
24465           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24466                               DAG.getIntPtrConstant(0, DL));
24467         }
24468         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24469         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24470       }
24471   }
24472
24473   return SDValue();
24474 }
24475
24476 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24477                                              DAGCombinerInfo &DCI) const {
24478   SelectionDAG &DAG = DCI.DAG;
24479   switch (N->getOpcode()) {
24480   default: break;
24481   case ISD::EXTRACT_VECTOR_ELT:
24482     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24483   case ISD::VSELECT:
24484   case ISD::SELECT:
24485   case X86ISD::SHRUNKBLEND:
24486     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24487   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24488   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24489   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24490   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24491   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24492   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24493   case ISD::SHL:
24494   case ISD::SRA:
24495   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24496   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24497   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24498   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24499   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24500   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24501   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24502   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24503   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24504   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24505   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24506   case X86ISD::FXOR:
24507   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24508   case X86ISD::FMIN:
24509   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24510   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24511   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24512   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24513   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24514   case ISD::ANY_EXTEND:
24515   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24516   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24517   case ISD::SIGN_EXTEND_INREG:
24518     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24519   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24520   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24521   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24522   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24523   case X86ISD::SHUFP:       // Handle all target specific shuffles
24524   case X86ISD::PALIGNR:
24525   case X86ISD::UNPCKH:
24526   case X86ISD::UNPCKL:
24527   case X86ISD::MOVHLPS:
24528   case X86ISD::MOVLHPS:
24529   case X86ISD::PSHUFB:
24530   case X86ISD::PSHUFD:
24531   case X86ISD::PSHUFHW:
24532   case X86ISD::PSHUFLW:
24533   case X86ISD::MOVSS:
24534   case X86ISD::MOVSD:
24535   case X86ISD::VPERMILPI:
24536   case X86ISD::VPERM2X128:
24537   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24538   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24539   case ISD::INTRINSIC_WO_CHAIN:
24540     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24541   case X86ISD::INSERTPS: {
24542     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24543       return PerformINSERTPSCombine(N, DAG, Subtarget);
24544     break;
24545   }
24546   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24547   }
24548
24549   return SDValue();
24550 }
24551
24552 /// isTypeDesirableForOp - Return true if the target has native support for
24553 /// the specified value type and it is 'desirable' to use the type for the
24554 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24555 /// instruction encodings are longer and some i16 instructions are slow.
24556 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24557   if (!isTypeLegal(VT))
24558     return false;
24559   if (VT != MVT::i16)
24560     return true;
24561
24562   switch (Opc) {
24563   default:
24564     return true;
24565   case ISD::LOAD:
24566   case ISD::SIGN_EXTEND:
24567   case ISD::ZERO_EXTEND:
24568   case ISD::ANY_EXTEND:
24569   case ISD::SHL:
24570   case ISD::SRL:
24571   case ISD::SUB:
24572   case ISD::ADD:
24573   case ISD::MUL:
24574   case ISD::AND:
24575   case ISD::OR:
24576   case ISD::XOR:
24577     return false;
24578   }
24579 }
24580
24581 /// IsDesirableToPromoteOp - This method query the target whether it is
24582 /// beneficial for dag combiner to promote the specified node. If true, it
24583 /// should return the desired promotion type by reference.
24584 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24585   EVT VT = Op.getValueType();
24586   if (VT != MVT::i16)
24587     return false;
24588
24589   bool Promote = false;
24590   bool Commute = false;
24591   switch (Op.getOpcode()) {
24592   default: break;
24593   case ISD::LOAD: {
24594     LoadSDNode *LD = cast<LoadSDNode>(Op);
24595     // If the non-extending load has a single use and it's not live out, then it
24596     // might be folded.
24597     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24598                                                      Op.hasOneUse()*/) {
24599       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24600              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24601         // The only case where we'd want to promote LOAD (rather then it being
24602         // promoted as an operand is when it's only use is liveout.
24603         if (UI->getOpcode() != ISD::CopyToReg)
24604           return false;
24605       }
24606     }
24607     Promote = true;
24608     break;
24609   }
24610   case ISD::SIGN_EXTEND:
24611   case ISD::ZERO_EXTEND:
24612   case ISD::ANY_EXTEND:
24613     Promote = true;
24614     break;
24615   case ISD::SHL:
24616   case ISD::SRL: {
24617     SDValue N0 = Op.getOperand(0);
24618     // Look out for (store (shl (load), x)).
24619     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24620       return false;
24621     Promote = true;
24622     break;
24623   }
24624   case ISD::ADD:
24625   case ISD::MUL:
24626   case ISD::AND:
24627   case ISD::OR:
24628   case ISD::XOR:
24629     Commute = true;
24630     // fallthrough
24631   case ISD::SUB: {
24632     SDValue N0 = Op.getOperand(0);
24633     SDValue N1 = Op.getOperand(1);
24634     if (!Commute && MayFoldLoad(N1))
24635       return false;
24636     // Avoid disabling potential load folding opportunities.
24637     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24638       return false;
24639     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24640       return false;
24641     Promote = true;
24642   }
24643   }
24644
24645   PVT = MVT::i32;
24646   return Promote;
24647 }
24648
24649 //===----------------------------------------------------------------------===//
24650 //                           X86 Inline Assembly Support
24651 //===----------------------------------------------------------------------===//
24652
24653 // Helper to match a string separated by whitespace.
24654 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24655   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24656
24657   for (StringRef Piece : Pieces) {
24658     if (!S.startswith(Piece)) // Check if the piece matches.
24659       return false;
24660
24661     S = S.substr(Piece.size());
24662     StringRef::size_type Pos = S.find_first_not_of(" \t");
24663     if (Pos == 0) // We matched a prefix.
24664       return false;
24665
24666     S = S.substr(Pos);
24667   }
24668
24669   return S.empty();
24670 }
24671
24672 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24673
24674   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24675     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24676         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24677         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24678
24679       if (AsmPieces.size() == 3)
24680         return true;
24681       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24682         return true;
24683     }
24684   }
24685   return false;
24686 }
24687
24688 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24689   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24690
24691   std::string AsmStr = IA->getAsmString();
24692
24693   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24694   if (!Ty || Ty->getBitWidth() % 16 != 0)
24695     return false;
24696
24697   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24698   SmallVector<StringRef, 4> AsmPieces;
24699   SplitString(AsmStr, AsmPieces, ";\n");
24700
24701   switch (AsmPieces.size()) {
24702   default: return false;
24703   case 1:
24704     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24705     // we will turn this bswap into something that will be lowered to logical
24706     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24707     // lower so don't worry about this.
24708     // bswap $0
24709     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24710         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24711         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24712         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24713         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24714         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24715       // No need to check constraints, nothing other than the equivalent of
24716       // "=r,0" would be valid here.
24717       return IntrinsicLowering::LowerToByteSwap(CI);
24718     }
24719
24720     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24721     if (CI->getType()->isIntegerTy(16) &&
24722         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24723         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24724          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24725       AsmPieces.clear();
24726       const std::string &ConstraintsStr = IA->getConstraintString();
24727       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24728       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24729       if (clobbersFlagRegisters(AsmPieces))
24730         return IntrinsicLowering::LowerToByteSwap(CI);
24731     }
24732     break;
24733   case 3:
24734     if (CI->getType()->isIntegerTy(32) &&
24735         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24736         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24737         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24738         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24739       AsmPieces.clear();
24740       const std::string &ConstraintsStr = IA->getConstraintString();
24741       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24742       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24743       if (clobbersFlagRegisters(AsmPieces))
24744         return IntrinsicLowering::LowerToByteSwap(CI);
24745     }
24746
24747     if (CI->getType()->isIntegerTy(64)) {
24748       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24749       if (Constraints.size() >= 2 &&
24750           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24751           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24752         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24753         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24754             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24755             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24756           return IntrinsicLowering::LowerToByteSwap(CI);
24757       }
24758     }
24759     break;
24760   }
24761   return false;
24762 }
24763
24764 /// getConstraintType - Given a constraint letter, return the type of
24765 /// constraint it is for this target.
24766 X86TargetLowering::ConstraintType
24767 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24768   if (Constraint.size() == 1) {
24769     switch (Constraint[0]) {
24770     case 'R':
24771     case 'q':
24772     case 'Q':
24773     case 'f':
24774     case 't':
24775     case 'u':
24776     case 'y':
24777     case 'x':
24778     case 'Y':
24779     case 'l':
24780       return C_RegisterClass;
24781     case 'a':
24782     case 'b':
24783     case 'c':
24784     case 'd':
24785     case 'S':
24786     case 'D':
24787     case 'A':
24788       return C_Register;
24789     case 'I':
24790     case 'J':
24791     case 'K':
24792     case 'L':
24793     case 'M':
24794     case 'N':
24795     case 'G':
24796     case 'C':
24797     case 'e':
24798     case 'Z':
24799       return C_Other;
24800     default:
24801       break;
24802     }
24803   }
24804   return TargetLowering::getConstraintType(Constraint);
24805 }
24806
24807 /// Examine constraint type and operand type and determine a weight value.
24808 /// This object must already have been set up with the operand type
24809 /// and the current alternative constraint selected.
24810 TargetLowering::ConstraintWeight
24811   X86TargetLowering::getSingleConstraintMatchWeight(
24812     AsmOperandInfo &info, const char *constraint) const {
24813   ConstraintWeight weight = CW_Invalid;
24814   Value *CallOperandVal = info.CallOperandVal;
24815     // If we don't have a value, we can't do a match,
24816     // but allow it at the lowest weight.
24817   if (!CallOperandVal)
24818     return CW_Default;
24819   Type *type = CallOperandVal->getType();
24820   // Look at the constraint type.
24821   switch (*constraint) {
24822   default:
24823     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24824   case 'R':
24825   case 'q':
24826   case 'Q':
24827   case 'a':
24828   case 'b':
24829   case 'c':
24830   case 'd':
24831   case 'S':
24832   case 'D':
24833   case 'A':
24834     if (CallOperandVal->getType()->isIntegerTy())
24835       weight = CW_SpecificReg;
24836     break;
24837   case 'f':
24838   case 't':
24839   case 'u':
24840     if (type->isFloatingPointTy())
24841       weight = CW_SpecificReg;
24842     break;
24843   case 'y':
24844     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24845       weight = CW_SpecificReg;
24846     break;
24847   case 'x':
24848   case 'Y':
24849     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24850         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24851       weight = CW_Register;
24852     break;
24853   case 'I':
24854     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24855       if (C->getZExtValue() <= 31)
24856         weight = CW_Constant;
24857     }
24858     break;
24859   case 'J':
24860     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24861       if (C->getZExtValue() <= 63)
24862         weight = CW_Constant;
24863     }
24864     break;
24865   case 'K':
24866     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24867       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24868         weight = CW_Constant;
24869     }
24870     break;
24871   case 'L':
24872     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24873       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24874         weight = CW_Constant;
24875     }
24876     break;
24877   case 'M':
24878     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24879       if (C->getZExtValue() <= 3)
24880         weight = CW_Constant;
24881     }
24882     break;
24883   case 'N':
24884     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24885       if (C->getZExtValue() <= 0xff)
24886         weight = CW_Constant;
24887     }
24888     break;
24889   case 'G':
24890   case 'C':
24891     if (isa<ConstantFP>(CallOperandVal)) {
24892       weight = CW_Constant;
24893     }
24894     break;
24895   case 'e':
24896     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24897       if ((C->getSExtValue() >= -0x80000000LL) &&
24898           (C->getSExtValue() <= 0x7fffffffLL))
24899         weight = CW_Constant;
24900     }
24901     break;
24902   case 'Z':
24903     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24904       if (C->getZExtValue() <= 0xffffffff)
24905         weight = CW_Constant;
24906     }
24907     break;
24908   }
24909   return weight;
24910 }
24911
24912 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24913 /// with another that has more specific requirements based on the type of the
24914 /// corresponding operand.
24915 const char *X86TargetLowering::
24916 LowerXConstraint(EVT ConstraintVT) const {
24917   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24918   // 'f' like normal targets.
24919   if (ConstraintVT.isFloatingPoint()) {
24920     if (Subtarget->hasSSE2())
24921       return "Y";
24922     if (Subtarget->hasSSE1())
24923       return "x";
24924   }
24925
24926   return TargetLowering::LowerXConstraint(ConstraintVT);
24927 }
24928
24929 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24930 /// vector.  If it is invalid, don't add anything to Ops.
24931 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24932                                                      std::string &Constraint,
24933                                                      std::vector<SDValue>&Ops,
24934                                                      SelectionDAG &DAG) const {
24935   SDValue Result;
24936
24937   // Only support length 1 constraints for now.
24938   if (Constraint.length() > 1) return;
24939
24940   char ConstraintLetter = Constraint[0];
24941   switch (ConstraintLetter) {
24942   default: break;
24943   case 'I':
24944     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24945       if (C->getZExtValue() <= 31) {
24946         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24947                                        Op.getValueType());
24948         break;
24949       }
24950     }
24951     return;
24952   case 'J':
24953     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24954       if (C->getZExtValue() <= 63) {
24955         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24956                                        Op.getValueType());
24957         break;
24958       }
24959     }
24960     return;
24961   case 'K':
24962     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24963       if (isInt<8>(C->getSExtValue())) {
24964         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24965                                        Op.getValueType());
24966         break;
24967       }
24968     }
24969     return;
24970   case 'L':
24971     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24972       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24973           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24974         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24975                                        Op.getValueType());
24976         break;
24977       }
24978     }
24979     return;
24980   case 'M':
24981     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24982       if (C->getZExtValue() <= 3) {
24983         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24984                                        Op.getValueType());
24985         break;
24986       }
24987     }
24988     return;
24989   case 'N':
24990     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24991       if (C->getZExtValue() <= 255) {
24992         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24993                                        Op.getValueType());
24994         break;
24995       }
24996     }
24997     return;
24998   case 'O':
24999     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25000       if (C->getZExtValue() <= 127) {
25001         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25002                                        Op.getValueType());
25003         break;
25004       }
25005     }
25006     return;
25007   case 'e': {
25008     // 32-bit signed value
25009     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25010       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25011                                            C->getSExtValue())) {
25012         // Widen to 64 bits here to get it sign extended.
25013         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
25014         break;
25015       }
25016     // FIXME gcc accepts some relocatable values here too, but only in certain
25017     // memory models; it's complicated.
25018     }
25019     return;
25020   }
25021   case 'Z': {
25022     // 32-bit unsigned value
25023     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25024       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25025                                            C->getZExtValue())) {
25026         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25027                                        Op.getValueType());
25028         break;
25029       }
25030     }
25031     // FIXME gcc accepts some relocatable values here too, but only in certain
25032     // memory models; it's complicated.
25033     return;
25034   }
25035   case 'i': {
25036     // Literal immediates are always ok.
25037     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25038       // Widen to 64 bits here to get it sign extended.
25039       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25040       break;
25041     }
25042
25043     // In any sort of PIC mode addresses need to be computed at runtime by
25044     // adding in a register or some sort of table lookup.  These can't
25045     // be used as immediates.
25046     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25047       return;
25048
25049     // If we are in non-pic codegen mode, we allow the address of a global (with
25050     // an optional displacement) to be used with 'i'.
25051     GlobalAddressSDNode *GA = nullptr;
25052     int64_t Offset = 0;
25053
25054     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25055     while (1) {
25056       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25057         Offset += GA->getOffset();
25058         break;
25059       } else if (Op.getOpcode() == ISD::ADD) {
25060         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25061           Offset += C->getZExtValue();
25062           Op = Op.getOperand(0);
25063           continue;
25064         }
25065       } else if (Op.getOpcode() == ISD::SUB) {
25066         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25067           Offset += -C->getZExtValue();
25068           Op = Op.getOperand(0);
25069           continue;
25070         }
25071       }
25072
25073       // Otherwise, this isn't something we can handle, reject it.
25074       return;
25075     }
25076
25077     const GlobalValue *GV = GA->getGlobal();
25078     // If we require an extra load to get this address, as in PIC mode, we
25079     // can't accept it.
25080     if (isGlobalStubReference(
25081             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25082       return;
25083
25084     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25085                                         GA->getValueType(0), Offset);
25086     break;
25087   }
25088   }
25089
25090   if (Result.getNode()) {
25091     Ops.push_back(Result);
25092     return;
25093   }
25094   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25095 }
25096
25097 std::pair<unsigned, const TargetRegisterClass *>
25098 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25099                                                 const std::string &Constraint,
25100                                                 MVT VT) const {
25101   // First, see if this is a constraint that directly corresponds to an LLVM
25102   // register class.
25103   if (Constraint.size() == 1) {
25104     // GCC Constraint Letters
25105     switch (Constraint[0]) {
25106     default: break;
25107       // TODO: Slight differences here in allocation order and leaving
25108       // RIP in the class. Do they matter any more here than they do
25109       // in the normal allocation?
25110     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25111       if (Subtarget->is64Bit()) {
25112         if (VT == MVT::i32 || VT == MVT::f32)
25113           return std::make_pair(0U, &X86::GR32RegClass);
25114         if (VT == MVT::i16)
25115           return std::make_pair(0U, &X86::GR16RegClass);
25116         if (VT == MVT::i8 || VT == MVT::i1)
25117           return std::make_pair(0U, &X86::GR8RegClass);
25118         if (VT == MVT::i64 || VT == MVT::f64)
25119           return std::make_pair(0U, &X86::GR64RegClass);
25120         break;
25121       }
25122       // 32-bit fallthrough
25123     case 'Q':   // Q_REGS
25124       if (VT == MVT::i32 || VT == MVT::f32)
25125         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25126       if (VT == MVT::i16)
25127         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25128       if (VT == MVT::i8 || VT == MVT::i1)
25129         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25130       if (VT == MVT::i64)
25131         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25132       break;
25133     case 'r':   // GENERAL_REGS
25134     case 'l':   // INDEX_REGS
25135       if (VT == MVT::i8 || VT == MVT::i1)
25136         return std::make_pair(0U, &X86::GR8RegClass);
25137       if (VT == MVT::i16)
25138         return std::make_pair(0U, &X86::GR16RegClass);
25139       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
25140         return std::make_pair(0U, &X86::GR32RegClass);
25141       return std::make_pair(0U, &X86::GR64RegClass);
25142     case 'R':   // LEGACY_REGS
25143       if (VT == MVT::i8 || VT == MVT::i1)
25144         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
25145       if (VT == MVT::i16)
25146         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
25147       if (VT == MVT::i32 || !Subtarget->is64Bit())
25148         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
25149       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
25150     case 'f':  // FP Stack registers.
25151       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
25152       // value to the correct fpstack register class.
25153       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
25154         return std::make_pair(0U, &X86::RFP32RegClass);
25155       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
25156         return std::make_pair(0U, &X86::RFP64RegClass);
25157       return std::make_pair(0U, &X86::RFP80RegClass);
25158     case 'y':   // MMX_REGS if MMX allowed.
25159       if (!Subtarget->hasMMX()) break;
25160       return std::make_pair(0U, &X86::VR64RegClass);
25161     case 'Y':   // SSE_REGS if SSE2 allowed
25162       if (!Subtarget->hasSSE2()) break;
25163       // FALL THROUGH.
25164     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25165       if (!Subtarget->hasSSE1()) break;
25166
25167       switch (VT.SimpleTy) {
25168       default: break;
25169       // Scalar SSE types.
25170       case MVT::f32:
25171       case MVT::i32:
25172         return std::make_pair(0U, &X86::FR32RegClass);
25173       case MVT::f64:
25174       case MVT::i64:
25175         return std::make_pair(0U, &X86::FR64RegClass);
25176       // Vector types.
25177       case MVT::v16i8:
25178       case MVT::v8i16:
25179       case MVT::v4i32:
25180       case MVT::v2i64:
25181       case MVT::v4f32:
25182       case MVT::v2f64:
25183         return std::make_pair(0U, &X86::VR128RegClass);
25184       // AVX types.
25185       case MVT::v32i8:
25186       case MVT::v16i16:
25187       case MVT::v8i32:
25188       case MVT::v4i64:
25189       case MVT::v8f32:
25190       case MVT::v4f64:
25191         return std::make_pair(0U, &X86::VR256RegClass);
25192       case MVT::v8f64:
25193       case MVT::v16f32:
25194       case MVT::v16i32:
25195       case MVT::v8i64:
25196         return std::make_pair(0U, &X86::VR512RegClass);
25197       }
25198       break;
25199     }
25200   }
25201
25202   // Use the default implementation in TargetLowering to convert the register
25203   // constraint into a member of a register class.
25204   std::pair<unsigned, const TargetRegisterClass*> Res;
25205   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25206
25207   // Not found as a standard register?
25208   if (!Res.second) {
25209     // Map st(0) -> st(7) -> ST0
25210     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25211         tolower(Constraint[1]) == 's' &&
25212         tolower(Constraint[2]) == 't' &&
25213         Constraint[3] == '(' &&
25214         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25215         Constraint[5] == ')' &&
25216         Constraint[6] == '}') {
25217
25218       Res.first = X86::FP0+Constraint[4]-'0';
25219       Res.second = &X86::RFP80RegClass;
25220       return Res;
25221     }
25222
25223     // GCC allows "st(0)" to be called just plain "st".
25224     if (StringRef("{st}").equals_lower(Constraint)) {
25225       Res.first = X86::FP0;
25226       Res.second = &X86::RFP80RegClass;
25227       return Res;
25228     }
25229
25230     // flags -> EFLAGS
25231     if (StringRef("{flags}").equals_lower(Constraint)) {
25232       Res.first = X86::EFLAGS;
25233       Res.second = &X86::CCRRegClass;
25234       return Res;
25235     }
25236
25237     // 'A' means EAX + EDX.
25238     if (Constraint == "A") {
25239       Res.first = X86::EAX;
25240       Res.second = &X86::GR32_ADRegClass;
25241       return Res;
25242     }
25243     return Res;
25244   }
25245
25246   // Otherwise, check to see if this is a register class of the wrong value
25247   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25248   // turn into {ax},{dx}.
25249   if (Res.second->hasType(VT))
25250     return Res;   // Correct type already, nothing to do.
25251
25252   // All of the single-register GCC register classes map their values onto
25253   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
25254   // really want an 8-bit or 32-bit register, map to the appropriate register
25255   // class and return the appropriate register.
25256   if (Res.second == &X86::GR16RegClass) {
25257     if (VT == MVT::i8 || VT == MVT::i1) {
25258       unsigned DestReg = 0;
25259       switch (Res.first) {
25260       default: break;
25261       case X86::AX: DestReg = X86::AL; break;
25262       case X86::DX: DestReg = X86::DL; break;
25263       case X86::CX: DestReg = X86::CL; break;
25264       case X86::BX: DestReg = X86::BL; break;
25265       }
25266       if (DestReg) {
25267         Res.first = DestReg;
25268         Res.second = &X86::GR8RegClass;
25269       }
25270     } else if (VT == MVT::i32 || VT == MVT::f32) {
25271       unsigned DestReg = 0;
25272       switch (Res.first) {
25273       default: break;
25274       case X86::AX: DestReg = X86::EAX; break;
25275       case X86::DX: DestReg = X86::EDX; break;
25276       case X86::CX: DestReg = X86::ECX; break;
25277       case X86::BX: DestReg = X86::EBX; break;
25278       case X86::SI: DestReg = X86::ESI; break;
25279       case X86::DI: DestReg = X86::EDI; break;
25280       case X86::BP: DestReg = X86::EBP; break;
25281       case X86::SP: DestReg = X86::ESP; break;
25282       }
25283       if (DestReg) {
25284         Res.first = DestReg;
25285         Res.second = &X86::GR32RegClass;
25286       }
25287     } else if (VT == MVT::i64 || VT == MVT::f64) {
25288       unsigned DestReg = 0;
25289       switch (Res.first) {
25290       default: break;
25291       case X86::AX: DestReg = X86::RAX; break;
25292       case X86::DX: DestReg = X86::RDX; break;
25293       case X86::CX: DestReg = X86::RCX; break;
25294       case X86::BX: DestReg = X86::RBX; break;
25295       case X86::SI: DestReg = X86::RSI; break;
25296       case X86::DI: DestReg = X86::RDI; break;
25297       case X86::BP: DestReg = X86::RBP; break;
25298       case X86::SP: DestReg = X86::RSP; break;
25299       }
25300       if (DestReg) {
25301         Res.first = DestReg;
25302         Res.second = &X86::GR64RegClass;
25303       }
25304     }
25305   } else if (Res.second == &X86::FR32RegClass ||
25306              Res.second == &X86::FR64RegClass ||
25307              Res.second == &X86::VR128RegClass ||
25308              Res.second == &X86::VR256RegClass ||
25309              Res.second == &X86::FR32XRegClass ||
25310              Res.second == &X86::FR64XRegClass ||
25311              Res.second == &X86::VR128XRegClass ||
25312              Res.second == &X86::VR256XRegClass ||
25313              Res.second == &X86::VR512RegClass) {
25314     // Handle references to XMM physical registers that got mapped into the
25315     // wrong class.  This can happen with constraints like {xmm0} where the
25316     // target independent register mapper will just pick the first match it can
25317     // find, ignoring the required type.
25318
25319     if (VT == MVT::f32 || VT == MVT::i32)
25320       Res.second = &X86::FR32RegClass;
25321     else if (VT == MVT::f64 || VT == MVT::i64)
25322       Res.second = &X86::FR64RegClass;
25323     else if (X86::VR128RegClass.hasType(VT))
25324       Res.second = &X86::VR128RegClass;
25325     else if (X86::VR256RegClass.hasType(VT))
25326       Res.second = &X86::VR256RegClass;
25327     else if (X86::VR512RegClass.hasType(VT))
25328       Res.second = &X86::VR512RegClass;
25329   }
25330
25331   return Res;
25332 }
25333
25334 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25335                                             Type *Ty) const {
25336   // Scaling factors are not free at all.
25337   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25338   // will take 2 allocations in the out of order engine instead of 1
25339   // for plain addressing mode, i.e. inst (reg1).
25340   // E.g.,
25341   // vaddps (%rsi,%drx), %ymm0, %ymm1
25342   // Requires two allocations (one for the load, one for the computation)
25343   // whereas:
25344   // vaddps (%rsi), %ymm0, %ymm1
25345   // Requires just 1 allocation, i.e., freeing allocations for other operations
25346   // and having less micro operations to execute.
25347   //
25348   // For some X86 architectures, this is even worse because for instance for
25349   // stores, the complex addressing mode forces the instruction to use the
25350   // "load" ports instead of the dedicated "store" port.
25351   // E.g., on Haswell:
25352   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25353   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25354   if (isLegalAddressingMode(AM, Ty))
25355     // Scale represents reg2 * scale, thus account for 1
25356     // as soon as we use a second register.
25357     return AM.Scale != 0;
25358   return -1;
25359 }
25360
25361 bool X86TargetLowering::isTargetFTOL() const {
25362   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25363 }