AVX-512: fixed UINT_TO_FP operation for 512-bit types.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 static cl::opt<int> ReciprocalEstimateRefinementSteps(
71     "x86-recip-refinement-steps", cl::init(1),
72     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
73              "result of the hardware reciprocal estimate instruction."),
74     cl::NotHidden);
75
76 // Forward declarations.
77 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
78                        SDValue V2);
79
80 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
81                                      const X86Subtarget &STI)
82     : TargetLowering(TM), Subtarget(&STI) {
83   X86ScalarSSEf64 = Subtarget->hasSSE2();
84   X86ScalarSSEf32 = Subtarget->hasSSE1();
85   TD = getDataLayout();
86
87   // Set up the TargetLowering object.
88   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
89
90   // X86 is weird. It always uses i8 for shift amounts and setcc results.
91   setBooleanContents(ZeroOrOneBooleanContent);
92   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
93   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
94
95   // For 64-bit, since we have so many registers, use the ILP scheduler.
96   // For 32-bit, use the register pressure specific scheduling.
97   // For Atom, always use ILP scheduling.
98   if (Subtarget->isAtom())
99     setSchedulingPreference(Sched::ILP);
100   else if (Subtarget->is64Bit())
101     setSchedulingPreference(Sched::ILP);
102   else
103     setSchedulingPreference(Sched::RegPressure);
104   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
105   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
106
107   // Bypass expensive divides on Atom when compiling with O2.
108   if (TM.getOptLevel() >= CodeGenOpt::Default) {
109     if (Subtarget->hasSlowDivide32())
110       addBypassSlowDiv(32, 8);
111     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
112       addBypassSlowDiv(64, 16);
113   }
114
115   if (Subtarget->isTargetKnownWindowsMSVC()) {
116     // Setup Windows compiler runtime calls.
117     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
118     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
119     setLibcallName(RTLIB::SREM_I64, "_allrem");
120     setLibcallName(RTLIB::UREM_I64, "_aullrem");
121     setLibcallName(RTLIB::MUL_I64, "_allmul");
122     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
123     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
124     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
125     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
126     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
127
128     // The _ftol2 runtime function has an unusual calling conv, which
129     // is modeled by a special pseudo-instruction.
130     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
131     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
132     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
133     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
134   }
135
136   if (Subtarget->isTargetDarwin()) {
137     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
138     setUseUnderscoreSetJmp(false);
139     setUseUnderscoreLongJmp(false);
140   } else if (Subtarget->isTargetWindowsGNU()) {
141     // MS runtime is weird: it exports _setjmp, but longjmp!
142     setUseUnderscoreSetJmp(true);
143     setUseUnderscoreLongJmp(false);
144   } else {
145     setUseUnderscoreSetJmp(true);
146     setUseUnderscoreLongJmp(true);
147   }
148
149   // Set up the register classes.
150   addRegisterClass(MVT::i8, &X86::GR8RegClass);
151   addRegisterClass(MVT::i16, &X86::GR16RegClass);
152   addRegisterClass(MVT::i32, &X86::GR32RegClass);
153   if (Subtarget->is64Bit())
154     addRegisterClass(MVT::i64, &X86::GR64RegClass);
155
156   for (MVT VT : MVT::integer_valuetypes())
157     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
158
159   // We don't accept any truncstore of integer registers.
160   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
161   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
162   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
163   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
164   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
165   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
166
167   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
168
169   // SETOEQ and SETUNE require checking two conditions.
170   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
171   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
172   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
173   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
174   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
175   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
176
177   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
178   // operation.
179   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
180   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
181   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
182
183   if (Subtarget->is64Bit()) {
184     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
185     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
186   } else if (!TM.Options.UseSoftFloat) {
187     // We have an algorithm for SSE2->double, and we turn this into a
188     // 64-bit FILD followed by conditional FADD for other targets.
189     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
190     // We have an algorithm for SSE2, and we turn this into a 64-bit
191     // FILD for other targets.
192     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
193   }
194
195   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
196   // this operation.
197   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
198   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
199
200   if (!TM.Options.UseSoftFloat) {
201     // SSE has no i16 to fp conversion, only i32
202     if (X86ScalarSSEf32) {
203       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
204       // f32 and f64 cases are Legal, f80 case is not
205       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
206     } else {
207       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
208       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
209     }
210   } else {
211     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
212     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
213   }
214
215   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
216   // are Legal, f80 is custom lowered.
217   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
218   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
219
220   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
221   // this operation.
222   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
223   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
224
225   if (X86ScalarSSEf32) {
226     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
227     // f32 and f64 cases are Legal, f80 case is not
228     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
229   } else {
230     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
231     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
232   }
233
234   // Handle FP_TO_UINT by promoting the destination to a larger signed
235   // conversion.
236   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
237   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
238   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
239
240   if (Subtarget->is64Bit()) {
241     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
242     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
243   } else if (!TM.Options.UseSoftFloat) {
244     // Since AVX is a superset of SSE3, only check for SSE here.
245     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246       // Expand FP_TO_UINT into a select.
247       // FIXME: We would like to use a Custom expander here eventually to do
248       // the optimal thing for SSE vs. the default expansion in the legalizer.
249       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
250     else
251       // With SSE3 we can use fisttpll to convert to a signed i64; without
252       // SSE, we're stuck with a fistpll.
253       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
254   }
255
256   if (isTargetFTOL()) {
257     // Use the _ftol2 runtime function, which has a pseudo-instruction
258     // to handle its weird calling convention.
259     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
260   }
261
262   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
263   if (!X86ScalarSSEf64) {
264     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
265     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
266     if (Subtarget->is64Bit()) {
267       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
268       // Without SSE, i64->f64 goes through memory.
269       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
270     }
271   }
272
273   // Scalar integer divide and remainder are lowered to use operations that
274   // produce two results, to match the available instructions. This exposes
275   // the two-result form to trivial CSE, which is able to combine x/y and x%y
276   // into a single instruction.
277   //
278   // Scalar integer multiply-high is also lowered to use two-result
279   // operations, to match the available instructions. However, plain multiply
280   // (low) operations are left as Legal, as there are single-result
281   // instructions for this in x86. Using the two-result multiply instructions
282   // when both high and low results are needed must be arranged by dagcombine.
283   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
284     MVT VT = IntVTs[i];
285     setOperationAction(ISD::MULHS, VT, Expand);
286     setOperationAction(ISD::MULHU, VT, Expand);
287     setOperationAction(ISD::SDIV, VT, Expand);
288     setOperationAction(ISD::UDIV, VT, Expand);
289     setOperationAction(ISD::SREM, VT, Expand);
290     setOperationAction(ISD::UREM, VT, Expand);
291
292     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
293     setOperationAction(ISD::ADDC, VT, Custom);
294     setOperationAction(ISD::ADDE, VT, Custom);
295     setOperationAction(ISD::SUBC, VT, Custom);
296     setOperationAction(ISD::SUBE, VT, Custom);
297   }
298
299   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
300   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
301   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
302   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
303   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
304   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
305   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
306   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
307   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
312   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
313   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
314   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
315   if (Subtarget->is64Bit())
316     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
318   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
319   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
320   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
321   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
322   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
323   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
324   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
325
326   // Promote the i8 variants and force them on up to i32 which has a shorter
327   // encoding.
328   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
329   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
330   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
331   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
332   if (Subtarget->hasBMI()) {
333     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
334     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
335     if (Subtarget->is64Bit())
336       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
337   } else {
338     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
339     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
340     if (Subtarget->is64Bit())
341       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
342   }
343
344   if (Subtarget->hasLZCNT()) {
345     // When promoting the i8 variants, force them to i32 for a shorter
346     // encoding.
347     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
348     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
350     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
352     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
353     if (Subtarget->is64Bit())
354       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
355   } else {
356     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
357     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
358     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
361     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
362     if (Subtarget->is64Bit()) {
363       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
364       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
365     }
366   }
367
368   // Special handling for half-precision floating point conversions.
369   // If we don't have F16C support, then lower half float conversions
370   // into library calls.
371   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
372     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
374   }
375
376   // There's never any support for operations beyond MVT::f32.
377   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
381
382   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
388
389   if (Subtarget->hasPOPCNT()) {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
391   } else {
392     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
394     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
397   }
398
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400
401   if (!Subtarget->hasMOVBE())
402     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
403
404   // These should be promoted to a larger select which is supported.
405   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
406   // X86 wants to expand cmov itself.
407   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
408   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
412   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
419   if (Subtarget->is64Bit()) {
420     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
421     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
422   }
423   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
424   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426   // support continuation, user-level threading, and etc.. As a result, no
427   // other SjLj exception interfaces are implemented and please don't build
428   // your own exception handling based on them.
429   // LLVM/Clang supports zero-cost DWARF exception handling.
430   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
432
433   // Darwin ABI issue.
434   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
435   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
436   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
437   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
438   if (Subtarget->is64Bit())
439     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
441   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
442   if (Subtarget->is64Bit()) {
443     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
444     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
445     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
446     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
447     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
448   }
449   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
451   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
452   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
455     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
456     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
457   }
458
459   if (Subtarget->hasSSE1())
460     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
461
462   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
463
464   // Expand certain atomics
465   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
466     MVT VT = IntVTs[i];
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
470   }
471
472   if (Subtarget->hasCmpxchg16b()) {
473     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
474   }
475
476   // FIXME - use subtarget debug flags
477   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
480   }
481
482   if (Subtarget->is64Bit()) {
483     setExceptionPointerRegister(X86::RAX);
484     setExceptionSelectorRegister(X86::RDX);
485   } else {
486     setExceptionPointerRegister(X86::EAX);
487     setExceptionSelectorRegister(X86::EDX);
488   }
489   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
491
492   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
494
495   setOperationAction(ISD::TRAP, MVT::Other, Legal);
496   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
497
498   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
500   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
501   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
502     // TargetInfo::X86_64ABIBuiltinVaList
503     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
505   } else {
506     // TargetInfo::CharPtrBuiltinVaList
507     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
508     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
509   }
510
511   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
512   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
513
514   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
515
516   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
517   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
518   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
519
520   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
521     // f32 and f64 use SSE.
522     // Set up the FP register classes.
523     addRegisterClass(MVT::f32, &X86::FR32RegClass);
524     addRegisterClass(MVT::f64, &X86::FR64RegClass);
525
526     // Use ANDPD to simulate FABS.
527     setOperationAction(ISD::FABS , MVT::f64, Custom);
528     setOperationAction(ISD::FABS , MVT::f32, Custom);
529
530     // Use XORP to simulate FNEG.
531     setOperationAction(ISD::FNEG , MVT::f64, Custom);
532     setOperationAction(ISD::FNEG , MVT::f32, Custom);
533
534     // Use ANDPD and ORPD to simulate FCOPYSIGN.
535     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
536     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
537
538     // Lower this to FGETSIGNx86 plus an AND.
539     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
540     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
541
542     // We don't support sin/cos/fmod
543     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
544     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
545     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
546     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
547     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
548     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
549
550     // Expand FP immediates into loads from the stack, except for the special
551     // cases we handle.
552     addLegalFPImmediate(APFloat(+0.0)); // xorpd
553     addLegalFPImmediate(APFloat(+0.0f)); // xorps
554   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
555     // Use SSE for f32, x87 for f64.
556     // Set up the FP register classes.
557     addRegisterClass(MVT::f32, &X86::FR32RegClass);
558     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
559
560     // Use ANDPS to simulate FABS.
561     setOperationAction(ISD::FABS , MVT::f32, Custom);
562
563     // Use XORP to simulate FNEG.
564     setOperationAction(ISD::FNEG , MVT::f32, Custom);
565
566     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
567
568     // Use ANDPS and ORPS to simulate FCOPYSIGN.
569     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
570     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571
572     // We don't support sin/cos/fmod
573     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
574     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
575     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
576
577     // Special cases we handle for FP constants.
578     addLegalFPImmediate(APFloat(+0.0f)); // xorps
579     addLegalFPImmediate(APFloat(+0.0)); // FLD0
580     addLegalFPImmediate(APFloat(+1.0)); // FLD1
581     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
582     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
583
584     if (!TM.Options.UnsafeFPMath) {
585       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
586       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
587       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
588     }
589   } else if (!TM.Options.UseSoftFloat) {
590     // f32 and f64 in x87.
591     // Set up the FP register classes.
592     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
593     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
594
595     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
596     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
597     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
599
600     if (!TM.Options.UnsafeFPMath) {
601       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
602       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
603       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
604       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
605       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
606       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
607     }
608     addLegalFPImmediate(APFloat(+0.0)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
612     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
613     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
614     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
615     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
616   }
617
618   // We don't support FMA.
619   setOperationAction(ISD::FMA, MVT::f64, Expand);
620   setOperationAction(ISD::FMA, MVT::f32, Expand);
621
622   // Long double always uses X87.
623   if (!TM.Options.UseSoftFloat) {
624     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
625     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
626     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
627     {
628       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
629       addLegalFPImmediate(TmpFlt);  // FLD0
630       TmpFlt.changeSign();
631       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
632
633       bool ignored;
634       APFloat TmpFlt2(+1.0);
635       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
636                       &ignored);
637       addLegalFPImmediate(TmpFlt2);  // FLD1
638       TmpFlt2.changeSign();
639       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
640     }
641
642     if (!TM.Options.UnsafeFPMath) {
643       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
644       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
645       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
646     }
647
648     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
649     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
650     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
651     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
652     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
653     setOperationAction(ISD::FMA, MVT::f80, Expand);
654   }
655
656   // Always use a library call for pow.
657   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
658   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
659   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
660
661   setOperationAction(ISD::FLOG, MVT::f80, Expand);
662   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
663   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
664   setOperationAction(ISD::FEXP, MVT::f80, Expand);
665   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
666   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
667   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
668
669   // First set operation action for all vector types to either promote
670   // (for widening) or expand (for scalarization). Then we will selectively
671   // turn on ones that can be effectively codegen'd.
672   for (MVT VT : MVT::vector_valuetypes()) {
673     setOperationAction(ISD::ADD , VT, Expand);
674     setOperationAction(ISD::SUB , VT, Expand);
675     setOperationAction(ISD::FADD, VT, Expand);
676     setOperationAction(ISD::FNEG, VT, Expand);
677     setOperationAction(ISD::FSUB, VT, Expand);
678     setOperationAction(ISD::MUL , VT, Expand);
679     setOperationAction(ISD::FMUL, VT, Expand);
680     setOperationAction(ISD::SDIV, VT, Expand);
681     setOperationAction(ISD::UDIV, VT, Expand);
682     setOperationAction(ISD::FDIV, VT, Expand);
683     setOperationAction(ISD::SREM, VT, Expand);
684     setOperationAction(ISD::UREM, VT, Expand);
685     setOperationAction(ISD::LOAD, VT, Expand);
686     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
687     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
688     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
689     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
690     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
691     setOperationAction(ISD::FABS, VT, Expand);
692     setOperationAction(ISD::FSIN, VT, Expand);
693     setOperationAction(ISD::FSINCOS, VT, Expand);
694     setOperationAction(ISD::FCOS, VT, Expand);
695     setOperationAction(ISD::FSINCOS, VT, Expand);
696     setOperationAction(ISD::FREM, VT, Expand);
697     setOperationAction(ISD::FMA,  VT, Expand);
698     setOperationAction(ISD::FPOWI, VT, Expand);
699     setOperationAction(ISD::FSQRT, VT, Expand);
700     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
701     setOperationAction(ISD::FFLOOR, VT, Expand);
702     setOperationAction(ISD::FCEIL, VT, Expand);
703     setOperationAction(ISD::FTRUNC, VT, Expand);
704     setOperationAction(ISD::FRINT, VT, Expand);
705     setOperationAction(ISD::FNEARBYINT, VT, Expand);
706     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
707     setOperationAction(ISD::MULHS, VT, Expand);
708     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
709     setOperationAction(ISD::MULHU, VT, Expand);
710     setOperationAction(ISD::SDIVREM, VT, Expand);
711     setOperationAction(ISD::UDIVREM, VT, Expand);
712     setOperationAction(ISD::FPOW, VT, Expand);
713     setOperationAction(ISD::CTPOP, VT, Expand);
714     setOperationAction(ISD::CTTZ, VT, Expand);
715     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
716     setOperationAction(ISD::CTLZ, VT, Expand);
717     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
718     setOperationAction(ISD::SHL, VT, Expand);
719     setOperationAction(ISD::SRA, VT, Expand);
720     setOperationAction(ISD::SRL, VT, Expand);
721     setOperationAction(ISD::ROTL, VT, Expand);
722     setOperationAction(ISD::ROTR, VT, Expand);
723     setOperationAction(ISD::BSWAP, VT, Expand);
724     setOperationAction(ISD::SETCC, VT, Expand);
725     setOperationAction(ISD::FLOG, VT, Expand);
726     setOperationAction(ISD::FLOG2, VT, Expand);
727     setOperationAction(ISD::FLOG10, VT, Expand);
728     setOperationAction(ISD::FEXP, VT, Expand);
729     setOperationAction(ISD::FEXP2, VT, Expand);
730     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
731     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
732     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
733     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
734     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
735     setOperationAction(ISD::TRUNCATE, VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
737     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
738     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
739     setOperationAction(ISD::VSELECT, VT, Expand);
740     setOperationAction(ISD::SELECT_CC, VT, Expand);
741     for (MVT InnerVT : MVT::vector_valuetypes()) {
742       setTruncStoreAction(InnerVT, VT, Expand);
743
744       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
745       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
746
747       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
748       // types, we have to deal with them whether we ask for Expansion or not.
749       // Setting Expand causes its own optimisation problems though, so leave
750       // them legal.
751       if (VT.getVectorElementType() == MVT::i1)
752         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
753     }
754   }
755
756   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
757   // with -msoft-float, disable use of MMX as well.
758   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
759     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
760     // No operations on x86mmx supported, everything uses intrinsics.
761   }
762
763   // MMX-sized vectors (other than x86mmx) are expected to be expanded
764   // into smaller operations.
765   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
766     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
767     setOperationAction(ISD::AND,                MMXTy,      Expand);
768     setOperationAction(ISD::OR,                 MMXTy,      Expand);
769     setOperationAction(ISD::XOR,                MMXTy,      Expand);
770     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
771     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
772     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
773   }
774   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
775
776   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
777     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
778
779     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
780     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
783     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
784     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
785     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
786     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
787     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
788     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
789     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
790     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
791     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
792     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
793   }
794
795   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
796     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
797
798     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
799     // registers cannot be used even for integer operations.
800     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
801     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
802     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
803     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
804
805     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
806     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
807     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
808     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
809     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
810     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
811     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
812     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
813     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
814     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
815     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
816     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
817     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
818     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
819     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
820     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
821     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
822     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
825     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
826     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
827     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
828
829     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
830     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
831     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
832     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
833
834     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
835     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
836     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
837     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
838     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
839
840     // Only provide customized ctpop vector bit twiddling for vector types we
841     // know to perform better than using the popcnt instructions on each vector
842     // element. If popcnt isn't supported, always provide the custom version.
843     if (!Subtarget->hasPOPCNT()) {
844       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
845       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
846     }
847
848     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
849     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
850       MVT VT = (MVT::SimpleValueType)i;
851       // Do not attempt to custom lower non-power-of-2 vectors
852       if (!isPowerOf2_32(VT.getVectorNumElements()))
853         continue;
854       // Do not attempt to custom lower non-128-bit vectors
855       if (!VT.is128BitVector())
856         continue;
857       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
858       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
859       setOperationAction(ISD::VSELECT,            VT, Custom);
860       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
861     }
862
863     // We support custom legalizing of sext and anyext loads for specific
864     // memory vector types which we can load as a scalar (or sequence of
865     // scalars) and extend in-register to a legal 128-bit vector type. For sext
866     // loads these must work with a single scalar load.
867     for (MVT VT : MVT::integer_vector_valuetypes()) {
868       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
869       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
870       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
871       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
877     }
878
879     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
880     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
881     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
882     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
883     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
884     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
885     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
886     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
887
888     if (Subtarget->is64Bit()) {
889       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
890       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
891     }
892
893     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
894     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
895       MVT VT = (MVT::SimpleValueType)i;
896
897       // Do not attempt to promote non-128-bit vectors
898       if (!VT.is128BitVector())
899         continue;
900
901       setOperationAction(ISD::AND,    VT, Promote);
902       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
903       setOperationAction(ISD::OR,     VT, Promote);
904       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
905       setOperationAction(ISD::XOR,    VT, Promote);
906       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
907       setOperationAction(ISD::LOAD,   VT, Promote);
908       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
909       setOperationAction(ISD::SELECT, VT, Promote);
910       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
911     }
912
913     // Custom lower v2i64 and v2f64 selects.
914     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
915     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
916     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
917     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
918
919     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
920     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
921
922     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
923     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
924     // As there is no 64-bit GPR available, we need build a special custom
925     // sequence to convert from v2i32 to v2f32.
926     if (!Subtarget->is64Bit())
927       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
928
929     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
930     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
931
932     for (MVT VT : MVT::fp_vector_valuetypes())
933       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
934
935     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
936     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
937     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
938   }
939
940   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
941     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
942       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
943       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
944       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
945       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
946       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
947     }
948
949     // FIXME: Do we need to handle scalar-to-vector here?
950     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
951
952     // We directly match byte blends in the backend as they match the VSELECT
953     // condition form.
954     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
955
956     // SSE41 brings specific instructions for doing vector sign extend even in
957     // cases where we don't have SRA.
958     for (MVT VT : MVT::integer_vector_valuetypes()) {
959       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
960       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
961       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
962     }
963
964     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
965     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
966     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
967     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
968     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
969     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
970     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
971
972     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
973     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
974     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
975     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
976     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
977     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
978
979     // i8 and i16 vectors are custom because the source register and source
980     // source memory operand types are not the same width.  f32 vectors are
981     // custom since the immediate controlling the insert encodes additional
982     // information.
983     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
984     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
985     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
986     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
987
988     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
989     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
990     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
991     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
992
993     // FIXME: these should be Legal, but that's only for the case where
994     // the index is constant.  For now custom expand to deal with that.
995     if (Subtarget->is64Bit()) {
996       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
997       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
998     }
999   }
1000
1001   if (Subtarget->hasSSE2()) {
1002     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1003     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1004
1005     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1006     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1007
1008     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1009     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1010
1011     // In the customized shift lowering, the legal cases in AVX2 will be
1012     // recognized.
1013     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1014     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1015
1016     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1017     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1018
1019     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1020   }
1021
1022   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1023     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1024     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1025     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1026     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1027     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1028     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1029
1030     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1031     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1032     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1033
1034     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1035     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1036     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1037     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1038     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1039     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1040     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1041     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1042     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1043     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1044     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1045     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1046
1047     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1048     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1049     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1050     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1051     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1052     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1053     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1054     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1055     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1056     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1057     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1058     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1059
1060     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1061     // even though v8i16 is a legal type.
1062     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1063     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1064     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1065
1066     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1067     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1068     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1069
1070     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1071     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1072
1073     for (MVT VT : MVT::fp_vector_valuetypes())
1074       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1075
1076     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1077     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1078
1079     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1080     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1081
1082     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1083     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1084
1085     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1086     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1087     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1088     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1089
1090     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1091     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1092     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1093
1094     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1095     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1096     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1097     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1098     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1099     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1100     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1101     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1102     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1103     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1104     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1105     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1106
1107     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1108       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1109       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1110       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1111       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1112       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1113       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1114     }
1115
1116     if (Subtarget->hasInt256()) {
1117       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1118       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1119       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1120       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1121
1122       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1123       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1124       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1125       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1126
1127       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1128       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1129       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1130       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1131
1132       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1133       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1134       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1135       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1136
1137       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1138       // when we have a 256bit-wide blend with immediate.
1139       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1140
1141       // Only provide customized ctpop vector bit twiddling for vector types we
1142       // know to perform better than using the popcnt instructions on each
1143       // vector element. If popcnt isn't supported, always provide the custom
1144       // version.
1145       if (!Subtarget->hasPOPCNT())
1146         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1147
1148       // Custom CTPOP always performs better on natively supported v8i32
1149       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1150
1151       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1152       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1153       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1154       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1155       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1156       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1157       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1158
1159       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1160       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1161       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1162       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1163       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1164       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1165     } else {
1166       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1167       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1168       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1169       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1170
1171       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1172       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1173       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1174       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1175
1176       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1177       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1178       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1179       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1180     }
1181
1182     // In the customized shift lowering, the legal cases in AVX2 will be
1183     // recognized.
1184     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1185     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1186
1187     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1188     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1189
1190     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1191
1192     // Custom lower several nodes for 256-bit types.
1193     for (MVT VT : MVT::vector_valuetypes()) {
1194       if (VT.getScalarSizeInBits() >= 32) {
1195         setOperationAction(ISD::MLOAD,  VT, Legal);
1196         setOperationAction(ISD::MSTORE, VT, Legal);
1197       }
1198       // Extract subvector is special because the value type
1199       // (result) is 128-bit but the source is 256-bit wide.
1200       if (VT.is128BitVector()) {
1201         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1202       }
1203       // Do not attempt to custom lower other non-256-bit vectors
1204       if (!VT.is256BitVector())
1205         continue;
1206
1207       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1208       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1209       setOperationAction(ISD::VSELECT,            VT, Custom);
1210       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1211       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1212       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1213       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1214       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1215     }
1216
1217     if (Subtarget->hasInt256())
1218       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1219
1220
1221     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1222     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1223       MVT VT = (MVT::SimpleValueType)i;
1224
1225       // Do not attempt to promote non-256-bit vectors
1226       if (!VT.is256BitVector())
1227         continue;
1228
1229       setOperationAction(ISD::AND,    VT, Promote);
1230       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1231       setOperationAction(ISD::OR,     VT, Promote);
1232       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1233       setOperationAction(ISD::XOR,    VT, Promote);
1234       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1235       setOperationAction(ISD::LOAD,   VT, Promote);
1236       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1237       setOperationAction(ISD::SELECT, VT, Promote);
1238       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1239     }
1240   }
1241
1242   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1243     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1244     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1245     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1246     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1247
1248     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1249     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1250     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1251
1252     for (MVT VT : MVT::fp_vector_valuetypes())
1253       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1254
1255     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1256     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1257     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1258     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1259     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1260     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1261     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1262     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1263     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1264     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1265
1266     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1267     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1268     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1269     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1270     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1271     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1272
1273     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1274     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1275     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1276     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1277     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1278     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1279     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1280     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1281
1282     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1283     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1284     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1285     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1286     if (Subtarget->is64Bit()) {
1287       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1288       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1289       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1290       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1291     }
1292     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1293     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1294     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1295     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1296     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1297     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1298     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1299     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1300     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1301     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1302     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1303     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1304     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1305     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1306     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1307     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1308
1309     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1310     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1311     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1312     if (Subtarget->hasDQI()) {
1313       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1314       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1315     }
1316     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1317     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1318     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1319     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1320     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1321     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1322     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1323     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1324     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1325     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1326     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1327     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1328     if (Subtarget->hasDQI()) {
1329       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1330       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1331     }
1332     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1333     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1334     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1335     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1336     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1337     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1338     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1339     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1340     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1341     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1342
1343     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1344     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1345     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1346     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1347     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1348
1349     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1350     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1351
1352     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1353
1354     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1355     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1356     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1357     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1358     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1359     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1360     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1361     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1362     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1363
1364     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1365     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1366
1367     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1368     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1369
1370     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1371
1372     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1373     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1374
1375     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1376     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1377
1378     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1379     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1380
1381     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1382     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1383     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1384     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1385     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1386     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1387
1388     if (Subtarget->hasCDI()) {
1389       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1390       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1391     }
1392     if (Subtarget->hasDQI()) {
1393       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1394       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1395       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1396     }
1397     // Custom lower several nodes.
1398     for (MVT VT : MVT::vector_valuetypes()) {
1399       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1400       if (EltSize == 1) {
1401         setOperationAction(ISD::AND, VT, Legal);
1402         setOperationAction(ISD::OR,  VT, Legal);
1403         setOperationAction(ISD::XOR,  VT, Legal);
1404       }
1405       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1406         setOperationAction(ISD::MGATHER,  VT, Custom);
1407         setOperationAction(ISD::MSCATTER, VT, Custom);
1408       }
1409       // Extract subvector is special because the value type
1410       // (result) is 256/128-bit but the source is 512-bit wide.
1411       if (VT.is128BitVector() || VT.is256BitVector()) {
1412         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1413       }
1414       if (VT.getVectorElementType() == MVT::i1)
1415         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1416
1417       // Do not attempt to custom lower other non-512-bit vectors
1418       if (!VT.is512BitVector())
1419         continue;
1420
1421       if (EltSize >= 32) {
1422         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1423         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1424         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1425         setOperationAction(ISD::VSELECT,             VT, Legal);
1426         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1427         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1428         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1429         setOperationAction(ISD::MLOAD,               VT, Legal);
1430         setOperationAction(ISD::MSTORE,              VT, Legal);
1431       }
1432     }
1433     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1434       MVT VT = (MVT::SimpleValueType)i;
1435
1436       // Do not attempt to promote non-512-bit vectors.
1437       if (!VT.is512BitVector())
1438         continue;
1439
1440       setOperationAction(ISD::SELECT, VT, Promote);
1441       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1442     }
1443   }// has  AVX-512
1444
1445   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1446     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1447     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1448
1449     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1450     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1451
1452     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1453     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1454     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1455     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1456     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1457     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1458     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1459     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1460     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1461     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1462     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1463     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1464     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1465
1466     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1467       const MVT VT = (MVT::SimpleValueType)i;
1468
1469       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1470
1471       // Do not attempt to promote non-512-bit vectors.
1472       if (!VT.is512BitVector())
1473         continue;
1474
1475       if (EltSize < 32) {
1476         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1477         setOperationAction(ISD::VSELECT,             VT, Legal);
1478       }
1479     }
1480   }
1481
1482   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1483     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1484     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1485
1486     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1487     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1488     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1489     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1490     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1491     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1492
1493     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1494     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1495     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1496     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1497     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1498     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1499   }
1500
1501   // We want to custom lower some of our intrinsics.
1502   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1503   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1504   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1505   if (!Subtarget->is64Bit())
1506     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1507
1508   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1509   // handle type legalization for these operations here.
1510   //
1511   // FIXME: We really should do custom legalization for addition and
1512   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1513   // than generic legalization for 64-bit multiplication-with-overflow, though.
1514   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1515     // Add/Sub/Mul with overflow operations are custom lowered.
1516     MVT VT = IntVTs[i];
1517     setOperationAction(ISD::SADDO, VT, Custom);
1518     setOperationAction(ISD::UADDO, VT, Custom);
1519     setOperationAction(ISD::SSUBO, VT, Custom);
1520     setOperationAction(ISD::USUBO, VT, Custom);
1521     setOperationAction(ISD::SMULO, VT, Custom);
1522     setOperationAction(ISD::UMULO, VT, Custom);
1523   }
1524
1525
1526   if (!Subtarget->is64Bit()) {
1527     // These libcalls are not available in 32-bit.
1528     setLibcallName(RTLIB::SHL_I128, nullptr);
1529     setLibcallName(RTLIB::SRL_I128, nullptr);
1530     setLibcallName(RTLIB::SRA_I128, nullptr);
1531   }
1532
1533   // Combine sin / cos into one node or libcall if possible.
1534   if (Subtarget->hasSinCos()) {
1535     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1536     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1537     if (Subtarget->isTargetDarwin()) {
1538       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1539       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1540       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1541       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1542     }
1543   }
1544
1545   if (Subtarget->isTargetWin64()) {
1546     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1547     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1548     setOperationAction(ISD::SREM, MVT::i128, Custom);
1549     setOperationAction(ISD::UREM, MVT::i128, Custom);
1550     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1551     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1552   }
1553
1554   // We have target-specific dag combine patterns for the following nodes:
1555   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1556   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1557   setTargetDAGCombine(ISD::BITCAST);
1558   setTargetDAGCombine(ISD::VSELECT);
1559   setTargetDAGCombine(ISD::SELECT);
1560   setTargetDAGCombine(ISD::SHL);
1561   setTargetDAGCombine(ISD::SRA);
1562   setTargetDAGCombine(ISD::SRL);
1563   setTargetDAGCombine(ISD::OR);
1564   setTargetDAGCombine(ISD::AND);
1565   setTargetDAGCombine(ISD::ADD);
1566   setTargetDAGCombine(ISD::FADD);
1567   setTargetDAGCombine(ISD::FSUB);
1568   setTargetDAGCombine(ISD::FMA);
1569   setTargetDAGCombine(ISD::SUB);
1570   setTargetDAGCombine(ISD::LOAD);
1571   setTargetDAGCombine(ISD::MLOAD);
1572   setTargetDAGCombine(ISD::STORE);
1573   setTargetDAGCombine(ISD::MSTORE);
1574   setTargetDAGCombine(ISD::ZERO_EXTEND);
1575   setTargetDAGCombine(ISD::ANY_EXTEND);
1576   setTargetDAGCombine(ISD::SIGN_EXTEND);
1577   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1578   setTargetDAGCombine(ISD::TRUNCATE);
1579   setTargetDAGCombine(ISD::SINT_TO_FP);
1580   setTargetDAGCombine(ISD::SETCC);
1581   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1582   setTargetDAGCombine(ISD::BUILD_VECTOR);
1583   setTargetDAGCombine(ISD::MUL);
1584   setTargetDAGCombine(ISD::XOR);
1585
1586   computeRegisterProperties(Subtarget->getRegisterInfo());
1587
1588   // On Darwin, -Os means optimize for size without hurting performance,
1589   // do not reduce the limit.
1590   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1591   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1592   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1593   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1594   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1595   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1596   setPrefLoopAlignment(4); // 2^4 bytes.
1597
1598   // Predictable cmov don't hurt on atom because it's in-order.
1599   PredictableSelectIsExpensive = !Subtarget->isAtom();
1600   EnableExtLdPromotion = true;
1601   setPrefFunctionAlignment(4); // 2^4 bytes.
1602
1603   verifyIntrinsicTables();
1604 }
1605
1606 // This has so far only been implemented for 64-bit MachO.
1607 bool X86TargetLowering::useLoadStackGuardNode() const {
1608   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1609 }
1610
1611 TargetLoweringBase::LegalizeTypeAction
1612 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1613   if (ExperimentalVectorWideningLegalization &&
1614       VT.getVectorNumElements() != 1 &&
1615       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1616     return TypeWidenVector;
1617
1618   return TargetLoweringBase::getPreferredVectorAction(VT);
1619 }
1620
1621 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1622   if (!VT.isVector())
1623     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1624
1625   const unsigned NumElts = VT.getVectorNumElements();
1626   const EVT EltVT = VT.getVectorElementType();
1627   if (VT.is512BitVector()) {
1628     if (Subtarget->hasAVX512())
1629       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1630           EltVT == MVT::f32 || EltVT == MVT::f64)
1631         switch(NumElts) {
1632         case  8: return MVT::v8i1;
1633         case 16: return MVT::v16i1;
1634       }
1635     if (Subtarget->hasBWI())
1636       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1637         switch(NumElts) {
1638         case 32: return MVT::v32i1;
1639         case 64: return MVT::v64i1;
1640       }
1641   }
1642
1643   if (VT.is256BitVector() || VT.is128BitVector()) {
1644     if (Subtarget->hasVLX())
1645       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1646           EltVT == MVT::f32 || EltVT == MVT::f64)
1647         switch(NumElts) {
1648         case 2: return MVT::v2i1;
1649         case 4: return MVT::v4i1;
1650         case 8: return MVT::v8i1;
1651       }
1652     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1653       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1654         switch(NumElts) {
1655         case  8: return MVT::v8i1;
1656         case 16: return MVT::v16i1;
1657         case 32: return MVT::v32i1;
1658       }
1659   }
1660
1661   return VT.changeVectorElementTypeToInteger();
1662 }
1663
1664 /// Helper for getByValTypeAlignment to determine
1665 /// the desired ByVal argument alignment.
1666 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1667   if (MaxAlign == 16)
1668     return;
1669   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1670     if (VTy->getBitWidth() == 128)
1671       MaxAlign = 16;
1672   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1673     unsigned EltAlign = 0;
1674     getMaxByValAlign(ATy->getElementType(), EltAlign);
1675     if (EltAlign > MaxAlign)
1676       MaxAlign = EltAlign;
1677   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1678     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1679       unsigned EltAlign = 0;
1680       getMaxByValAlign(STy->getElementType(i), EltAlign);
1681       if (EltAlign > MaxAlign)
1682         MaxAlign = EltAlign;
1683       if (MaxAlign == 16)
1684         break;
1685     }
1686   }
1687 }
1688
1689 /// Return the desired alignment for ByVal aggregate
1690 /// function arguments in the caller parameter area. For X86, aggregates
1691 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1692 /// are at 4-byte boundaries.
1693 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1694   if (Subtarget->is64Bit()) {
1695     // Max of 8 and alignment of type.
1696     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1697     if (TyAlign > 8)
1698       return TyAlign;
1699     return 8;
1700   }
1701
1702   unsigned Align = 4;
1703   if (Subtarget->hasSSE1())
1704     getMaxByValAlign(Ty, Align);
1705   return Align;
1706 }
1707
1708 /// Returns the target specific optimal type for load
1709 /// and store operations as a result of memset, memcpy, and memmove
1710 /// lowering. If DstAlign is zero that means it's safe to destination
1711 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1712 /// means there isn't a need to check it against alignment requirement,
1713 /// probably because the source does not need to be loaded. If 'IsMemset' is
1714 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1715 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1716 /// source is constant so it does not need to be loaded.
1717 /// It returns EVT::Other if the type should be determined using generic
1718 /// target-independent logic.
1719 EVT
1720 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1721                                        unsigned DstAlign, unsigned SrcAlign,
1722                                        bool IsMemset, bool ZeroMemset,
1723                                        bool MemcpyStrSrc,
1724                                        MachineFunction &MF) const {
1725   const Function *F = MF.getFunction();
1726   if ((!IsMemset || ZeroMemset) &&
1727       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1728     if (Size >= 16 &&
1729         (Subtarget->isUnalignedMemAccessFast() ||
1730          ((DstAlign == 0 || DstAlign >= 16) &&
1731           (SrcAlign == 0 || SrcAlign >= 16)))) {
1732       if (Size >= 32) {
1733         if (Subtarget->hasInt256())
1734           return MVT::v8i32;
1735         if (Subtarget->hasFp256())
1736           return MVT::v8f32;
1737       }
1738       if (Subtarget->hasSSE2())
1739         return MVT::v4i32;
1740       if (Subtarget->hasSSE1())
1741         return MVT::v4f32;
1742     } else if (!MemcpyStrSrc && Size >= 8 &&
1743                !Subtarget->is64Bit() &&
1744                Subtarget->hasSSE2()) {
1745       // Do not use f64 to lower memcpy if source is string constant. It's
1746       // better to use i32 to avoid the loads.
1747       return MVT::f64;
1748     }
1749   }
1750   if (Subtarget->is64Bit() && Size >= 8)
1751     return MVT::i64;
1752   return MVT::i32;
1753 }
1754
1755 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1756   if (VT == MVT::f32)
1757     return X86ScalarSSEf32;
1758   else if (VT == MVT::f64)
1759     return X86ScalarSSEf64;
1760   return true;
1761 }
1762
1763 bool
1764 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1765                                                   unsigned,
1766                                                   unsigned,
1767                                                   bool *Fast) const {
1768   if (Fast)
1769     *Fast = Subtarget->isUnalignedMemAccessFast();
1770   return true;
1771 }
1772
1773 /// Return the entry encoding for a jump table in the
1774 /// current function.  The returned value is a member of the
1775 /// MachineJumpTableInfo::JTEntryKind enum.
1776 unsigned X86TargetLowering::getJumpTableEncoding() const {
1777   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1778   // symbol.
1779   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1780       Subtarget->isPICStyleGOT())
1781     return MachineJumpTableInfo::EK_Custom32;
1782
1783   // Otherwise, use the normal jump table encoding heuristics.
1784   return TargetLowering::getJumpTableEncoding();
1785 }
1786
1787 const MCExpr *
1788 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1789                                              const MachineBasicBlock *MBB,
1790                                              unsigned uid,MCContext &Ctx) const{
1791   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1792          Subtarget->isPICStyleGOT());
1793   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1794   // entries.
1795   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1796                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1797 }
1798
1799 /// Returns relocation base for the given PIC jumptable.
1800 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1801                                                     SelectionDAG &DAG) const {
1802   if (!Subtarget->is64Bit())
1803     // This doesn't have SDLoc associated with it, but is not really the
1804     // same as a Register.
1805     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1806   return Table;
1807 }
1808
1809 /// This returns the relocation base for the given PIC jumptable,
1810 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1811 const MCExpr *X86TargetLowering::
1812 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1813                              MCContext &Ctx) const {
1814   // X86-64 uses RIP relative addressing based on the jump table label.
1815   if (Subtarget->isPICStyleRIPRel())
1816     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1817
1818   // Otherwise, the reference is relative to the PIC base.
1819   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1820 }
1821
1822 std::pair<const TargetRegisterClass *, uint8_t>
1823 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1824                                            MVT VT) const {
1825   const TargetRegisterClass *RRC = nullptr;
1826   uint8_t Cost = 1;
1827   switch (VT.SimpleTy) {
1828   default:
1829     return TargetLowering::findRepresentativeClass(TRI, VT);
1830   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1831     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1832     break;
1833   case MVT::x86mmx:
1834     RRC = &X86::VR64RegClass;
1835     break;
1836   case MVT::f32: case MVT::f64:
1837   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1838   case MVT::v4f32: case MVT::v2f64:
1839   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1840   case MVT::v4f64:
1841     RRC = &X86::VR128RegClass;
1842     break;
1843   }
1844   return std::make_pair(RRC, Cost);
1845 }
1846
1847 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1848                                                unsigned &Offset) const {
1849   if (!Subtarget->isTargetLinux())
1850     return false;
1851
1852   if (Subtarget->is64Bit()) {
1853     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1854     Offset = 0x28;
1855     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1856       AddressSpace = 256;
1857     else
1858       AddressSpace = 257;
1859   } else {
1860     // %gs:0x14 on i386
1861     Offset = 0x14;
1862     AddressSpace = 256;
1863   }
1864   return true;
1865 }
1866
1867 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1868                                             unsigned DestAS) const {
1869   assert(SrcAS != DestAS && "Expected different address spaces!");
1870
1871   return SrcAS < 256 && DestAS < 256;
1872 }
1873
1874 //===----------------------------------------------------------------------===//
1875 //               Return Value Calling Convention Implementation
1876 //===----------------------------------------------------------------------===//
1877
1878 #include "X86GenCallingConv.inc"
1879
1880 bool
1881 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1882                                   MachineFunction &MF, bool isVarArg,
1883                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1884                         LLVMContext &Context) const {
1885   SmallVector<CCValAssign, 16> RVLocs;
1886   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1887   return CCInfo.CheckReturn(Outs, RetCC_X86);
1888 }
1889
1890 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1891   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1892   return ScratchRegs;
1893 }
1894
1895 SDValue
1896 X86TargetLowering::LowerReturn(SDValue Chain,
1897                                CallingConv::ID CallConv, bool isVarArg,
1898                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1899                                const SmallVectorImpl<SDValue> &OutVals,
1900                                SDLoc dl, SelectionDAG &DAG) const {
1901   MachineFunction &MF = DAG.getMachineFunction();
1902   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1903
1904   SmallVector<CCValAssign, 16> RVLocs;
1905   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1906   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1907
1908   SDValue Flag;
1909   SmallVector<SDValue, 6> RetOps;
1910   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1911   // Operand #1 = Bytes To Pop
1912   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1913                    MVT::i16));
1914
1915   // Copy the result values into the output registers.
1916   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1917     CCValAssign &VA = RVLocs[i];
1918     assert(VA.isRegLoc() && "Can only return in registers!");
1919     SDValue ValToCopy = OutVals[i];
1920     EVT ValVT = ValToCopy.getValueType();
1921
1922     // Promote values to the appropriate types.
1923     if (VA.getLocInfo() == CCValAssign::SExt)
1924       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1925     else if (VA.getLocInfo() == CCValAssign::ZExt)
1926       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1927     else if (VA.getLocInfo() == CCValAssign::AExt) {
1928       if (ValVT.getScalarType() == MVT::i1)
1929         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1930       else
1931         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1932     }   
1933     else if (VA.getLocInfo() == CCValAssign::BCvt)
1934       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1935
1936     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1937            "Unexpected FP-extend for return value.");
1938
1939     // If this is x86-64, and we disabled SSE, we can't return FP values,
1940     // or SSE or MMX vectors.
1941     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1942          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1943           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1944       report_fatal_error("SSE register return with SSE disabled");
1945     }
1946     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1947     // llvm-gcc has never done it right and no one has noticed, so this
1948     // should be OK for now.
1949     if (ValVT == MVT::f64 &&
1950         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1951       report_fatal_error("SSE2 register return with SSE2 disabled");
1952
1953     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1954     // the RET instruction and handled by the FP Stackifier.
1955     if (VA.getLocReg() == X86::FP0 ||
1956         VA.getLocReg() == X86::FP1) {
1957       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1958       // change the value to the FP stack register class.
1959       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1960         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1961       RetOps.push_back(ValToCopy);
1962       // Don't emit a copytoreg.
1963       continue;
1964     }
1965
1966     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1967     // which is returned in RAX / RDX.
1968     if (Subtarget->is64Bit()) {
1969       if (ValVT == MVT::x86mmx) {
1970         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1971           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1972           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1973                                   ValToCopy);
1974           // If we don't have SSE2 available, convert to v4f32 so the generated
1975           // register is legal.
1976           if (!Subtarget->hasSSE2())
1977             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1978         }
1979       }
1980     }
1981
1982     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1983     Flag = Chain.getValue(1);
1984     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1985   }
1986
1987   // The x86-64 ABIs require that for returning structs by value we copy
1988   // the sret argument into %rax/%eax (depending on ABI) for the return.
1989   // Win32 requires us to put the sret argument to %eax as well.
1990   // We saved the argument into a virtual register in the entry block,
1991   // so now we copy the value out and into %rax/%eax.
1992   //
1993   // Checking Function.hasStructRetAttr() here is insufficient because the IR
1994   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
1995   // false, then an sret argument may be implicitly inserted in the SelDAG. In
1996   // either case FuncInfo->setSRetReturnReg() will have been called.
1997   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
1998     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
1999            "No need for an sret register");
2000     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2001
2002     unsigned RetValReg
2003         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2004           X86::RAX : X86::EAX;
2005     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2006     Flag = Chain.getValue(1);
2007
2008     // RAX/EAX now acts like a return value.
2009     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2010   }
2011
2012   RetOps[0] = Chain;  // Update chain.
2013
2014   // Add the flag if we have it.
2015   if (Flag.getNode())
2016     RetOps.push_back(Flag);
2017
2018   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2019 }
2020
2021 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2022   if (N->getNumValues() != 1)
2023     return false;
2024   if (!N->hasNUsesOfValue(1, 0))
2025     return false;
2026
2027   SDValue TCChain = Chain;
2028   SDNode *Copy = *N->use_begin();
2029   if (Copy->getOpcode() == ISD::CopyToReg) {
2030     // If the copy has a glue operand, we conservatively assume it isn't safe to
2031     // perform a tail call.
2032     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2033       return false;
2034     TCChain = Copy->getOperand(0);
2035   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2036     return false;
2037
2038   bool HasRet = false;
2039   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2040        UI != UE; ++UI) {
2041     if (UI->getOpcode() != X86ISD::RET_FLAG)
2042       return false;
2043     // If we are returning more than one value, we can definitely
2044     // not make a tail call see PR19530
2045     if (UI->getNumOperands() > 4)
2046       return false;
2047     if (UI->getNumOperands() == 4 &&
2048         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2049       return false;
2050     HasRet = true;
2051   }
2052
2053   if (!HasRet)
2054     return false;
2055
2056   Chain = TCChain;
2057   return true;
2058 }
2059
2060 EVT
2061 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2062                                             ISD::NodeType ExtendKind) const {
2063   MVT ReturnMVT;
2064   // TODO: Is this also valid on 32-bit?
2065   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2066     ReturnMVT = MVT::i8;
2067   else
2068     ReturnMVT = MVT::i32;
2069
2070   EVT MinVT = getRegisterType(Context, ReturnMVT);
2071   return VT.bitsLT(MinVT) ? MinVT : VT;
2072 }
2073
2074 /// Lower the result values of a call into the
2075 /// appropriate copies out of appropriate physical registers.
2076 ///
2077 SDValue
2078 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2079                                    CallingConv::ID CallConv, bool isVarArg,
2080                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2081                                    SDLoc dl, SelectionDAG &DAG,
2082                                    SmallVectorImpl<SDValue> &InVals) const {
2083
2084   // Assign locations to each value returned by this call.
2085   SmallVector<CCValAssign, 16> RVLocs;
2086   bool Is64Bit = Subtarget->is64Bit();
2087   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2088                  *DAG.getContext());
2089   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2090
2091   // Copy all of the result registers out of their specified physreg.
2092   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2093     CCValAssign &VA = RVLocs[i];
2094     EVT CopyVT = VA.getLocVT();
2095
2096     // If this is x86-64, and we disabled SSE, we can't return FP values
2097     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2098         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2099       report_fatal_error("SSE register return with SSE disabled");
2100     }
2101
2102     // If we prefer to use the value in xmm registers, copy it out as f80 and
2103     // use a truncate to move it from fp stack reg to xmm reg.
2104     bool RoundAfterCopy = false;
2105     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2106         isScalarFPTypeInSSEReg(VA.getValVT())) {
2107       CopyVT = MVT::f80;
2108       RoundAfterCopy = (CopyVT != VA.getLocVT());
2109     }
2110
2111     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2112                                CopyVT, InFlag).getValue(1);
2113     SDValue Val = Chain.getValue(0);
2114
2115     if (RoundAfterCopy)
2116       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2117                         // This truncation won't change the value.
2118                         DAG.getIntPtrConstant(1, dl));
2119
2120     InFlag = Chain.getValue(2);
2121     InVals.push_back(Val);
2122   }
2123
2124   return Chain;
2125 }
2126
2127 //===----------------------------------------------------------------------===//
2128 //                C & StdCall & Fast Calling Convention implementation
2129 //===----------------------------------------------------------------------===//
2130 //  StdCall calling convention seems to be standard for many Windows' API
2131 //  routines and around. It differs from C calling convention just a little:
2132 //  callee should clean up the stack, not caller. Symbols should be also
2133 //  decorated in some fancy way :) It doesn't support any vector arguments.
2134 //  For info on fast calling convention see Fast Calling Convention (tail call)
2135 //  implementation LowerX86_32FastCCCallTo.
2136
2137 /// CallIsStructReturn - Determines whether a call uses struct return
2138 /// semantics.
2139 enum StructReturnType {
2140   NotStructReturn,
2141   RegStructReturn,
2142   StackStructReturn
2143 };
2144 static StructReturnType
2145 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2146   if (Outs.empty())
2147     return NotStructReturn;
2148
2149   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2150   if (!Flags.isSRet())
2151     return NotStructReturn;
2152   if (Flags.isInReg())
2153     return RegStructReturn;
2154   return StackStructReturn;
2155 }
2156
2157 /// Determines whether a function uses struct return semantics.
2158 static StructReturnType
2159 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2160   if (Ins.empty())
2161     return NotStructReturn;
2162
2163   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2164   if (!Flags.isSRet())
2165     return NotStructReturn;
2166   if (Flags.isInReg())
2167     return RegStructReturn;
2168   return StackStructReturn;
2169 }
2170
2171 /// Make a copy of an aggregate at address specified by "Src" to address
2172 /// "Dst" with size and alignment information specified by the specific
2173 /// parameter attribute. The copy will be passed as a byval function parameter.
2174 static SDValue
2175 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2176                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2177                           SDLoc dl) {
2178   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2179
2180   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2181                        /*isVolatile*/false, /*AlwaysInline=*/true,
2182                        /*isTailCall*/false,
2183                        MachinePointerInfo(), MachinePointerInfo());
2184 }
2185
2186 /// Return true if the calling convention is one that
2187 /// supports tail call optimization.
2188 static bool IsTailCallConvention(CallingConv::ID CC) {
2189   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2190           CC == CallingConv::HiPE);
2191 }
2192
2193 /// \brief Return true if the calling convention is a C calling convention.
2194 static bool IsCCallConvention(CallingConv::ID CC) {
2195   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2196           CC == CallingConv::X86_64_SysV);
2197 }
2198
2199 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2200   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2201     return false;
2202
2203   CallSite CS(CI);
2204   CallingConv::ID CalleeCC = CS.getCallingConv();
2205   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2206     return false;
2207
2208   return true;
2209 }
2210
2211 /// Return true if the function is being made into
2212 /// a tailcall target by changing its ABI.
2213 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2214                                    bool GuaranteedTailCallOpt) {
2215   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2216 }
2217
2218 SDValue
2219 X86TargetLowering::LowerMemArgument(SDValue Chain,
2220                                     CallingConv::ID CallConv,
2221                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2222                                     SDLoc dl, SelectionDAG &DAG,
2223                                     const CCValAssign &VA,
2224                                     MachineFrameInfo *MFI,
2225                                     unsigned i) const {
2226   // Create the nodes corresponding to a load from this parameter slot.
2227   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2228   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2229       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2230   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2231   EVT ValVT;
2232
2233   // If value is passed by pointer we have address passed instead of the value
2234   // itself.
2235   if (VA.getLocInfo() == CCValAssign::Indirect)
2236     ValVT = VA.getLocVT();
2237   else
2238     ValVT = VA.getValVT();
2239
2240   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2241   // changed with more analysis.
2242   // In case of tail call optimization mark all arguments mutable. Since they
2243   // could be overwritten by lowering of arguments in case of a tail call.
2244   if (Flags.isByVal()) {
2245     unsigned Bytes = Flags.getByValSize();
2246     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2247     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2248     return DAG.getFrameIndex(FI, getPointerTy());
2249   } else {
2250     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2251                                     VA.getLocMemOffset(), isImmutable);
2252     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2253     return DAG.getLoad(ValVT, dl, Chain, FIN,
2254                        MachinePointerInfo::getFixedStack(FI),
2255                        false, false, false, 0);
2256   }
2257 }
2258
2259 // FIXME: Get this from tablegen.
2260 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2261                                                 const X86Subtarget *Subtarget) {
2262   assert(Subtarget->is64Bit());
2263
2264   if (Subtarget->isCallingConvWin64(CallConv)) {
2265     static const MCPhysReg GPR64ArgRegsWin64[] = {
2266       X86::RCX, X86::RDX, X86::R8,  X86::R9
2267     };
2268     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2269   }
2270
2271   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2272     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2273   };
2274   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2275 }
2276
2277 // FIXME: Get this from tablegen.
2278 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2279                                                 CallingConv::ID CallConv,
2280                                                 const X86Subtarget *Subtarget) {
2281   assert(Subtarget->is64Bit());
2282   if (Subtarget->isCallingConvWin64(CallConv)) {
2283     // The XMM registers which might contain var arg parameters are shadowed
2284     // in their paired GPR.  So we only need to save the GPR to their home
2285     // slots.
2286     // TODO: __vectorcall will change this.
2287     return None;
2288   }
2289
2290   const Function *Fn = MF.getFunction();
2291   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2292   bool isSoftFloat = MF.getTarget().Options.UseSoftFloat;
2293   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2294          "SSE register cannot be used when SSE is disabled!");
2295   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2296     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2297     // registers.
2298     return None;
2299
2300   static const MCPhysReg XMMArgRegs64Bit[] = {
2301     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2302     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2303   };
2304   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2305 }
2306
2307 SDValue
2308 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2309                                         CallingConv::ID CallConv,
2310                                         bool isVarArg,
2311                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2312                                         SDLoc dl,
2313                                         SelectionDAG &DAG,
2314                                         SmallVectorImpl<SDValue> &InVals)
2315                                           const {
2316   MachineFunction &MF = DAG.getMachineFunction();
2317   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2318   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2319
2320   const Function* Fn = MF.getFunction();
2321   if (Fn->hasExternalLinkage() &&
2322       Subtarget->isTargetCygMing() &&
2323       Fn->getName() == "main")
2324     FuncInfo->setForceFramePointer(true);
2325
2326   MachineFrameInfo *MFI = MF.getFrameInfo();
2327   bool Is64Bit = Subtarget->is64Bit();
2328   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2329
2330   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2331          "Var args not supported with calling convention fastcc, ghc or hipe");
2332
2333   // Assign locations to all of the incoming arguments.
2334   SmallVector<CCValAssign, 16> ArgLocs;
2335   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2336
2337   // Allocate shadow area for Win64
2338   if (IsWin64)
2339     CCInfo.AllocateStack(32, 8);
2340
2341   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2342
2343   unsigned LastVal = ~0U;
2344   SDValue ArgValue;
2345   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2346     CCValAssign &VA = ArgLocs[i];
2347     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2348     // places.
2349     assert(VA.getValNo() != LastVal &&
2350            "Don't support value assigned to multiple locs yet");
2351     (void)LastVal;
2352     LastVal = VA.getValNo();
2353
2354     if (VA.isRegLoc()) {
2355       EVT RegVT = VA.getLocVT();
2356       const TargetRegisterClass *RC;
2357       if (RegVT == MVT::i32)
2358         RC = &X86::GR32RegClass;
2359       else if (Is64Bit && RegVT == MVT::i64)
2360         RC = &X86::GR64RegClass;
2361       else if (RegVT == MVT::f32)
2362         RC = &X86::FR32RegClass;
2363       else if (RegVT == MVT::f64)
2364         RC = &X86::FR64RegClass;
2365       else if (RegVT.is512BitVector())
2366         RC = &X86::VR512RegClass;
2367       else if (RegVT.is256BitVector())
2368         RC = &X86::VR256RegClass;
2369       else if (RegVT.is128BitVector())
2370         RC = &X86::VR128RegClass;
2371       else if (RegVT == MVT::x86mmx)
2372         RC = &X86::VR64RegClass;
2373       else if (RegVT == MVT::i1)
2374         RC = &X86::VK1RegClass;
2375       else if (RegVT == MVT::v8i1)
2376         RC = &X86::VK8RegClass;
2377       else if (RegVT == MVT::v16i1)
2378         RC = &X86::VK16RegClass;
2379       else if (RegVT == MVT::v32i1)
2380         RC = &X86::VK32RegClass;
2381       else if (RegVT == MVT::v64i1)
2382         RC = &X86::VK64RegClass;
2383       else
2384         llvm_unreachable("Unknown argument type!");
2385
2386       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2387       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2388
2389       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2390       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2391       // right size.
2392       if (VA.getLocInfo() == CCValAssign::SExt)
2393         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2394                                DAG.getValueType(VA.getValVT()));
2395       else if (VA.getLocInfo() == CCValAssign::ZExt)
2396         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2397                                DAG.getValueType(VA.getValVT()));
2398       else if (VA.getLocInfo() == CCValAssign::BCvt)
2399         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2400
2401       if (VA.isExtInLoc()) {
2402         // Handle MMX values passed in XMM regs.
2403         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2404           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2405         else
2406           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2407       }
2408     } else {
2409       assert(VA.isMemLoc());
2410       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2411     }
2412
2413     // If value is passed via pointer - do a load.
2414     if (VA.getLocInfo() == CCValAssign::Indirect)
2415       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2416                              MachinePointerInfo(), false, false, false, 0);
2417
2418     InVals.push_back(ArgValue);
2419   }
2420
2421   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2422     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2423       // The x86-64 ABIs require that for returning structs by value we copy
2424       // the sret argument into %rax/%eax (depending on ABI) for the return.
2425       // Win32 requires us to put the sret argument to %eax as well.
2426       // Save the argument into a virtual register so that we can access it
2427       // from the return points.
2428       if (Ins[i].Flags.isSRet()) {
2429         unsigned Reg = FuncInfo->getSRetReturnReg();
2430         if (!Reg) {
2431           MVT PtrTy = getPointerTy();
2432           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2433           FuncInfo->setSRetReturnReg(Reg);
2434         }
2435         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2436         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2437         break;
2438       }
2439     }
2440   }
2441
2442   unsigned StackSize = CCInfo.getNextStackOffset();
2443   // Align stack specially for tail calls.
2444   if (FuncIsMadeTailCallSafe(CallConv,
2445                              MF.getTarget().Options.GuaranteedTailCallOpt))
2446     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2447
2448   // If the function takes variable number of arguments, make a frame index for
2449   // the start of the first vararg value... for expansion of llvm.va_start. We
2450   // can skip this if there are no va_start calls.
2451   if (MFI->hasVAStart() &&
2452       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2453                    CallConv != CallingConv::X86_ThisCall))) {
2454     FuncInfo->setVarArgsFrameIndex(
2455         MFI->CreateFixedObject(1, StackSize, true));
2456   }
2457
2458   MachineModuleInfo &MMI = MF.getMMI();
2459   const Function *WinEHParent = nullptr;
2460   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2461     WinEHParent = MMI.getWinEHParent(Fn);
2462   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2463   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2464
2465   // Figure out if XMM registers are in use.
2466   assert(!(MF.getTarget().Options.UseSoftFloat &&
2467            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2468          "SSE register cannot be used when SSE is disabled!");
2469
2470   // 64-bit calling conventions support varargs and register parameters, so we
2471   // have to do extra work to spill them in the prologue.
2472   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2473     // Find the first unallocated argument registers.
2474     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2475     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2476     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2477     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2478     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2479            "SSE register cannot be used when SSE is disabled!");
2480
2481     // Gather all the live in physical registers.
2482     SmallVector<SDValue, 6> LiveGPRs;
2483     SmallVector<SDValue, 8> LiveXMMRegs;
2484     SDValue ALVal;
2485     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2486       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2487       LiveGPRs.push_back(
2488           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2489     }
2490     if (!ArgXMMs.empty()) {
2491       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2492       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2493       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2494         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2495         LiveXMMRegs.push_back(
2496             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2497       }
2498     }
2499
2500     if (IsWin64) {
2501       // Get to the caller-allocated home save location.  Add 8 to account
2502       // for the return address.
2503       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2504       FuncInfo->setRegSaveFrameIndex(
2505           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2506       // Fixup to set vararg frame on shadow area (4 x i64).
2507       if (NumIntRegs < 4)
2508         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2509     } else {
2510       // For X86-64, if there are vararg parameters that are passed via
2511       // registers, then we must store them to their spots on the stack so
2512       // they may be loaded by deferencing the result of va_next.
2513       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2514       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2515       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2516           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2517     }
2518
2519     // Store the integer parameter registers.
2520     SmallVector<SDValue, 8> MemOps;
2521     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2522                                       getPointerTy());
2523     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2524     for (SDValue Val : LiveGPRs) {
2525       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2526                                 DAG.getIntPtrConstant(Offset, dl));
2527       SDValue Store =
2528         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2529                      MachinePointerInfo::getFixedStack(
2530                        FuncInfo->getRegSaveFrameIndex(), Offset),
2531                      false, false, 0);
2532       MemOps.push_back(Store);
2533       Offset += 8;
2534     }
2535
2536     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2537       // Now store the XMM (fp + vector) parameter registers.
2538       SmallVector<SDValue, 12> SaveXMMOps;
2539       SaveXMMOps.push_back(Chain);
2540       SaveXMMOps.push_back(ALVal);
2541       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2542                              FuncInfo->getRegSaveFrameIndex(), dl));
2543       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2544                              FuncInfo->getVarArgsFPOffset(), dl));
2545       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2546                         LiveXMMRegs.end());
2547       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2548                                    MVT::Other, SaveXMMOps));
2549     }
2550
2551     if (!MemOps.empty())
2552       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2553   } else if (IsWinEHOutlined) {
2554     // Get to the caller-allocated home save location.  Add 8 to account
2555     // for the return address.
2556     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2557     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2558         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2559
2560     MMI.getWinEHFuncInfo(Fn)
2561         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2562         FuncInfo->getRegSaveFrameIndex();
2563
2564     // Store the second integer parameter (rdx) into rsp+16 relative to the
2565     // stack pointer at the entry of the function.
2566     SDValue RSFIN =
2567         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2568     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2569     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2570     Chain = DAG.getStore(
2571         Val.getValue(1), dl, Val, RSFIN,
2572         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2573         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2574   }
2575
2576   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2577     // Find the largest legal vector type.
2578     MVT VecVT = MVT::Other;
2579     // FIXME: Only some x86_32 calling conventions support AVX512.
2580     if (Subtarget->hasAVX512() &&
2581         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2582                      CallConv == CallingConv::Intel_OCL_BI)))
2583       VecVT = MVT::v16f32;
2584     else if (Subtarget->hasAVX())
2585       VecVT = MVT::v8f32;
2586     else if (Subtarget->hasSSE2())
2587       VecVT = MVT::v4f32;
2588
2589     // We forward some GPRs and some vector types.
2590     SmallVector<MVT, 2> RegParmTypes;
2591     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2592     RegParmTypes.push_back(IntVT);
2593     if (VecVT != MVT::Other)
2594       RegParmTypes.push_back(VecVT);
2595
2596     // Compute the set of forwarded registers. The rest are scratch.
2597     SmallVectorImpl<ForwardedRegister> &Forwards =
2598         FuncInfo->getForwardedMustTailRegParms();
2599     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2600
2601     // Conservatively forward AL on x86_64, since it might be used for varargs.
2602     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2603       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2604       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2605     }
2606
2607     // Copy all forwards from physical to virtual registers.
2608     for (ForwardedRegister &F : Forwards) {
2609       // FIXME: Can we use a less constrained schedule?
2610       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2611       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2612       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2613     }
2614   }
2615
2616   // Some CCs need callee pop.
2617   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2618                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2619     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2620   } else {
2621     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2622     // If this is an sret function, the return should pop the hidden pointer.
2623     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2624         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2625         argsAreStructReturn(Ins) == StackStructReturn)
2626       FuncInfo->setBytesToPopOnReturn(4);
2627   }
2628
2629   if (!Is64Bit) {
2630     // RegSaveFrameIndex is X86-64 only.
2631     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2632     if (CallConv == CallingConv::X86_FastCall ||
2633         CallConv == CallingConv::X86_ThisCall)
2634       // fastcc functions can't have varargs.
2635       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2636   }
2637
2638   FuncInfo->setArgumentStackSize(StackSize);
2639
2640   if (IsWinEHParent) {
2641     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2642     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2643     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2644     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2645     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2646                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2647                          /*isVolatile=*/true,
2648                          /*isNonTemporal=*/false, /*Alignment=*/0);
2649   }
2650
2651   return Chain;
2652 }
2653
2654 SDValue
2655 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2656                                     SDValue StackPtr, SDValue Arg,
2657                                     SDLoc dl, SelectionDAG &DAG,
2658                                     const CCValAssign &VA,
2659                                     ISD::ArgFlagsTy Flags) const {
2660   unsigned LocMemOffset = VA.getLocMemOffset();
2661   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2662   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2663   if (Flags.isByVal())
2664     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2665
2666   return DAG.getStore(Chain, dl, Arg, PtrOff,
2667                       MachinePointerInfo::getStack(LocMemOffset),
2668                       false, false, 0);
2669 }
2670
2671 /// Emit a load of return address if tail call
2672 /// optimization is performed and it is required.
2673 SDValue
2674 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2675                                            SDValue &OutRetAddr, SDValue Chain,
2676                                            bool IsTailCall, bool Is64Bit,
2677                                            int FPDiff, SDLoc dl) const {
2678   // Adjust the Return address stack slot.
2679   EVT VT = getPointerTy();
2680   OutRetAddr = getReturnAddressFrameIndex(DAG);
2681
2682   // Load the "old" Return address.
2683   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2684                            false, false, false, 0);
2685   return SDValue(OutRetAddr.getNode(), 1);
2686 }
2687
2688 /// Emit a store of the return address if tail call
2689 /// optimization is performed and it is required (FPDiff!=0).
2690 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2691                                         SDValue Chain, SDValue RetAddrFrIdx,
2692                                         EVT PtrVT, unsigned SlotSize,
2693                                         int FPDiff, SDLoc dl) {
2694   // Store the return address to the appropriate stack slot.
2695   if (!FPDiff) return Chain;
2696   // Calculate the new stack slot for the return address.
2697   int NewReturnAddrFI =
2698     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2699                                          false);
2700   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2701   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2702                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2703                        false, false, 0);
2704   return Chain;
2705 }
2706
2707 SDValue
2708 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2709                              SmallVectorImpl<SDValue> &InVals) const {
2710   SelectionDAG &DAG                     = CLI.DAG;
2711   SDLoc &dl                             = CLI.DL;
2712   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2713   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2714   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2715   SDValue Chain                         = CLI.Chain;
2716   SDValue Callee                        = CLI.Callee;
2717   CallingConv::ID CallConv              = CLI.CallConv;
2718   bool &isTailCall                      = CLI.IsTailCall;
2719   bool isVarArg                         = CLI.IsVarArg;
2720
2721   MachineFunction &MF = DAG.getMachineFunction();
2722   bool Is64Bit        = Subtarget->is64Bit();
2723   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2724   StructReturnType SR = callIsStructReturn(Outs);
2725   bool IsSibcall      = false;
2726   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2727
2728   if (MF.getTarget().Options.DisableTailCalls)
2729     isTailCall = false;
2730
2731   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2732   if (IsMustTail) {
2733     // Force this to be a tail call.  The verifier rules are enough to ensure
2734     // that we can lower this successfully without moving the return address
2735     // around.
2736     isTailCall = true;
2737   } else if (isTailCall) {
2738     // Check if it's really possible to do a tail call.
2739     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2740                     isVarArg, SR != NotStructReturn,
2741                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2742                     Outs, OutVals, Ins, DAG);
2743
2744     // Sibcalls are automatically detected tailcalls which do not require
2745     // ABI changes.
2746     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2747       IsSibcall = true;
2748
2749     if (isTailCall)
2750       ++NumTailCalls;
2751   }
2752
2753   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2754          "Var args not supported with calling convention fastcc, ghc or hipe");
2755
2756   // Analyze operands of the call, assigning locations to each operand.
2757   SmallVector<CCValAssign, 16> ArgLocs;
2758   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2759
2760   // Allocate shadow area for Win64
2761   if (IsWin64)
2762     CCInfo.AllocateStack(32, 8);
2763
2764   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2765
2766   // Get a count of how many bytes are to be pushed on the stack.
2767   unsigned NumBytes = CCInfo.getNextStackOffset();
2768   if (IsSibcall)
2769     // This is a sibcall. The memory operands are available in caller's
2770     // own caller's stack.
2771     NumBytes = 0;
2772   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2773            IsTailCallConvention(CallConv))
2774     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2775
2776   int FPDiff = 0;
2777   if (isTailCall && !IsSibcall && !IsMustTail) {
2778     // Lower arguments at fp - stackoffset + fpdiff.
2779     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2780
2781     FPDiff = NumBytesCallerPushed - NumBytes;
2782
2783     // Set the delta of movement of the returnaddr stackslot.
2784     // But only set if delta is greater than previous delta.
2785     if (FPDiff < X86Info->getTCReturnAddrDelta())
2786       X86Info->setTCReturnAddrDelta(FPDiff);
2787   }
2788
2789   unsigned NumBytesToPush = NumBytes;
2790   unsigned NumBytesToPop = NumBytes;
2791
2792   // If we have an inalloca argument, all stack space has already been allocated
2793   // for us and be right at the top of the stack.  We don't support multiple
2794   // arguments passed in memory when using inalloca.
2795   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2796     NumBytesToPush = 0;
2797     if (!ArgLocs.back().isMemLoc())
2798       report_fatal_error("cannot use inalloca attribute on a register "
2799                          "parameter");
2800     if (ArgLocs.back().getLocMemOffset() != 0)
2801       report_fatal_error("any parameter with the inalloca attribute must be "
2802                          "the only memory argument");
2803   }
2804
2805   if (!IsSibcall)
2806     Chain = DAG.getCALLSEQ_START(
2807         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2808
2809   SDValue RetAddrFrIdx;
2810   // Load return address for tail calls.
2811   if (isTailCall && FPDiff)
2812     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2813                                     Is64Bit, FPDiff, dl);
2814
2815   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2816   SmallVector<SDValue, 8> MemOpChains;
2817   SDValue StackPtr;
2818
2819   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2820   // of tail call optimization arguments are handle later.
2821   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2822   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2823     // Skip inalloca arguments, they have already been written.
2824     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2825     if (Flags.isInAlloca())
2826       continue;
2827
2828     CCValAssign &VA = ArgLocs[i];
2829     EVT RegVT = VA.getLocVT();
2830     SDValue Arg = OutVals[i];
2831     bool isByVal = Flags.isByVal();
2832
2833     // Promote the value if needed.
2834     switch (VA.getLocInfo()) {
2835     default: llvm_unreachable("Unknown loc info!");
2836     case CCValAssign::Full: break;
2837     case CCValAssign::SExt:
2838       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2839       break;
2840     case CCValAssign::ZExt:
2841       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2842       break;
2843     case CCValAssign::AExt:
2844       if (Arg.getValueType().getScalarType() == MVT::i1)
2845         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2846       else if (RegVT.is128BitVector()) {
2847         // Special case: passing MMX values in XMM registers.
2848         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2849         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2850         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2851       } else
2852         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2853       break;
2854     case CCValAssign::BCvt:
2855       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2856       break;
2857     case CCValAssign::Indirect: {
2858       // Store the argument.
2859       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2860       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2861       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2862                            MachinePointerInfo::getFixedStack(FI),
2863                            false, false, 0);
2864       Arg = SpillSlot;
2865       break;
2866     }
2867     }
2868
2869     if (VA.isRegLoc()) {
2870       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2871       if (isVarArg && IsWin64) {
2872         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2873         // shadow reg if callee is a varargs function.
2874         unsigned ShadowReg = 0;
2875         switch (VA.getLocReg()) {
2876         case X86::XMM0: ShadowReg = X86::RCX; break;
2877         case X86::XMM1: ShadowReg = X86::RDX; break;
2878         case X86::XMM2: ShadowReg = X86::R8; break;
2879         case X86::XMM3: ShadowReg = X86::R9; break;
2880         }
2881         if (ShadowReg)
2882           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2883       }
2884     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2885       assert(VA.isMemLoc());
2886       if (!StackPtr.getNode())
2887         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2888                                       getPointerTy());
2889       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2890                                              dl, DAG, VA, Flags));
2891     }
2892   }
2893
2894   if (!MemOpChains.empty())
2895     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2896
2897   if (Subtarget->isPICStyleGOT()) {
2898     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2899     // GOT pointer.
2900     if (!isTailCall) {
2901       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2902                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2903     } else {
2904       // If we are tail calling and generating PIC/GOT style code load the
2905       // address of the callee into ECX. The value in ecx is used as target of
2906       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2907       // for tail calls on PIC/GOT architectures. Normally we would just put the
2908       // address of GOT into ebx and then call target@PLT. But for tail calls
2909       // ebx would be restored (since ebx is callee saved) before jumping to the
2910       // target@PLT.
2911
2912       // Note: The actual moving to ECX is done further down.
2913       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2914       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2915           !G->getGlobal()->hasProtectedVisibility())
2916         Callee = LowerGlobalAddress(Callee, DAG);
2917       else if (isa<ExternalSymbolSDNode>(Callee))
2918         Callee = LowerExternalSymbol(Callee, DAG);
2919     }
2920   }
2921
2922   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2923     // From AMD64 ABI document:
2924     // For calls that may call functions that use varargs or stdargs
2925     // (prototype-less calls or calls to functions containing ellipsis (...) in
2926     // the declaration) %al is used as hidden argument to specify the number
2927     // of SSE registers used. The contents of %al do not need to match exactly
2928     // the number of registers, but must be an ubound on the number of SSE
2929     // registers used and is in the range 0 - 8 inclusive.
2930
2931     // Count the number of XMM registers allocated.
2932     static const MCPhysReg XMMArgRegs[] = {
2933       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2934       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2935     };
2936     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2937     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2938            && "SSE registers cannot be used when SSE is disabled");
2939
2940     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2941                                         DAG.getConstant(NumXMMRegs, dl,
2942                                                         MVT::i8)));
2943   }
2944
2945   if (isVarArg && IsMustTail) {
2946     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2947     for (const auto &F : Forwards) {
2948       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2949       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2950     }
2951   }
2952
2953   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2954   // don't need this because the eligibility check rejects calls that require
2955   // shuffling arguments passed in memory.
2956   if (!IsSibcall && isTailCall) {
2957     // Force all the incoming stack arguments to be loaded from the stack
2958     // before any new outgoing arguments are stored to the stack, because the
2959     // outgoing stack slots may alias the incoming argument stack slots, and
2960     // the alias isn't otherwise explicit. This is slightly more conservative
2961     // than necessary, because it means that each store effectively depends
2962     // on every argument instead of just those arguments it would clobber.
2963     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2964
2965     SmallVector<SDValue, 8> MemOpChains2;
2966     SDValue FIN;
2967     int FI = 0;
2968     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2969       CCValAssign &VA = ArgLocs[i];
2970       if (VA.isRegLoc())
2971         continue;
2972       assert(VA.isMemLoc());
2973       SDValue Arg = OutVals[i];
2974       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2975       // Skip inalloca arguments.  They don't require any work.
2976       if (Flags.isInAlloca())
2977         continue;
2978       // Create frame index.
2979       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2980       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2981       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2982       FIN = DAG.getFrameIndex(FI, getPointerTy());
2983
2984       if (Flags.isByVal()) {
2985         // Copy relative to framepointer.
2986         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
2987         if (!StackPtr.getNode())
2988           StackPtr = DAG.getCopyFromReg(Chain, dl,
2989                                         RegInfo->getStackRegister(),
2990                                         getPointerTy());
2991         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2992
2993         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2994                                                          ArgChain,
2995                                                          Flags, DAG, dl));
2996       } else {
2997         // Store relative to framepointer.
2998         MemOpChains2.push_back(
2999           DAG.getStore(ArgChain, dl, Arg, FIN,
3000                        MachinePointerInfo::getFixedStack(FI),
3001                        false, false, 0));
3002       }
3003     }
3004
3005     if (!MemOpChains2.empty())
3006       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3007
3008     // Store the return address to the appropriate stack slot.
3009     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3010                                      getPointerTy(), RegInfo->getSlotSize(),
3011                                      FPDiff, dl);
3012   }
3013
3014   // Build a sequence of copy-to-reg nodes chained together with token chain
3015   // and flag operands which copy the outgoing args into registers.
3016   SDValue InFlag;
3017   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3018     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3019                              RegsToPass[i].second, InFlag);
3020     InFlag = Chain.getValue(1);
3021   }
3022
3023   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3024     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3025     // In the 64-bit large code model, we have to make all calls
3026     // through a register, since the call instruction's 32-bit
3027     // pc-relative offset may not be large enough to hold the whole
3028     // address.
3029   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3030     // If the callee is a GlobalAddress node (quite common, every direct call
3031     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3032     // it.
3033     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3034
3035     // We should use extra load for direct calls to dllimported functions in
3036     // non-JIT mode.
3037     const GlobalValue *GV = G->getGlobal();
3038     if (!GV->hasDLLImportStorageClass()) {
3039       unsigned char OpFlags = 0;
3040       bool ExtraLoad = false;
3041       unsigned WrapperKind = ISD::DELETED_NODE;
3042
3043       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3044       // external symbols most go through the PLT in PIC mode.  If the symbol
3045       // has hidden or protected visibility, or if it is static or local, then
3046       // we don't need to use the PLT - we can directly call it.
3047       if (Subtarget->isTargetELF() &&
3048           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3049           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3050         OpFlags = X86II::MO_PLT;
3051       } else if (Subtarget->isPICStyleStubAny() &&
3052                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3053                  (!Subtarget->getTargetTriple().isMacOSX() ||
3054                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3055         // PC-relative references to external symbols should go through $stub,
3056         // unless we're building with the leopard linker or later, which
3057         // automatically synthesizes these stubs.
3058         OpFlags = X86II::MO_DARWIN_STUB;
3059       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3060                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3061         // If the function is marked as non-lazy, generate an indirect call
3062         // which loads from the GOT directly. This avoids runtime overhead
3063         // at the cost of eager binding (and one extra byte of encoding).
3064         OpFlags = X86II::MO_GOTPCREL;
3065         WrapperKind = X86ISD::WrapperRIP;
3066         ExtraLoad = true;
3067       }
3068
3069       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3070                                           G->getOffset(), OpFlags);
3071
3072       // Add a wrapper if needed.
3073       if (WrapperKind != ISD::DELETED_NODE)
3074         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3075       // Add extra indirection if needed.
3076       if (ExtraLoad)
3077         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3078                              MachinePointerInfo::getGOT(),
3079                              false, false, false, 0);
3080     }
3081   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3082     unsigned char OpFlags = 0;
3083
3084     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3085     // external symbols should go through the PLT.
3086     if (Subtarget->isTargetELF() &&
3087         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3088       OpFlags = X86II::MO_PLT;
3089     } else if (Subtarget->isPICStyleStubAny() &&
3090                (!Subtarget->getTargetTriple().isMacOSX() ||
3091                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3092       // PC-relative references to external symbols should go through $stub,
3093       // unless we're building with the leopard linker or later, which
3094       // automatically synthesizes these stubs.
3095       OpFlags = X86II::MO_DARWIN_STUB;
3096     }
3097
3098     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3099                                          OpFlags);
3100   } else if (Subtarget->isTarget64BitILP32() &&
3101              Callee->getValueType(0) == MVT::i32) {
3102     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3103     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3104   }
3105
3106   // Returns a chain & a flag for retval copy to use.
3107   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3108   SmallVector<SDValue, 8> Ops;
3109
3110   if (!IsSibcall && isTailCall) {
3111     Chain = DAG.getCALLSEQ_END(Chain,
3112                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3113                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3114     InFlag = Chain.getValue(1);
3115   }
3116
3117   Ops.push_back(Chain);
3118   Ops.push_back(Callee);
3119
3120   if (isTailCall)
3121     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3122
3123   // Add argument registers to the end of the list so that they are known live
3124   // into the call.
3125   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3126     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3127                                   RegsToPass[i].second.getValueType()));
3128
3129   // Add a register mask operand representing the call-preserved registers.
3130   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3131   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3132   assert(Mask && "Missing call preserved mask for calling convention");
3133   Ops.push_back(DAG.getRegisterMask(Mask));
3134
3135   if (InFlag.getNode())
3136     Ops.push_back(InFlag);
3137
3138   if (isTailCall) {
3139     // We used to do:
3140     //// If this is the first return lowered for this function, add the regs
3141     //// to the liveout set for the function.
3142     // This isn't right, although it's probably harmless on x86; liveouts
3143     // should be computed from returns not tail calls.  Consider a void
3144     // function making a tail call to a function returning int.
3145     MF.getFrameInfo()->setHasTailCall();
3146     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3147   }
3148
3149   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3150   InFlag = Chain.getValue(1);
3151
3152   // Create the CALLSEQ_END node.
3153   unsigned NumBytesForCalleeToPop;
3154   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3155                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3156     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3157   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3158            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3159            SR == StackStructReturn)
3160     // If this is a call to a struct-return function, the callee
3161     // pops the hidden struct pointer, so we have to push it back.
3162     // This is common for Darwin/X86, Linux & Mingw32 targets.
3163     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3164     NumBytesForCalleeToPop = 4;
3165   else
3166     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3167
3168   // Returns a flag for retval copy to use.
3169   if (!IsSibcall) {
3170     Chain = DAG.getCALLSEQ_END(Chain,
3171                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3172                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3173                                                      true),
3174                                InFlag, dl);
3175     InFlag = Chain.getValue(1);
3176   }
3177
3178   // Handle result values, copying them out of physregs into vregs that we
3179   // return.
3180   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3181                          Ins, dl, DAG, InVals);
3182 }
3183
3184 //===----------------------------------------------------------------------===//
3185 //                Fast Calling Convention (tail call) implementation
3186 //===----------------------------------------------------------------------===//
3187
3188 //  Like std call, callee cleans arguments, convention except that ECX is
3189 //  reserved for storing the tail called function address. Only 2 registers are
3190 //  free for argument passing (inreg). Tail call optimization is performed
3191 //  provided:
3192 //                * tailcallopt is enabled
3193 //                * caller/callee are fastcc
3194 //  On X86_64 architecture with GOT-style position independent code only local
3195 //  (within module) calls are supported at the moment.
3196 //  To keep the stack aligned according to platform abi the function
3197 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3198 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3199 //  If a tail called function callee has more arguments than the caller the
3200 //  caller needs to make sure that there is room to move the RETADDR to. This is
3201 //  achieved by reserving an area the size of the argument delta right after the
3202 //  original RETADDR, but before the saved framepointer or the spilled registers
3203 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3204 //  stack layout:
3205 //    arg1
3206 //    arg2
3207 //    RETADDR
3208 //    [ new RETADDR
3209 //      move area ]
3210 //    (possible EBP)
3211 //    ESI
3212 //    EDI
3213 //    local1 ..
3214
3215 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3216 /// for a 16 byte align requirement.
3217 unsigned
3218 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3219                                                SelectionDAG& DAG) const {
3220   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3221   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3222   unsigned StackAlignment = TFI.getStackAlignment();
3223   uint64_t AlignMask = StackAlignment - 1;
3224   int64_t Offset = StackSize;
3225   unsigned SlotSize = RegInfo->getSlotSize();
3226   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3227     // Number smaller than 12 so just add the difference.
3228     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3229   } else {
3230     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3231     Offset = ((~AlignMask) & Offset) + StackAlignment +
3232       (StackAlignment-SlotSize);
3233   }
3234   return Offset;
3235 }
3236
3237 /// MatchingStackOffset - Return true if the given stack call argument is
3238 /// already available in the same position (relatively) of the caller's
3239 /// incoming argument stack.
3240 static
3241 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3242                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3243                          const X86InstrInfo *TII) {
3244   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3245   int FI = INT_MAX;
3246   if (Arg.getOpcode() == ISD::CopyFromReg) {
3247     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3248     if (!TargetRegisterInfo::isVirtualRegister(VR))
3249       return false;
3250     MachineInstr *Def = MRI->getVRegDef(VR);
3251     if (!Def)
3252       return false;
3253     if (!Flags.isByVal()) {
3254       if (!TII->isLoadFromStackSlot(Def, FI))
3255         return false;
3256     } else {
3257       unsigned Opcode = Def->getOpcode();
3258       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3259            Opcode == X86::LEA64_32r) &&
3260           Def->getOperand(1).isFI()) {
3261         FI = Def->getOperand(1).getIndex();
3262         Bytes = Flags.getByValSize();
3263       } else
3264         return false;
3265     }
3266   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3267     if (Flags.isByVal())
3268       // ByVal argument is passed in as a pointer but it's now being
3269       // dereferenced. e.g.
3270       // define @foo(%struct.X* %A) {
3271       //   tail call @bar(%struct.X* byval %A)
3272       // }
3273       return false;
3274     SDValue Ptr = Ld->getBasePtr();
3275     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3276     if (!FINode)
3277       return false;
3278     FI = FINode->getIndex();
3279   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3280     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3281     FI = FINode->getIndex();
3282     Bytes = Flags.getByValSize();
3283   } else
3284     return false;
3285
3286   assert(FI != INT_MAX);
3287   if (!MFI->isFixedObjectIndex(FI))
3288     return false;
3289   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3290 }
3291
3292 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3293 /// for tail call optimization. Targets which want to do tail call
3294 /// optimization should implement this function.
3295 bool
3296 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3297                                                      CallingConv::ID CalleeCC,
3298                                                      bool isVarArg,
3299                                                      bool isCalleeStructRet,
3300                                                      bool isCallerStructRet,
3301                                                      Type *RetTy,
3302                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3303                                     const SmallVectorImpl<SDValue> &OutVals,
3304                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3305                                                      SelectionDAG &DAG) const {
3306   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3307     return false;
3308
3309   // If -tailcallopt is specified, make fastcc functions tail-callable.
3310   const MachineFunction &MF = DAG.getMachineFunction();
3311   const Function *CallerF = MF.getFunction();
3312
3313   // If the function return type is x86_fp80 and the callee return type is not,
3314   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3315   // perform a tailcall optimization here.
3316   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3317     return false;
3318
3319   CallingConv::ID CallerCC = CallerF->getCallingConv();
3320   bool CCMatch = CallerCC == CalleeCC;
3321   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3322   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3323
3324   // Win64 functions have extra shadow space for argument homing. Don't do the
3325   // sibcall if the caller and callee have mismatched expectations for this
3326   // space.
3327   if (IsCalleeWin64 != IsCallerWin64)
3328     return false;
3329
3330   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3331     if (IsTailCallConvention(CalleeCC) && CCMatch)
3332       return true;
3333     return false;
3334   }
3335
3336   // Look for obvious safe cases to perform tail call optimization that do not
3337   // require ABI changes. This is what gcc calls sibcall.
3338
3339   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3340   // emit a special epilogue.
3341   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3342   if (RegInfo->needsStackRealignment(MF))
3343     return false;
3344
3345   // Also avoid sibcall optimization if either caller or callee uses struct
3346   // return semantics.
3347   if (isCalleeStructRet || isCallerStructRet)
3348     return false;
3349
3350   // An stdcall/thiscall caller is expected to clean up its arguments; the
3351   // callee isn't going to do that.
3352   // FIXME: this is more restrictive than needed. We could produce a tailcall
3353   // when the stack adjustment matches. For example, with a thiscall that takes
3354   // only one argument.
3355   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3356                    CallerCC == CallingConv::X86_ThisCall))
3357     return false;
3358
3359   // Do not sibcall optimize vararg calls unless all arguments are passed via
3360   // registers.
3361   if (isVarArg && !Outs.empty()) {
3362
3363     // Optimizing for varargs on Win64 is unlikely to be safe without
3364     // additional testing.
3365     if (IsCalleeWin64 || IsCallerWin64)
3366       return false;
3367
3368     SmallVector<CCValAssign, 16> ArgLocs;
3369     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3370                    *DAG.getContext());
3371
3372     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3373     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3374       if (!ArgLocs[i].isRegLoc())
3375         return false;
3376   }
3377
3378   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3379   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3380   // this into a sibcall.
3381   bool Unused = false;
3382   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3383     if (!Ins[i].Used) {
3384       Unused = true;
3385       break;
3386     }
3387   }
3388   if (Unused) {
3389     SmallVector<CCValAssign, 16> RVLocs;
3390     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3391                    *DAG.getContext());
3392     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3393     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3394       CCValAssign &VA = RVLocs[i];
3395       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3396         return false;
3397     }
3398   }
3399
3400   // If the calling conventions do not match, then we'd better make sure the
3401   // results are returned in the same way as what the caller expects.
3402   if (!CCMatch) {
3403     SmallVector<CCValAssign, 16> RVLocs1;
3404     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3405                     *DAG.getContext());
3406     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3407
3408     SmallVector<CCValAssign, 16> RVLocs2;
3409     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3410                     *DAG.getContext());
3411     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3412
3413     if (RVLocs1.size() != RVLocs2.size())
3414       return false;
3415     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3416       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3417         return false;
3418       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3419         return false;
3420       if (RVLocs1[i].isRegLoc()) {
3421         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3422           return false;
3423       } else {
3424         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3425           return false;
3426       }
3427     }
3428   }
3429
3430   // If the callee takes no arguments then go on to check the results of the
3431   // call.
3432   if (!Outs.empty()) {
3433     // Check if stack adjustment is needed. For now, do not do this if any
3434     // argument is passed on the stack.
3435     SmallVector<CCValAssign, 16> ArgLocs;
3436     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3437                    *DAG.getContext());
3438
3439     // Allocate shadow area for Win64
3440     if (IsCalleeWin64)
3441       CCInfo.AllocateStack(32, 8);
3442
3443     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3444     if (CCInfo.getNextStackOffset()) {
3445       MachineFunction &MF = DAG.getMachineFunction();
3446       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3447         return false;
3448
3449       // Check if the arguments are already laid out in the right way as
3450       // the caller's fixed stack objects.
3451       MachineFrameInfo *MFI = MF.getFrameInfo();
3452       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3453       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3454       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3455         CCValAssign &VA = ArgLocs[i];
3456         SDValue Arg = OutVals[i];
3457         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3458         if (VA.getLocInfo() == CCValAssign::Indirect)
3459           return false;
3460         if (!VA.isRegLoc()) {
3461           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3462                                    MFI, MRI, TII))
3463             return false;
3464         }
3465       }
3466     }
3467
3468     // If the tailcall address may be in a register, then make sure it's
3469     // possible to register allocate for it. In 32-bit, the call address can
3470     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3471     // callee-saved registers are restored. These happen to be the same
3472     // registers used to pass 'inreg' arguments so watch out for those.
3473     if (!Subtarget->is64Bit() &&
3474         ((!isa<GlobalAddressSDNode>(Callee) &&
3475           !isa<ExternalSymbolSDNode>(Callee)) ||
3476          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3477       unsigned NumInRegs = 0;
3478       // In PIC we need an extra register to formulate the address computation
3479       // for the callee.
3480       unsigned MaxInRegs =
3481         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3482
3483       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3484         CCValAssign &VA = ArgLocs[i];
3485         if (!VA.isRegLoc())
3486           continue;
3487         unsigned Reg = VA.getLocReg();
3488         switch (Reg) {
3489         default: break;
3490         case X86::EAX: case X86::EDX: case X86::ECX:
3491           if (++NumInRegs == MaxInRegs)
3492             return false;
3493           break;
3494         }
3495       }
3496     }
3497   }
3498
3499   return true;
3500 }
3501
3502 FastISel *
3503 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3504                                   const TargetLibraryInfo *libInfo) const {
3505   return X86::createFastISel(funcInfo, libInfo);
3506 }
3507
3508 //===----------------------------------------------------------------------===//
3509 //                           Other Lowering Hooks
3510 //===----------------------------------------------------------------------===//
3511
3512 static bool MayFoldLoad(SDValue Op) {
3513   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3514 }
3515
3516 static bool MayFoldIntoStore(SDValue Op) {
3517   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3518 }
3519
3520 static bool isTargetShuffle(unsigned Opcode) {
3521   switch(Opcode) {
3522   default: return false;
3523   case X86ISD::BLENDI:
3524   case X86ISD::PSHUFB:
3525   case X86ISD::PSHUFD:
3526   case X86ISD::PSHUFHW:
3527   case X86ISD::PSHUFLW:
3528   case X86ISD::SHUFP:
3529   case X86ISD::PALIGNR:
3530   case X86ISD::MOVLHPS:
3531   case X86ISD::MOVLHPD:
3532   case X86ISD::MOVHLPS:
3533   case X86ISD::MOVLPS:
3534   case X86ISD::MOVLPD:
3535   case X86ISD::MOVSHDUP:
3536   case X86ISD::MOVSLDUP:
3537   case X86ISD::MOVDDUP:
3538   case X86ISD::MOVSS:
3539   case X86ISD::MOVSD:
3540   case X86ISD::UNPCKL:
3541   case X86ISD::UNPCKH:
3542   case X86ISD::VPERMILPI:
3543   case X86ISD::VPERM2X128:
3544   case X86ISD::VPERMI:
3545     return true;
3546   }
3547 }
3548
3549 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3550                                     SDValue V1, unsigned TargetMask,
3551                                     SelectionDAG &DAG) {
3552   switch(Opc) {
3553   default: llvm_unreachable("Unknown x86 shuffle node");
3554   case X86ISD::PSHUFD:
3555   case X86ISD::PSHUFHW:
3556   case X86ISD::PSHUFLW:
3557   case X86ISD::VPERMILPI:
3558   case X86ISD::VPERMI:
3559     return DAG.getNode(Opc, dl, VT, V1,
3560                        DAG.getConstant(TargetMask, dl, MVT::i8));
3561   }
3562 }
3563
3564 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3565                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3566   switch(Opc) {
3567   default: llvm_unreachable("Unknown x86 shuffle node");
3568   case X86ISD::MOVLHPS:
3569   case X86ISD::MOVLHPD:
3570   case X86ISD::MOVHLPS:
3571   case X86ISD::MOVLPS:
3572   case X86ISD::MOVLPD:
3573   case X86ISD::MOVSS:
3574   case X86ISD::MOVSD:
3575   case X86ISD::UNPCKL:
3576   case X86ISD::UNPCKH:
3577     return DAG.getNode(Opc, dl, VT, V1, V2);
3578   }
3579 }
3580
3581 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3582   MachineFunction &MF = DAG.getMachineFunction();
3583   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3584   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3585   int ReturnAddrIndex = FuncInfo->getRAIndex();
3586
3587   if (ReturnAddrIndex == 0) {
3588     // Set up a frame object for the return address.
3589     unsigned SlotSize = RegInfo->getSlotSize();
3590     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3591                                                            -(int64_t)SlotSize,
3592                                                            false);
3593     FuncInfo->setRAIndex(ReturnAddrIndex);
3594   }
3595
3596   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3597 }
3598
3599 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3600                                        bool hasSymbolicDisplacement) {
3601   // Offset should fit into 32 bit immediate field.
3602   if (!isInt<32>(Offset))
3603     return false;
3604
3605   // If we don't have a symbolic displacement - we don't have any extra
3606   // restrictions.
3607   if (!hasSymbolicDisplacement)
3608     return true;
3609
3610   // FIXME: Some tweaks might be needed for medium code model.
3611   if (M != CodeModel::Small && M != CodeModel::Kernel)
3612     return false;
3613
3614   // For small code model we assume that latest object is 16MB before end of 31
3615   // bits boundary. We may also accept pretty large negative constants knowing
3616   // that all objects are in the positive half of address space.
3617   if (M == CodeModel::Small && Offset < 16*1024*1024)
3618     return true;
3619
3620   // For kernel code model we know that all object resist in the negative half
3621   // of 32bits address space. We may not accept negative offsets, since they may
3622   // be just off and we may accept pretty large positive ones.
3623   if (M == CodeModel::Kernel && Offset >= 0)
3624     return true;
3625
3626   return false;
3627 }
3628
3629 /// isCalleePop - Determines whether the callee is required to pop its
3630 /// own arguments. Callee pop is necessary to support tail calls.
3631 bool X86::isCalleePop(CallingConv::ID CallingConv,
3632                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3633   switch (CallingConv) {
3634   default:
3635     return false;
3636   case CallingConv::X86_StdCall:
3637   case CallingConv::X86_FastCall:
3638   case CallingConv::X86_ThisCall:
3639     return !is64Bit;
3640   case CallingConv::Fast:
3641   case CallingConv::GHC:
3642   case CallingConv::HiPE:
3643     if (IsVarArg)
3644       return false;
3645     return TailCallOpt;
3646   }
3647 }
3648
3649 /// \brief Return true if the condition is an unsigned comparison operation.
3650 static bool isX86CCUnsigned(unsigned X86CC) {
3651   switch (X86CC) {
3652   default: llvm_unreachable("Invalid integer condition!");
3653   case X86::COND_E:     return true;
3654   case X86::COND_G:     return false;
3655   case X86::COND_GE:    return false;
3656   case X86::COND_L:     return false;
3657   case X86::COND_LE:    return false;
3658   case X86::COND_NE:    return true;
3659   case X86::COND_B:     return true;
3660   case X86::COND_A:     return true;
3661   case X86::COND_BE:    return true;
3662   case X86::COND_AE:    return true;
3663   }
3664   llvm_unreachable("covered switch fell through?!");
3665 }
3666
3667 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3668 /// specific condition code, returning the condition code and the LHS/RHS of the
3669 /// comparison to make.
3670 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3671                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3672   if (!isFP) {
3673     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3674       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3675         // X > -1   -> X == 0, jump !sign.
3676         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3677         return X86::COND_NS;
3678       }
3679       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3680         // X < 0   -> X == 0, jump on sign.
3681         return X86::COND_S;
3682       }
3683       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3684         // X < 1   -> X <= 0
3685         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3686         return X86::COND_LE;
3687       }
3688     }
3689
3690     switch (SetCCOpcode) {
3691     default: llvm_unreachable("Invalid integer condition!");
3692     case ISD::SETEQ:  return X86::COND_E;
3693     case ISD::SETGT:  return X86::COND_G;
3694     case ISD::SETGE:  return X86::COND_GE;
3695     case ISD::SETLT:  return X86::COND_L;
3696     case ISD::SETLE:  return X86::COND_LE;
3697     case ISD::SETNE:  return X86::COND_NE;
3698     case ISD::SETULT: return X86::COND_B;
3699     case ISD::SETUGT: return X86::COND_A;
3700     case ISD::SETULE: return X86::COND_BE;
3701     case ISD::SETUGE: return X86::COND_AE;
3702     }
3703   }
3704
3705   // First determine if it is required or is profitable to flip the operands.
3706
3707   // If LHS is a foldable load, but RHS is not, flip the condition.
3708   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3709       !ISD::isNON_EXTLoad(RHS.getNode())) {
3710     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3711     std::swap(LHS, RHS);
3712   }
3713
3714   switch (SetCCOpcode) {
3715   default: break;
3716   case ISD::SETOLT:
3717   case ISD::SETOLE:
3718   case ISD::SETUGT:
3719   case ISD::SETUGE:
3720     std::swap(LHS, RHS);
3721     break;
3722   }
3723
3724   // On a floating point condition, the flags are set as follows:
3725   // ZF  PF  CF   op
3726   //  0 | 0 | 0 | X > Y
3727   //  0 | 0 | 1 | X < Y
3728   //  1 | 0 | 0 | X == Y
3729   //  1 | 1 | 1 | unordered
3730   switch (SetCCOpcode) {
3731   default: llvm_unreachable("Condcode should be pre-legalized away");
3732   case ISD::SETUEQ:
3733   case ISD::SETEQ:   return X86::COND_E;
3734   case ISD::SETOLT:              // flipped
3735   case ISD::SETOGT:
3736   case ISD::SETGT:   return X86::COND_A;
3737   case ISD::SETOLE:              // flipped
3738   case ISD::SETOGE:
3739   case ISD::SETGE:   return X86::COND_AE;
3740   case ISD::SETUGT:              // flipped
3741   case ISD::SETULT:
3742   case ISD::SETLT:   return X86::COND_B;
3743   case ISD::SETUGE:              // flipped
3744   case ISD::SETULE:
3745   case ISD::SETLE:   return X86::COND_BE;
3746   case ISD::SETONE:
3747   case ISD::SETNE:   return X86::COND_NE;
3748   case ISD::SETUO:   return X86::COND_P;
3749   case ISD::SETO:    return X86::COND_NP;
3750   case ISD::SETOEQ:
3751   case ISD::SETUNE:  return X86::COND_INVALID;
3752   }
3753 }
3754
3755 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3756 /// code. Current x86 isa includes the following FP cmov instructions:
3757 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3758 static bool hasFPCMov(unsigned X86CC) {
3759   switch (X86CC) {
3760   default:
3761     return false;
3762   case X86::COND_B:
3763   case X86::COND_BE:
3764   case X86::COND_E:
3765   case X86::COND_P:
3766   case X86::COND_A:
3767   case X86::COND_AE:
3768   case X86::COND_NE:
3769   case X86::COND_NP:
3770     return true;
3771   }
3772 }
3773
3774 /// isFPImmLegal - Returns true if the target can instruction select the
3775 /// specified FP immediate natively. If false, the legalizer will
3776 /// materialize the FP immediate as a load from a constant pool.
3777 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3778   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3779     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3780       return true;
3781   }
3782   return false;
3783 }
3784
3785 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3786                                               ISD::LoadExtType ExtTy,
3787                                               EVT NewVT) const {
3788   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3789   // relocation target a movq or addq instruction: don't let the load shrink.
3790   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3791   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3792     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3793       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3794   return true;
3795 }
3796
3797 /// \brief Returns true if it is beneficial to convert a load of a constant
3798 /// to just the constant itself.
3799 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3800                                                           Type *Ty) const {
3801   assert(Ty->isIntegerTy());
3802
3803   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3804   if (BitSize == 0 || BitSize > 64)
3805     return false;
3806   return true;
3807 }
3808
3809 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3810                                                 unsigned Index) const {
3811   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3812     return false;
3813
3814   return (Index == 0 || Index == ResVT.getVectorNumElements());
3815 }
3816
3817 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3818   // Speculate cttz only if we can directly use TZCNT.
3819   return Subtarget->hasBMI();
3820 }
3821
3822 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3823   // Speculate ctlz only if we can directly use LZCNT.
3824   return Subtarget->hasLZCNT();
3825 }
3826
3827 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3828 /// the specified range (L, H].
3829 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3830   return (Val < 0) || (Val >= Low && Val < Hi);
3831 }
3832
3833 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3834 /// specified value.
3835 static bool isUndefOrEqual(int Val, int CmpVal) {
3836   return (Val < 0 || Val == CmpVal);
3837 }
3838
3839 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3840 /// from position Pos and ending in Pos+Size, falls within the specified
3841 /// sequential range (Low, Low+Size]. or is undef.
3842 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3843                                        unsigned Pos, unsigned Size, int Low) {
3844   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3845     if (!isUndefOrEqual(Mask[i], Low))
3846       return false;
3847   return true;
3848 }
3849
3850 /// isVEXTRACTIndex - Return true if the specified
3851 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3852 /// suitable for instruction that extract 128 or 256 bit vectors
3853 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3854   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3855   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3856     return false;
3857
3858   // The index should be aligned on a vecWidth-bit boundary.
3859   uint64_t Index =
3860     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3861
3862   MVT VT = N->getSimpleValueType(0);
3863   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3864   bool Result = (Index * ElSize) % vecWidth == 0;
3865
3866   return Result;
3867 }
3868
3869 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3870 /// operand specifies a subvector insert that is suitable for input to
3871 /// insertion of 128 or 256-bit subvectors
3872 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3873   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3874   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3875     return false;
3876   // The index should be aligned on a vecWidth-bit boundary.
3877   uint64_t Index =
3878     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3879
3880   MVT VT = N->getSimpleValueType(0);
3881   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3882   bool Result = (Index * ElSize) % vecWidth == 0;
3883
3884   return Result;
3885 }
3886
3887 bool X86::isVINSERT128Index(SDNode *N) {
3888   return isVINSERTIndex(N, 128);
3889 }
3890
3891 bool X86::isVINSERT256Index(SDNode *N) {
3892   return isVINSERTIndex(N, 256);
3893 }
3894
3895 bool X86::isVEXTRACT128Index(SDNode *N) {
3896   return isVEXTRACTIndex(N, 128);
3897 }
3898
3899 bool X86::isVEXTRACT256Index(SDNode *N) {
3900   return isVEXTRACTIndex(N, 256);
3901 }
3902
3903 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3904   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3905   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3906     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3907
3908   uint64_t Index =
3909     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3910
3911   MVT VecVT = N->getOperand(0).getSimpleValueType();
3912   MVT ElVT = VecVT.getVectorElementType();
3913
3914   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3915   return Index / NumElemsPerChunk;
3916 }
3917
3918 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3919   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3920   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3921     llvm_unreachable("Illegal insert subvector for VINSERT");
3922
3923   uint64_t Index =
3924     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3925
3926   MVT VecVT = N->getSimpleValueType(0);
3927   MVT ElVT = VecVT.getVectorElementType();
3928
3929   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3930   return Index / NumElemsPerChunk;
3931 }
3932
3933 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3934 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3935 /// and VINSERTI128 instructions.
3936 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3937   return getExtractVEXTRACTImmediate(N, 128);
3938 }
3939
3940 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3941 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3942 /// and VINSERTI64x4 instructions.
3943 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3944   return getExtractVEXTRACTImmediate(N, 256);
3945 }
3946
3947 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3948 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3949 /// and VINSERTI128 instructions.
3950 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3951   return getInsertVINSERTImmediate(N, 128);
3952 }
3953
3954 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3955 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3956 /// and VINSERTI64x4 instructions.
3957 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3958   return getInsertVINSERTImmediate(N, 256);
3959 }
3960
3961 /// isZero - Returns true if Elt is a constant integer zero
3962 static bool isZero(SDValue V) {
3963   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3964   return C && C->isNullValue();
3965 }
3966
3967 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3968 /// constant +0.0.
3969 bool X86::isZeroNode(SDValue Elt) {
3970   if (isZero(Elt))
3971     return true;
3972   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3973     return CFP->getValueAPF().isPosZero();
3974   return false;
3975 }
3976
3977 /// getZeroVector - Returns a vector of specified type with all zero elements.
3978 ///
3979 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
3980                              SelectionDAG &DAG, SDLoc dl) {
3981   assert(VT.isVector() && "Expected a vector type");
3982
3983   // Always build SSE zero vectors as <4 x i32> bitcasted
3984   // to their dest type. This ensures they get CSE'd.
3985   SDValue Vec;
3986   if (VT.is128BitVector()) {  // SSE
3987     if (Subtarget->hasSSE2()) {  // SSE2
3988       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
3989       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3990     } else { // SSE1
3991       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
3992       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3993     }
3994   } else if (VT.is256BitVector()) { // AVX
3995     if (Subtarget->hasInt256()) { // AVX2
3996       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
3997       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3998       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
3999     } else {
4000       // 256-bit logic and arithmetic instructions in AVX are all
4001       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4002       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4003       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4004       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4005     }
4006   } else if (VT.is512BitVector()) { // AVX-512
4007       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4008       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4009                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4010       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4011   } else if (VT.getScalarType() == MVT::i1) {
4012
4013     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4014             && "Unexpected vector type");
4015     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4016             && "Unexpected vector type");
4017     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4018     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4019     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4020   } else
4021     llvm_unreachable("Unexpected vector type");
4022
4023   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4024 }
4025
4026 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4027                                 SelectionDAG &DAG, SDLoc dl,
4028                                 unsigned vectorWidth) {
4029   assert((vectorWidth == 128 || vectorWidth == 256) &&
4030          "Unsupported vector width");
4031   EVT VT = Vec.getValueType();
4032   EVT ElVT = VT.getVectorElementType();
4033   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4034   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4035                                   VT.getVectorNumElements()/Factor);
4036
4037   // Extract from UNDEF is UNDEF.
4038   if (Vec.getOpcode() == ISD::UNDEF)
4039     return DAG.getUNDEF(ResultVT);
4040
4041   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4042   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4043
4044   // This is the index of the first element of the vectorWidth-bit chunk
4045   // we want.
4046   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4047                                * ElemsPerChunk);
4048
4049   // If the input is a buildvector just emit a smaller one.
4050   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4051     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4052                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4053                                     ElemsPerChunk));
4054
4055   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4056   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4057 }
4058
4059 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4060 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4061 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4062 /// instructions or a simple subregister reference. Idx is an index in the
4063 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4064 /// lowering EXTRACT_VECTOR_ELT operations easier.
4065 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4066                                    SelectionDAG &DAG, SDLoc dl) {
4067   assert((Vec.getValueType().is256BitVector() ||
4068           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4069   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4070 }
4071
4072 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4073 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4074                                    SelectionDAG &DAG, SDLoc dl) {
4075   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4076   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4077 }
4078
4079 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4080                                unsigned IdxVal, SelectionDAG &DAG,
4081                                SDLoc dl, unsigned vectorWidth) {
4082   assert((vectorWidth == 128 || vectorWidth == 256) &&
4083          "Unsupported vector width");
4084   // Inserting UNDEF is Result
4085   if (Vec.getOpcode() == ISD::UNDEF)
4086     return Result;
4087   EVT VT = Vec.getValueType();
4088   EVT ElVT = VT.getVectorElementType();
4089   EVT ResultVT = Result.getValueType();
4090
4091   // Insert the relevant vectorWidth bits.
4092   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4093
4094   // This is the index of the first element of the vectorWidth-bit chunk
4095   // we want.
4096   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4097                                * ElemsPerChunk);
4098
4099   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4100   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4101 }
4102
4103 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4104 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4105 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4106 /// simple superregister reference.  Idx is an index in the 128 bits
4107 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4108 /// lowering INSERT_VECTOR_ELT operations easier.
4109 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4110                                   SelectionDAG &DAG, SDLoc dl) {
4111   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4112
4113   // For insertion into the zero index (low half) of a 256-bit vector, it is
4114   // more efficient to generate a blend with immediate instead of an insert*128.
4115   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4116   // extend the subvector to the size of the result vector. Make sure that
4117   // we are not recursing on that node by checking for undef here.
4118   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4119       Result.getOpcode() != ISD::UNDEF) {
4120     EVT ResultVT = Result.getValueType();
4121     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4122     SDValue Undef = DAG.getUNDEF(ResultVT);
4123     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4124                                  Vec, ZeroIndex);
4125
4126     // The blend instruction, and therefore its mask, depend on the data type.
4127     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4128     if (ScalarType.isFloatingPoint()) {
4129       // Choose either vblendps (float) or vblendpd (double).
4130       unsigned ScalarSize = ScalarType.getSizeInBits();
4131       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4132       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4133       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4134       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4135     }
4136
4137     const X86Subtarget &Subtarget =
4138     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4139
4140     // AVX2 is needed for 256-bit integer blend support.
4141     // Integers must be cast to 32-bit because there is only vpblendd;
4142     // vpblendw can't be used for this because it has a handicapped mask.
4143
4144     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4145     // is still more efficient than using the wrong domain vinsertf128 that
4146     // will be created by InsertSubVector().
4147     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4148
4149     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4150     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4151     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4152     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4153   }
4154
4155   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4156 }
4157
4158 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4159                                   SelectionDAG &DAG, SDLoc dl) {
4160   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4161   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4162 }
4163
4164 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4165 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4166 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4167 /// large BUILD_VECTORS.
4168 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4169                                    unsigned NumElems, SelectionDAG &DAG,
4170                                    SDLoc dl) {
4171   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4172   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4173 }
4174
4175 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4176                                    unsigned NumElems, SelectionDAG &DAG,
4177                                    SDLoc dl) {
4178   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4179   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4180 }
4181
4182 /// getOnesVector - Returns a vector of specified type with all bits set.
4183 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4184 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4185 /// Then bitcast to their original type, ensuring they get CSE'd.
4186 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4187                              SDLoc dl) {
4188   assert(VT.isVector() && "Expected a vector type");
4189
4190   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4191   SDValue Vec;
4192   if (VT.is256BitVector()) {
4193     if (HasInt256) { // AVX2
4194       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4195       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4196     } else { // AVX
4197       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4198       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4199     }
4200   } else if (VT.is128BitVector()) {
4201     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4202   } else
4203     llvm_unreachable("Unexpected vector type");
4204
4205   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4206 }
4207
4208 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4209 /// operation of specified width.
4210 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4211                        SDValue V2) {
4212   unsigned NumElems = VT.getVectorNumElements();
4213   SmallVector<int, 8> Mask;
4214   Mask.push_back(NumElems);
4215   for (unsigned i = 1; i != NumElems; ++i)
4216     Mask.push_back(i);
4217   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4218 }
4219
4220 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4221 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4222                           SDValue V2) {
4223   unsigned NumElems = VT.getVectorNumElements();
4224   SmallVector<int, 8> Mask;
4225   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4226     Mask.push_back(i);
4227     Mask.push_back(i + NumElems);
4228   }
4229   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4230 }
4231
4232 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4233 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4234                           SDValue V2) {
4235   unsigned NumElems = VT.getVectorNumElements();
4236   SmallVector<int, 8> Mask;
4237   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4238     Mask.push_back(i + Half);
4239     Mask.push_back(i + NumElems + Half);
4240   }
4241   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4242 }
4243
4244 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4245 /// vector of zero or undef vector.  This produces a shuffle where the low
4246 /// element of V2 is swizzled into the zero/undef vector, landing at element
4247 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4248 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4249                                            bool IsZero,
4250                                            const X86Subtarget *Subtarget,
4251                                            SelectionDAG &DAG) {
4252   MVT VT = V2.getSimpleValueType();
4253   SDValue V1 = IsZero
4254     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4255   unsigned NumElems = VT.getVectorNumElements();
4256   SmallVector<int, 16> MaskVec;
4257   for (unsigned i = 0; i != NumElems; ++i)
4258     // If this is the insertion idx, put the low elt of V2 here.
4259     MaskVec.push_back(i == Idx ? NumElems : i);
4260   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4261 }
4262
4263 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4264 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4265 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4266 /// shuffles which use a single input multiple times, and in those cases it will
4267 /// adjust the mask to only have indices within that single input.
4268 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4269                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4270   unsigned NumElems = VT.getVectorNumElements();
4271   SDValue ImmN;
4272
4273   IsUnary = false;
4274   bool IsFakeUnary = false;
4275   switch(N->getOpcode()) {
4276   case X86ISD::BLENDI:
4277     ImmN = N->getOperand(N->getNumOperands()-1);
4278     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4279     break;
4280   case X86ISD::SHUFP:
4281     ImmN = N->getOperand(N->getNumOperands()-1);
4282     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4283     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4284     break;
4285   case X86ISD::UNPCKH:
4286     DecodeUNPCKHMask(VT, Mask);
4287     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4288     break;
4289   case X86ISD::UNPCKL:
4290     DecodeUNPCKLMask(VT, Mask);
4291     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4292     break;
4293   case X86ISD::MOVHLPS:
4294     DecodeMOVHLPSMask(NumElems, Mask);
4295     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4296     break;
4297   case X86ISD::MOVLHPS:
4298     DecodeMOVLHPSMask(NumElems, Mask);
4299     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4300     break;
4301   case X86ISD::PALIGNR:
4302     ImmN = N->getOperand(N->getNumOperands()-1);
4303     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4304     break;
4305   case X86ISD::PSHUFD:
4306   case X86ISD::VPERMILPI:
4307     ImmN = N->getOperand(N->getNumOperands()-1);
4308     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4309     IsUnary = true;
4310     break;
4311   case X86ISD::PSHUFHW:
4312     ImmN = N->getOperand(N->getNumOperands()-1);
4313     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4314     IsUnary = true;
4315     break;
4316   case X86ISD::PSHUFLW:
4317     ImmN = N->getOperand(N->getNumOperands()-1);
4318     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4319     IsUnary = true;
4320     break;
4321   case X86ISD::PSHUFB: {
4322     IsUnary = true;
4323     SDValue MaskNode = N->getOperand(1);
4324     while (MaskNode->getOpcode() == ISD::BITCAST)
4325       MaskNode = MaskNode->getOperand(0);
4326
4327     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4328       // If we have a build-vector, then things are easy.
4329       EVT VT = MaskNode.getValueType();
4330       assert(VT.isVector() &&
4331              "Can't produce a non-vector with a build_vector!");
4332       if (!VT.isInteger())
4333         return false;
4334
4335       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4336
4337       SmallVector<uint64_t, 32> RawMask;
4338       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4339         SDValue Op = MaskNode->getOperand(i);
4340         if (Op->getOpcode() == ISD::UNDEF) {
4341           RawMask.push_back((uint64_t)SM_SentinelUndef);
4342           continue;
4343         }
4344         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4345         if (!CN)
4346           return false;
4347         APInt MaskElement = CN->getAPIntValue();
4348
4349         // We now have to decode the element which could be any integer size and
4350         // extract each byte of it.
4351         for (int j = 0; j < NumBytesPerElement; ++j) {
4352           // Note that this is x86 and so always little endian: the low byte is
4353           // the first byte of the mask.
4354           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4355           MaskElement = MaskElement.lshr(8);
4356         }
4357       }
4358       DecodePSHUFBMask(RawMask, Mask);
4359       break;
4360     }
4361
4362     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4363     if (!MaskLoad)
4364       return false;
4365
4366     SDValue Ptr = MaskLoad->getBasePtr();
4367     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4368         Ptr->getOpcode() == X86ISD::WrapperRIP)
4369       Ptr = Ptr->getOperand(0);
4370
4371     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4372     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4373       return false;
4374
4375     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4376       DecodePSHUFBMask(C, Mask);
4377       if (Mask.empty())
4378         return false;
4379       break;
4380     }
4381
4382     return false;
4383   }
4384   case X86ISD::VPERMI:
4385     ImmN = N->getOperand(N->getNumOperands()-1);
4386     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4387     IsUnary = true;
4388     break;
4389   case X86ISD::MOVSS:
4390   case X86ISD::MOVSD:
4391     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4392     break;
4393   case X86ISD::VPERM2X128:
4394     ImmN = N->getOperand(N->getNumOperands()-1);
4395     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4396     if (Mask.empty()) return false;
4397     break;
4398   case X86ISD::MOVSLDUP:
4399     DecodeMOVSLDUPMask(VT, Mask);
4400     IsUnary = true;
4401     break;
4402   case X86ISD::MOVSHDUP:
4403     DecodeMOVSHDUPMask(VT, Mask);
4404     IsUnary = true;
4405     break;
4406   case X86ISD::MOVDDUP:
4407     DecodeMOVDDUPMask(VT, Mask);
4408     IsUnary = true;
4409     break;
4410   case X86ISD::MOVLHPD:
4411   case X86ISD::MOVLPD:
4412   case X86ISD::MOVLPS:
4413     // Not yet implemented
4414     return false;
4415   default: llvm_unreachable("unknown target shuffle node");
4416   }
4417
4418   // If we have a fake unary shuffle, the shuffle mask is spread across two
4419   // inputs that are actually the same node. Re-map the mask to always point
4420   // into the first input.
4421   if (IsFakeUnary)
4422     for (int &M : Mask)
4423       if (M >= (int)Mask.size())
4424         M -= Mask.size();
4425
4426   return true;
4427 }
4428
4429 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4430 /// element of the result of the vector shuffle.
4431 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4432                                    unsigned Depth) {
4433   if (Depth == 6)
4434     return SDValue();  // Limit search depth.
4435
4436   SDValue V = SDValue(N, 0);
4437   EVT VT = V.getValueType();
4438   unsigned Opcode = V.getOpcode();
4439
4440   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4441   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4442     int Elt = SV->getMaskElt(Index);
4443
4444     if (Elt < 0)
4445       return DAG.getUNDEF(VT.getVectorElementType());
4446
4447     unsigned NumElems = VT.getVectorNumElements();
4448     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4449                                          : SV->getOperand(1);
4450     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4451   }
4452
4453   // Recurse into target specific vector shuffles to find scalars.
4454   if (isTargetShuffle(Opcode)) {
4455     MVT ShufVT = V.getSimpleValueType();
4456     unsigned NumElems = ShufVT.getVectorNumElements();
4457     SmallVector<int, 16> ShuffleMask;
4458     bool IsUnary;
4459
4460     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4461       return SDValue();
4462
4463     int Elt = ShuffleMask[Index];
4464     if (Elt < 0)
4465       return DAG.getUNDEF(ShufVT.getVectorElementType());
4466
4467     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4468                                          : N->getOperand(1);
4469     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4470                                Depth+1);
4471   }
4472
4473   // Actual nodes that may contain scalar elements
4474   if (Opcode == ISD::BITCAST) {
4475     V = V.getOperand(0);
4476     EVT SrcVT = V.getValueType();
4477     unsigned NumElems = VT.getVectorNumElements();
4478
4479     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4480       return SDValue();
4481   }
4482
4483   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4484     return (Index == 0) ? V.getOperand(0)
4485                         : DAG.getUNDEF(VT.getVectorElementType());
4486
4487   if (V.getOpcode() == ISD::BUILD_VECTOR)
4488     return V.getOperand(Index);
4489
4490   return SDValue();
4491 }
4492
4493 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4494 ///
4495 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4496                                        unsigned NumNonZero, unsigned NumZero,
4497                                        SelectionDAG &DAG,
4498                                        const X86Subtarget* Subtarget,
4499                                        const TargetLowering &TLI) {
4500   if (NumNonZero > 8)
4501     return SDValue();
4502
4503   SDLoc dl(Op);
4504   SDValue V;
4505   bool First = true;
4506
4507   // SSE4.1 - use PINSRB to insert each byte directly.
4508   if (Subtarget->hasSSE41()) {
4509     for (unsigned i = 0; i < 16; ++i) {
4510       bool isNonZero = (NonZeros & (1 << i)) != 0;
4511       if (isNonZero) {
4512         if (First) {
4513           if (NumZero)
4514             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4515           else
4516             V = DAG.getUNDEF(MVT::v16i8);
4517           First = false;
4518         }
4519         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4520                         MVT::v16i8, V, Op.getOperand(i),
4521                         DAG.getIntPtrConstant(i, dl));
4522       }
4523     }
4524
4525     return V;
4526   }
4527
4528   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4529   for (unsigned i = 0; i < 16; ++i) {
4530     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4531     if (ThisIsNonZero && First) {
4532       if (NumZero)
4533         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4534       else
4535         V = DAG.getUNDEF(MVT::v8i16);
4536       First = false;
4537     }
4538
4539     if ((i & 1) != 0) {
4540       SDValue ThisElt, LastElt;
4541       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4542       if (LastIsNonZero) {
4543         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4544                               MVT::i16, Op.getOperand(i-1));
4545       }
4546       if (ThisIsNonZero) {
4547         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4548         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4549                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4550         if (LastIsNonZero)
4551           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4552       } else
4553         ThisElt = LastElt;
4554
4555       if (ThisElt.getNode())
4556         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4557                         DAG.getIntPtrConstant(i/2, dl));
4558     }
4559   }
4560
4561   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4562 }
4563
4564 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4565 ///
4566 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4567                                      unsigned NumNonZero, unsigned NumZero,
4568                                      SelectionDAG &DAG,
4569                                      const X86Subtarget* Subtarget,
4570                                      const TargetLowering &TLI) {
4571   if (NumNonZero > 4)
4572     return SDValue();
4573
4574   SDLoc dl(Op);
4575   SDValue V;
4576   bool First = true;
4577   for (unsigned i = 0; i < 8; ++i) {
4578     bool isNonZero = (NonZeros & (1 << i)) != 0;
4579     if (isNonZero) {
4580       if (First) {
4581         if (NumZero)
4582           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4583         else
4584           V = DAG.getUNDEF(MVT::v8i16);
4585         First = false;
4586       }
4587       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4588                       MVT::v8i16, V, Op.getOperand(i),
4589                       DAG.getIntPtrConstant(i, dl));
4590     }
4591   }
4592
4593   return V;
4594 }
4595
4596 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4597 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4598                                      const X86Subtarget *Subtarget,
4599                                      const TargetLowering &TLI) {
4600   // Find all zeroable elements.
4601   std::bitset<4> Zeroable;
4602   for (int i=0; i < 4; ++i) {
4603     SDValue Elt = Op->getOperand(i);
4604     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4605   }
4606   assert(Zeroable.size() - Zeroable.count() > 1 &&
4607          "We expect at least two non-zero elements!");
4608
4609   // We only know how to deal with build_vector nodes where elements are either
4610   // zeroable or extract_vector_elt with constant index.
4611   SDValue FirstNonZero;
4612   unsigned FirstNonZeroIdx;
4613   for (unsigned i=0; i < 4; ++i) {
4614     if (Zeroable[i])
4615       continue;
4616     SDValue Elt = Op->getOperand(i);
4617     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4618         !isa<ConstantSDNode>(Elt.getOperand(1)))
4619       return SDValue();
4620     // Make sure that this node is extracting from a 128-bit vector.
4621     MVT VT = Elt.getOperand(0).getSimpleValueType();
4622     if (!VT.is128BitVector())
4623       return SDValue();
4624     if (!FirstNonZero.getNode()) {
4625       FirstNonZero = Elt;
4626       FirstNonZeroIdx = i;
4627     }
4628   }
4629
4630   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4631   SDValue V1 = FirstNonZero.getOperand(0);
4632   MVT VT = V1.getSimpleValueType();
4633
4634   // See if this build_vector can be lowered as a blend with zero.
4635   SDValue Elt;
4636   unsigned EltMaskIdx, EltIdx;
4637   int Mask[4];
4638   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4639     if (Zeroable[EltIdx]) {
4640       // The zero vector will be on the right hand side.
4641       Mask[EltIdx] = EltIdx+4;
4642       continue;
4643     }
4644
4645     Elt = Op->getOperand(EltIdx);
4646     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4647     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4648     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4649       break;
4650     Mask[EltIdx] = EltIdx;
4651   }
4652
4653   if (EltIdx == 4) {
4654     // Let the shuffle legalizer deal with blend operations.
4655     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4656     if (V1.getSimpleValueType() != VT)
4657       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4658     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4659   }
4660
4661   // See if we can lower this build_vector to a INSERTPS.
4662   if (!Subtarget->hasSSE41())
4663     return SDValue();
4664
4665   SDValue V2 = Elt.getOperand(0);
4666   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4667     V1 = SDValue();
4668
4669   bool CanFold = true;
4670   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4671     if (Zeroable[i])
4672       continue;
4673
4674     SDValue Current = Op->getOperand(i);
4675     SDValue SrcVector = Current->getOperand(0);
4676     if (!V1.getNode())
4677       V1 = SrcVector;
4678     CanFold = SrcVector == V1 &&
4679       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4680   }
4681
4682   if (!CanFold)
4683     return SDValue();
4684
4685   assert(V1.getNode() && "Expected at least two non-zero elements!");
4686   if (V1.getSimpleValueType() != MVT::v4f32)
4687     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4688   if (V2.getSimpleValueType() != MVT::v4f32)
4689     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4690
4691   // Ok, we can emit an INSERTPS instruction.
4692   unsigned ZMask = Zeroable.to_ulong();
4693
4694   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4695   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4696   SDLoc DL(Op);
4697   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4698                                DAG.getIntPtrConstant(InsertPSMask, DL));
4699   return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4700 }
4701
4702 /// Return a vector logical shift node.
4703 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4704                          unsigned NumBits, SelectionDAG &DAG,
4705                          const TargetLowering &TLI, SDLoc dl) {
4706   assert(VT.is128BitVector() && "Unknown type for VShift");
4707   MVT ShVT = MVT::v2i64;
4708   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4709   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4710   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4711   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4712   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4713   return DAG.getNode(ISD::BITCAST, dl, VT,
4714                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4715 }
4716
4717 static SDValue
4718 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4719
4720   // Check if the scalar load can be widened into a vector load. And if
4721   // the address is "base + cst" see if the cst can be "absorbed" into
4722   // the shuffle mask.
4723   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4724     SDValue Ptr = LD->getBasePtr();
4725     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4726       return SDValue();
4727     EVT PVT = LD->getValueType(0);
4728     if (PVT != MVT::i32 && PVT != MVT::f32)
4729       return SDValue();
4730
4731     int FI = -1;
4732     int64_t Offset = 0;
4733     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4734       FI = FINode->getIndex();
4735       Offset = 0;
4736     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4737                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4738       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4739       Offset = Ptr.getConstantOperandVal(1);
4740       Ptr = Ptr.getOperand(0);
4741     } else {
4742       return SDValue();
4743     }
4744
4745     // FIXME: 256-bit vector instructions don't require a strict alignment,
4746     // improve this code to support it better.
4747     unsigned RequiredAlign = VT.getSizeInBits()/8;
4748     SDValue Chain = LD->getChain();
4749     // Make sure the stack object alignment is at least 16 or 32.
4750     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4751     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4752       if (MFI->isFixedObjectIndex(FI)) {
4753         // Can't change the alignment. FIXME: It's possible to compute
4754         // the exact stack offset and reference FI + adjust offset instead.
4755         // If someone *really* cares about this. That's the way to implement it.
4756         return SDValue();
4757       } else {
4758         MFI->setObjectAlignment(FI, RequiredAlign);
4759       }
4760     }
4761
4762     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4763     // Ptr + (Offset & ~15).
4764     if (Offset < 0)
4765       return SDValue();
4766     if ((Offset % RequiredAlign) & 3)
4767       return SDValue();
4768     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4769     if (StartOffset) {
4770       SDLoc DL(Ptr);
4771       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4772                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4773     }
4774
4775     int EltNo = (Offset - StartOffset) >> 2;
4776     unsigned NumElems = VT.getVectorNumElements();
4777
4778     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4779     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4780                              LD->getPointerInfo().getWithOffset(StartOffset),
4781                              false, false, false, 0);
4782
4783     SmallVector<int, 8> Mask(NumElems, EltNo);
4784
4785     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4786   }
4787
4788   return SDValue();
4789 }
4790
4791 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4792 /// elements can be replaced by a single large load which has the same value as
4793 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4794 ///
4795 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4796 ///
4797 /// FIXME: we'd also like to handle the case where the last elements are zero
4798 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4799 /// There's even a handy isZeroNode for that purpose.
4800 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4801                                         SDLoc &DL, SelectionDAG &DAG,
4802                                         bool isAfterLegalize) {
4803   unsigned NumElems = Elts.size();
4804
4805   LoadSDNode *LDBase = nullptr;
4806   unsigned LastLoadedElt = -1U;
4807
4808   // For each element in the initializer, see if we've found a load or an undef.
4809   // If we don't find an initial load element, or later load elements are
4810   // non-consecutive, bail out.
4811   for (unsigned i = 0; i < NumElems; ++i) {
4812     SDValue Elt = Elts[i];
4813     // Look through a bitcast.
4814     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4815       Elt = Elt.getOperand(0);
4816     if (!Elt.getNode() ||
4817         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4818       return SDValue();
4819     if (!LDBase) {
4820       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4821         return SDValue();
4822       LDBase = cast<LoadSDNode>(Elt.getNode());
4823       LastLoadedElt = i;
4824       continue;
4825     }
4826     if (Elt.getOpcode() == ISD::UNDEF)
4827       continue;
4828
4829     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4830     EVT LdVT = Elt.getValueType();
4831     // Each loaded element must be the correct fractional portion of the
4832     // requested vector load.
4833     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4834       return SDValue();
4835     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4836       return SDValue();
4837     LastLoadedElt = i;
4838   }
4839
4840   // If we have found an entire vector of loads and undefs, then return a large
4841   // load of the entire vector width starting at the base pointer.  If we found
4842   // consecutive loads for the low half, generate a vzext_load node.
4843   if (LastLoadedElt == NumElems - 1) {
4844     assert(LDBase && "Did not find base load for merging consecutive loads");
4845     EVT EltVT = LDBase->getValueType(0);
4846     // Ensure that the input vector size for the merged loads matches the
4847     // cumulative size of the input elements.
4848     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4849       return SDValue();
4850
4851     if (isAfterLegalize &&
4852         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4853       return SDValue();
4854
4855     SDValue NewLd = SDValue();
4856
4857     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4858                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4859                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4860                         LDBase->getAlignment());
4861
4862     if (LDBase->hasAnyUseOfValue(1)) {
4863       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4864                                      SDValue(LDBase, 1),
4865                                      SDValue(NewLd.getNode(), 1));
4866       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4867       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4868                              SDValue(NewLd.getNode(), 1));
4869     }
4870
4871     return NewLd;
4872   }
4873
4874   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4875   //of a v4i32 / v4f32. It's probably worth generalizing.
4876   EVT EltVT = VT.getVectorElementType();
4877   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4878       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4879     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4880     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4881     SDValue ResNode =
4882         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4883                                 LDBase->getPointerInfo(),
4884                                 LDBase->getAlignment(),
4885                                 false/*isVolatile*/, true/*ReadMem*/,
4886                                 false/*WriteMem*/);
4887
4888     // Make sure the newly-created LOAD is in the same position as LDBase in
4889     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4890     // update uses of LDBase's output chain to use the TokenFactor.
4891     if (LDBase->hasAnyUseOfValue(1)) {
4892       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4893                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4894       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4895       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4896                              SDValue(ResNode.getNode(), 1));
4897     }
4898
4899     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4900   }
4901   return SDValue();
4902 }
4903
4904 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4905 /// to generate a splat value for the following cases:
4906 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4907 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4908 /// a scalar load, or a constant.
4909 /// The VBROADCAST node is returned when a pattern is found,
4910 /// or SDValue() otherwise.
4911 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4912                                     SelectionDAG &DAG) {
4913   // VBROADCAST requires AVX.
4914   // TODO: Splats could be generated for non-AVX CPUs using SSE
4915   // instructions, but there's less potential gain for only 128-bit vectors.
4916   if (!Subtarget->hasAVX())
4917     return SDValue();
4918
4919   MVT VT = Op.getSimpleValueType();
4920   SDLoc dl(Op);
4921
4922   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4923          "Unsupported vector type for broadcast.");
4924
4925   SDValue Ld;
4926   bool ConstSplatVal;
4927
4928   switch (Op.getOpcode()) {
4929     default:
4930       // Unknown pattern found.
4931       return SDValue();
4932
4933     case ISD::BUILD_VECTOR: {
4934       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4935       BitVector UndefElements;
4936       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4937
4938       // We need a splat of a single value to use broadcast, and it doesn't
4939       // make any sense if the value is only in one element of the vector.
4940       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4941         return SDValue();
4942
4943       Ld = Splat;
4944       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4945                        Ld.getOpcode() == ISD::ConstantFP);
4946
4947       // Make sure that all of the users of a non-constant load are from the
4948       // BUILD_VECTOR node.
4949       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4950         return SDValue();
4951       break;
4952     }
4953
4954     case ISD::VECTOR_SHUFFLE: {
4955       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4956
4957       // Shuffles must have a splat mask where the first element is
4958       // broadcasted.
4959       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4960         return SDValue();
4961
4962       SDValue Sc = Op.getOperand(0);
4963       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4964           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4965
4966         if (!Subtarget->hasInt256())
4967           return SDValue();
4968
4969         // Use the register form of the broadcast instruction available on AVX2.
4970         if (VT.getSizeInBits() >= 256)
4971           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4972         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4973       }
4974
4975       Ld = Sc.getOperand(0);
4976       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4977                        Ld.getOpcode() == ISD::ConstantFP);
4978
4979       // The scalar_to_vector node and the suspected
4980       // load node must have exactly one user.
4981       // Constants may have multiple users.
4982
4983       // AVX-512 has register version of the broadcast
4984       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4985         Ld.getValueType().getSizeInBits() >= 32;
4986       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4987           !hasRegVer))
4988         return SDValue();
4989       break;
4990     }
4991   }
4992
4993   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4994   bool IsGE256 = (VT.getSizeInBits() >= 256);
4995
4996   // When optimizing for size, generate up to 5 extra bytes for a broadcast
4997   // instruction to save 8 or more bytes of constant pool data.
4998   // TODO: If multiple splats are generated to load the same constant,
4999   // it may be detrimental to overall size. There needs to be a way to detect
5000   // that condition to know if this is truly a size win.
5001   const Function *F = DAG.getMachineFunction().getFunction();
5002   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5003
5004   // Handle broadcasting a single constant scalar from the constant pool
5005   // into a vector.
5006   // On Sandybridge (no AVX2), it is still better to load a constant vector
5007   // from the constant pool and not to broadcast it from a scalar.
5008   // But override that restriction when optimizing for size.
5009   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5010   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5011     EVT CVT = Ld.getValueType();
5012     assert(!CVT.isVector() && "Must not broadcast a vector type");
5013
5014     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5015     // For size optimization, also splat v2f64 and v2i64, and for size opt
5016     // with AVX2, also splat i8 and i16.
5017     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5018     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5019         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5020       const Constant *C = nullptr;
5021       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5022         C = CI->getConstantIntValue();
5023       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5024         C = CF->getConstantFPValue();
5025
5026       assert(C && "Invalid constant type");
5027
5028       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5029       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5030       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5031       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5032                        MachinePointerInfo::getConstantPool(),
5033                        false, false, false, Alignment);
5034
5035       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5036     }
5037   }
5038
5039   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5040
5041   // Handle AVX2 in-register broadcasts.
5042   if (!IsLoad && Subtarget->hasInt256() &&
5043       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5044     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5045
5046   // The scalar source must be a normal load.
5047   if (!IsLoad)
5048     return SDValue();
5049
5050   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5051       (Subtarget->hasVLX() && ScalarSize == 64))
5052     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5053
5054   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5055   // double since there is no vbroadcastsd xmm
5056   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5057     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5058       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5059   }
5060
5061   // Unsupported broadcast.
5062   return SDValue();
5063 }
5064
5065 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5066 /// underlying vector and index.
5067 ///
5068 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5069 /// index.
5070 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5071                                          SDValue ExtIdx) {
5072   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5073   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5074     return Idx;
5075
5076   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5077   // lowered this:
5078   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5079   // to:
5080   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5081   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5082   //                           undef)
5083   //                       Constant<0>)
5084   // In this case the vector is the extract_subvector expression and the index
5085   // is 2, as specified by the shuffle.
5086   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5087   SDValue ShuffleVec = SVOp->getOperand(0);
5088   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5089   assert(ShuffleVecVT.getVectorElementType() ==
5090          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5091
5092   int ShuffleIdx = SVOp->getMaskElt(Idx);
5093   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5094     ExtractedFromVec = ShuffleVec;
5095     return ShuffleIdx;
5096   }
5097   return Idx;
5098 }
5099
5100 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5101   MVT VT = Op.getSimpleValueType();
5102
5103   // Skip if insert_vec_elt is not supported.
5104   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5105   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5106     return SDValue();
5107
5108   SDLoc DL(Op);
5109   unsigned NumElems = Op.getNumOperands();
5110
5111   SDValue VecIn1;
5112   SDValue VecIn2;
5113   SmallVector<unsigned, 4> InsertIndices;
5114   SmallVector<int, 8> Mask(NumElems, -1);
5115
5116   for (unsigned i = 0; i != NumElems; ++i) {
5117     unsigned Opc = Op.getOperand(i).getOpcode();
5118
5119     if (Opc == ISD::UNDEF)
5120       continue;
5121
5122     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5123       // Quit if more than 1 elements need inserting.
5124       if (InsertIndices.size() > 1)
5125         return SDValue();
5126
5127       InsertIndices.push_back(i);
5128       continue;
5129     }
5130
5131     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5132     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5133     // Quit if non-constant index.
5134     if (!isa<ConstantSDNode>(ExtIdx))
5135       return SDValue();
5136     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5137
5138     // Quit if extracted from vector of different type.
5139     if (ExtractedFromVec.getValueType() != VT)
5140       return SDValue();
5141
5142     if (!VecIn1.getNode())
5143       VecIn1 = ExtractedFromVec;
5144     else if (VecIn1 != ExtractedFromVec) {
5145       if (!VecIn2.getNode())
5146         VecIn2 = ExtractedFromVec;
5147       else if (VecIn2 != ExtractedFromVec)
5148         // Quit if more than 2 vectors to shuffle
5149         return SDValue();
5150     }
5151
5152     if (ExtractedFromVec == VecIn1)
5153       Mask[i] = Idx;
5154     else if (ExtractedFromVec == VecIn2)
5155       Mask[i] = Idx + NumElems;
5156   }
5157
5158   if (!VecIn1.getNode())
5159     return SDValue();
5160
5161   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5162   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5163   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5164     unsigned Idx = InsertIndices[i];
5165     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5166                      DAG.getIntPtrConstant(Idx, DL));
5167   }
5168
5169   return NV;
5170 }
5171
5172 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5173 SDValue
5174 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5175
5176   MVT VT = Op.getSimpleValueType();
5177   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5178          "Unexpected type in LowerBUILD_VECTORvXi1!");
5179
5180   SDLoc dl(Op);
5181   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5182     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5183     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5184     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5185   }
5186
5187   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5188     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5189     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5190     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5191   }
5192
5193   bool AllContants = true;
5194   uint64_t Immediate = 0;
5195   int NonConstIdx = -1;
5196   bool IsSplat = true;
5197   unsigned NumNonConsts = 0;
5198   unsigned NumConsts = 0;
5199   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5200     SDValue In = Op.getOperand(idx);
5201     if (In.getOpcode() == ISD::UNDEF)
5202       continue;
5203     if (!isa<ConstantSDNode>(In)) {
5204       AllContants = false;
5205       NonConstIdx = idx;
5206       NumNonConsts++;
5207     } else {
5208       NumConsts++;
5209       if (cast<ConstantSDNode>(In)->getZExtValue())
5210       Immediate |= (1ULL << idx);
5211     }
5212     if (In != Op.getOperand(0))
5213       IsSplat = false;
5214   }
5215
5216   if (AllContants) {
5217     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5218       DAG.getConstant(Immediate, dl, MVT::i16));
5219     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5220                        DAG.getIntPtrConstant(0, dl));
5221   }
5222
5223   if (NumNonConsts == 1 && NonConstIdx != 0) {
5224     SDValue DstVec;
5225     if (NumConsts) {
5226       SDValue VecAsImm = DAG.getConstant(Immediate, dl,
5227                                          MVT::getIntegerVT(VT.getSizeInBits()));
5228       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5229     }
5230     else
5231       DstVec = DAG.getUNDEF(VT);
5232     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5233                        Op.getOperand(NonConstIdx),
5234                        DAG.getIntPtrConstant(NonConstIdx, dl));
5235   }
5236   if (!IsSplat && (NonConstIdx != 0))
5237     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5238   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5239   SDValue Select;
5240   if (IsSplat)
5241     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5242                           DAG.getConstant(-1, dl, SelectVT),
5243                           DAG.getConstant(0, dl, SelectVT));
5244   else
5245     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5246                          DAG.getConstant((Immediate | 1), dl, SelectVT),
5247                          DAG.getConstant(Immediate, dl, SelectVT));
5248   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5249 }
5250
5251 /// \brief Return true if \p N implements a horizontal binop and return the
5252 /// operands for the horizontal binop into V0 and V1.
5253 ///
5254 /// This is a helper function of LowerToHorizontalOp().
5255 /// This function checks that the build_vector \p N in input implements a
5256 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5257 /// operation to match.
5258 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5259 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5260 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5261 /// arithmetic sub.
5262 ///
5263 /// This function only analyzes elements of \p N whose indices are
5264 /// in range [BaseIdx, LastIdx).
5265 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5266                               SelectionDAG &DAG,
5267                               unsigned BaseIdx, unsigned LastIdx,
5268                               SDValue &V0, SDValue &V1) {
5269   EVT VT = N->getValueType(0);
5270
5271   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5272   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5273          "Invalid Vector in input!");
5274
5275   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5276   bool CanFold = true;
5277   unsigned ExpectedVExtractIdx = BaseIdx;
5278   unsigned NumElts = LastIdx - BaseIdx;
5279   V0 = DAG.getUNDEF(VT);
5280   V1 = DAG.getUNDEF(VT);
5281
5282   // Check if N implements a horizontal binop.
5283   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5284     SDValue Op = N->getOperand(i + BaseIdx);
5285
5286     // Skip UNDEFs.
5287     if (Op->getOpcode() == ISD::UNDEF) {
5288       // Update the expected vector extract index.
5289       if (i * 2 == NumElts)
5290         ExpectedVExtractIdx = BaseIdx;
5291       ExpectedVExtractIdx += 2;
5292       continue;
5293     }
5294
5295     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5296
5297     if (!CanFold)
5298       break;
5299
5300     SDValue Op0 = Op.getOperand(0);
5301     SDValue Op1 = Op.getOperand(1);
5302
5303     // Try to match the following pattern:
5304     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5305     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5306         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5307         Op0.getOperand(0) == Op1.getOperand(0) &&
5308         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5309         isa<ConstantSDNode>(Op1.getOperand(1)));
5310     if (!CanFold)
5311       break;
5312
5313     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5314     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5315
5316     if (i * 2 < NumElts) {
5317       if (V0.getOpcode() == ISD::UNDEF) {
5318         V0 = Op0.getOperand(0);
5319         if (V0.getValueType() != VT)
5320           return false;
5321       }
5322     } else {
5323       if (V1.getOpcode() == ISD::UNDEF) {
5324         V1 = Op0.getOperand(0);
5325         if (V1.getValueType() != VT)
5326           return false;
5327       }
5328       if (i * 2 == NumElts)
5329         ExpectedVExtractIdx = BaseIdx;
5330     }
5331
5332     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5333     if (I0 == ExpectedVExtractIdx)
5334       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5335     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5336       // Try to match the following dag sequence:
5337       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5338       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5339     } else
5340       CanFold = false;
5341
5342     ExpectedVExtractIdx += 2;
5343   }
5344
5345   return CanFold;
5346 }
5347
5348 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5349 /// a concat_vector.
5350 ///
5351 /// This is a helper function of LowerToHorizontalOp().
5352 /// This function expects two 256-bit vectors called V0 and V1.
5353 /// At first, each vector is split into two separate 128-bit vectors.
5354 /// Then, the resulting 128-bit vectors are used to implement two
5355 /// horizontal binary operations.
5356 ///
5357 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5358 ///
5359 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5360 /// the two new horizontal binop.
5361 /// When Mode is set, the first horizontal binop dag node would take as input
5362 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5363 /// horizontal binop dag node would take as input the lower 128-bit of V1
5364 /// and the upper 128-bit of V1.
5365 ///   Example:
5366 ///     HADD V0_LO, V0_HI
5367 ///     HADD V1_LO, V1_HI
5368 ///
5369 /// Otherwise, the first horizontal binop dag node takes as input the lower
5370 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5371 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5372 ///   Example:
5373 ///     HADD V0_LO, V1_LO
5374 ///     HADD V0_HI, V1_HI
5375 ///
5376 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5377 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5378 /// the upper 128-bits of the result.
5379 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5380                                      SDLoc DL, SelectionDAG &DAG,
5381                                      unsigned X86Opcode, bool Mode,
5382                                      bool isUndefLO, bool isUndefHI) {
5383   EVT VT = V0.getValueType();
5384   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5385          "Invalid nodes in input!");
5386
5387   unsigned NumElts = VT.getVectorNumElements();
5388   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5389   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5390   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5391   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5392   EVT NewVT = V0_LO.getValueType();
5393
5394   SDValue LO = DAG.getUNDEF(NewVT);
5395   SDValue HI = DAG.getUNDEF(NewVT);
5396
5397   if (Mode) {
5398     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5399     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5400       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5401     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5402       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5403   } else {
5404     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5405     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5406                        V1_LO->getOpcode() != ISD::UNDEF))
5407       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5408
5409     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5410                        V1_HI->getOpcode() != ISD::UNDEF))
5411       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5412   }
5413
5414   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5415 }
5416
5417 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5418 /// node.
5419 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5420                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5421   EVT VT = BV->getValueType(0);
5422   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5423       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5424     return SDValue();
5425
5426   SDLoc DL(BV);
5427   unsigned NumElts = VT.getVectorNumElements();
5428   SDValue InVec0 = DAG.getUNDEF(VT);
5429   SDValue InVec1 = DAG.getUNDEF(VT);
5430
5431   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5432           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5433
5434   // Odd-numbered elements in the input build vector are obtained from
5435   // adding two integer/float elements.
5436   // Even-numbered elements in the input build vector are obtained from
5437   // subtracting two integer/float elements.
5438   unsigned ExpectedOpcode = ISD::FSUB;
5439   unsigned NextExpectedOpcode = ISD::FADD;
5440   bool AddFound = false;
5441   bool SubFound = false;
5442
5443   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5444     SDValue Op = BV->getOperand(i);
5445
5446     // Skip 'undef' values.
5447     unsigned Opcode = Op.getOpcode();
5448     if (Opcode == ISD::UNDEF) {
5449       std::swap(ExpectedOpcode, NextExpectedOpcode);
5450       continue;
5451     }
5452
5453     // Early exit if we found an unexpected opcode.
5454     if (Opcode != ExpectedOpcode)
5455       return SDValue();
5456
5457     SDValue Op0 = Op.getOperand(0);
5458     SDValue Op1 = Op.getOperand(1);
5459
5460     // Try to match the following pattern:
5461     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5462     // Early exit if we cannot match that sequence.
5463     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5464         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5465         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5466         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5467         Op0.getOperand(1) != Op1.getOperand(1))
5468       return SDValue();
5469
5470     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5471     if (I0 != i)
5472       return SDValue();
5473
5474     // We found a valid add/sub node. Update the information accordingly.
5475     if (i & 1)
5476       AddFound = true;
5477     else
5478       SubFound = true;
5479
5480     // Update InVec0 and InVec1.
5481     if (InVec0.getOpcode() == ISD::UNDEF) {
5482       InVec0 = Op0.getOperand(0);
5483       if (InVec0.getValueType() != VT)
5484         return SDValue();
5485     }
5486     if (InVec1.getOpcode() == ISD::UNDEF) {
5487       InVec1 = Op1.getOperand(0);
5488       if (InVec1.getValueType() != VT)
5489         return SDValue();
5490     }
5491
5492     // Make sure that operands in input to each add/sub node always
5493     // come from a same pair of vectors.
5494     if (InVec0 != Op0.getOperand(0)) {
5495       if (ExpectedOpcode == ISD::FSUB)
5496         return SDValue();
5497
5498       // FADD is commutable. Try to commute the operands
5499       // and then test again.
5500       std::swap(Op0, Op1);
5501       if (InVec0 != Op0.getOperand(0))
5502         return SDValue();
5503     }
5504
5505     if (InVec1 != Op1.getOperand(0))
5506       return SDValue();
5507
5508     // Update the pair of expected opcodes.
5509     std::swap(ExpectedOpcode, NextExpectedOpcode);
5510   }
5511
5512   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5513   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5514       InVec1.getOpcode() != ISD::UNDEF)
5515     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5516
5517   return SDValue();
5518 }
5519
5520 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5521 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5522                                    const X86Subtarget *Subtarget,
5523                                    SelectionDAG &DAG) {
5524   EVT VT = BV->getValueType(0);
5525   unsigned NumElts = VT.getVectorNumElements();
5526   unsigned NumUndefsLO = 0;
5527   unsigned NumUndefsHI = 0;
5528   unsigned Half = NumElts/2;
5529
5530   // Count the number of UNDEF operands in the build_vector in input.
5531   for (unsigned i = 0, e = Half; i != e; ++i)
5532     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5533       NumUndefsLO++;
5534
5535   for (unsigned i = Half, e = NumElts; i != e; ++i)
5536     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5537       NumUndefsHI++;
5538
5539   // Early exit if this is either a build_vector of all UNDEFs or all the
5540   // operands but one are UNDEF.
5541   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5542     return SDValue();
5543
5544   SDLoc DL(BV);
5545   SDValue InVec0, InVec1;
5546   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5547     // Try to match an SSE3 float HADD/HSUB.
5548     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5549       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5550
5551     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5552       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5553   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5554     // Try to match an SSSE3 integer HADD/HSUB.
5555     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5556       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5557
5558     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5559       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5560   }
5561
5562   if (!Subtarget->hasAVX())
5563     return SDValue();
5564
5565   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5566     // Try to match an AVX horizontal add/sub of packed single/double
5567     // precision floating point values from 256-bit vectors.
5568     SDValue InVec2, InVec3;
5569     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5570         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5571         ((InVec0.getOpcode() == ISD::UNDEF ||
5572           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5573         ((InVec1.getOpcode() == ISD::UNDEF ||
5574           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5575       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5576
5577     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5578         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5579         ((InVec0.getOpcode() == ISD::UNDEF ||
5580           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5581         ((InVec1.getOpcode() == ISD::UNDEF ||
5582           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5583       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5584   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5585     // Try to match an AVX2 horizontal add/sub of signed integers.
5586     SDValue InVec2, InVec3;
5587     unsigned X86Opcode;
5588     bool CanFold = true;
5589
5590     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5591         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5592         ((InVec0.getOpcode() == ISD::UNDEF ||
5593           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5594         ((InVec1.getOpcode() == ISD::UNDEF ||
5595           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5596       X86Opcode = X86ISD::HADD;
5597     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5598         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5599         ((InVec0.getOpcode() == ISD::UNDEF ||
5600           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5601         ((InVec1.getOpcode() == ISD::UNDEF ||
5602           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5603       X86Opcode = X86ISD::HSUB;
5604     else
5605       CanFold = false;
5606
5607     if (CanFold) {
5608       // Fold this build_vector into a single horizontal add/sub.
5609       // Do this only if the target has AVX2.
5610       if (Subtarget->hasAVX2())
5611         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5612
5613       // Do not try to expand this build_vector into a pair of horizontal
5614       // add/sub if we can emit a pair of scalar add/sub.
5615       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5616         return SDValue();
5617
5618       // Convert this build_vector into a pair of horizontal binop followed by
5619       // a concat vector.
5620       bool isUndefLO = NumUndefsLO == Half;
5621       bool isUndefHI = NumUndefsHI == Half;
5622       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5623                                    isUndefLO, isUndefHI);
5624     }
5625   }
5626
5627   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5628        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5629     unsigned X86Opcode;
5630     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5631       X86Opcode = X86ISD::HADD;
5632     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5633       X86Opcode = X86ISD::HSUB;
5634     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5635       X86Opcode = X86ISD::FHADD;
5636     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5637       X86Opcode = X86ISD::FHSUB;
5638     else
5639       return SDValue();
5640
5641     // Don't try to expand this build_vector into a pair of horizontal add/sub
5642     // if we can simply emit a pair of scalar add/sub.
5643     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5644       return SDValue();
5645
5646     // Convert this build_vector into two horizontal add/sub followed by
5647     // a concat vector.
5648     bool isUndefLO = NumUndefsLO == Half;
5649     bool isUndefHI = NumUndefsHI == Half;
5650     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5651                                  isUndefLO, isUndefHI);
5652   }
5653
5654   return SDValue();
5655 }
5656
5657 SDValue
5658 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5659   SDLoc dl(Op);
5660
5661   MVT VT = Op.getSimpleValueType();
5662   MVT ExtVT = VT.getVectorElementType();
5663   unsigned NumElems = Op.getNumOperands();
5664
5665   // Generate vectors for predicate vectors.
5666   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5667     return LowerBUILD_VECTORvXi1(Op, DAG);
5668
5669   // Vectors containing all zeros can be matched by pxor and xorps later
5670   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5671     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5672     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5673     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5674       return Op;
5675
5676     return getZeroVector(VT, Subtarget, DAG, dl);
5677   }
5678
5679   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5680   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5681   // vpcmpeqd on 256-bit vectors.
5682   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5683     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5684       return Op;
5685
5686     if (!VT.is512BitVector())
5687       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5688   }
5689
5690   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5691   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5692     return AddSub;
5693   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5694     return HorizontalOp;
5695   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5696     return Broadcast;
5697
5698   unsigned EVTBits = ExtVT.getSizeInBits();
5699
5700   unsigned NumZero  = 0;
5701   unsigned NumNonZero = 0;
5702   unsigned NonZeros = 0;
5703   bool IsAllConstants = true;
5704   SmallSet<SDValue, 8> Values;
5705   for (unsigned i = 0; i < NumElems; ++i) {
5706     SDValue Elt = Op.getOperand(i);
5707     if (Elt.getOpcode() == ISD::UNDEF)
5708       continue;
5709     Values.insert(Elt);
5710     if (Elt.getOpcode() != ISD::Constant &&
5711         Elt.getOpcode() != ISD::ConstantFP)
5712       IsAllConstants = false;
5713     if (X86::isZeroNode(Elt))
5714       NumZero++;
5715     else {
5716       NonZeros |= (1 << i);
5717       NumNonZero++;
5718     }
5719   }
5720
5721   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5722   if (NumNonZero == 0)
5723     return DAG.getUNDEF(VT);
5724
5725   // Special case for single non-zero, non-undef, element.
5726   if (NumNonZero == 1) {
5727     unsigned Idx = countTrailingZeros(NonZeros);
5728     SDValue Item = Op.getOperand(Idx);
5729
5730     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5731     // the value are obviously zero, truncate the value to i32 and do the
5732     // insertion that way.  Only do this if the value is non-constant or if the
5733     // value is a constant being inserted into element 0.  It is cheaper to do
5734     // a constant pool load than it is to do a movd + shuffle.
5735     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5736         (!IsAllConstants || Idx == 0)) {
5737       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5738         // Handle SSE only.
5739         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5740         EVT VecVT = MVT::v4i32;
5741
5742         // Truncate the value (which may itself be a constant) to i32, and
5743         // convert it to a vector with movd (S2V+shuffle to zero extend).
5744         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5745         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5746         return DAG.getNode(
5747             ISD::BITCAST, dl, VT,
5748             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5749       }
5750     }
5751
5752     // If we have a constant or non-constant insertion into the low element of
5753     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5754     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5755     // depending on what the source datatype is.
5756     if (Idx == 0) {
5757       if (NumZero == 0)
5758         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5759
5760       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5761           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5762         if (VT.is512BitVector()) {
5763           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5764           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5765                              Item, DAG.getIntPtrConstant(0, dl));
5766         }
5767         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5768                "Expected an SSE value type!");
5769         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5770         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5771         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5772       }
5773
5774       // We can't directly insert an i8 or i16 into a vector, so zero extend
5775       // it to i32 first.
5776       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5777         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5778         if (VT.is256BitVector()) {
5779           if (Subtarget->hasAVX()) {
5780             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5781             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5782           } else {
5783             // Without AVX, we need to extend to a 128-bit vector and then
5784             // insert into the 256-bit vector.
5785             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5786             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5787             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5788           }
5789         } else {
5790           assert(VT.is128BitVector() && "Expected an SSE value type!");
5791           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5792           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5793         }
5794         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5795       }
5796     }
5797
5798     // Is it a vector logical left shift?
5799     if (NumElems == 2 && Idx == 1 &&
5800         X86::isZeroNode(Op.getOperand(0)) &&
5801         !X86::isZeroNode(Op.getOperand(1))) {
5802       unsigned NumBits = VT.getSizeInBits();
5803       return getVShift(true, VT,
5804                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5805                                    VT, Op.getOperand(1)),
5806                        NumBits/2, DAG, *this, dl);
5807     }
5808
5809     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5810       return SDValue();
5811
5812     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5813     // is a non-constant being inserted into an element other than the low one,
5814     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5815     // movd/movss) to move this into the low element, then shuffle it into
5816     // place.
5817     if (EVTBits == 32) {
5818       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5819       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5820     }
5821   }
5822
5823   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5824   if (Values.size() == 1) {
5825     if (EVTBits == 32) {
5826       // Instead of a shuffle like this:
5827       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5828       // Check if it's possible to issue this instead.
5829       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5830       unsigned Idx = countTrailingZeros(NonZeros);
5831       SDValue Item = Op.getOperand(Idx);
5832       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5833         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5834     }
5835     return SDValue();
5836   }
5837
5838   // A vector full of immediates; various special cases are already
5839   // handled, so this is best done with a single constant-pool load.
5840   if (IsAllConstants)
5841     return SDValue();
5842
5843   // For AVX-length vectors, see if we can use a vector load to get all of the
5844   // elements, otherwise build the individual 128-bit pieces and use
5845   // shuffles to put them in place.
5846   if (VT.is256BitVector() || VT.is512BitVector()) {
5847     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5848
5849     // Check for a build vector of consecutive loads.
5850     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5851       return LD;
5852
5853     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5854
5855     // Build both the lower and upper subvector.
5856     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5857                                 makeArrayRef(&V[0], NumElems/2));
5858     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5859                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5860
5861     // Recreate the wider vector with the lower and upper part.
5862     if (VT.is256BitVector())
5863       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5864     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5865   }
5866
5867   // Let legalizer expand 2-wide build_vectors.
5868   if (EVTBits == 64) {
5869     if (NumNonZero == 1) {
5870       // One half is zero or undef.
5871       unsigned Idx = countTrailingZeros(NonZeros);
5872       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5873                                  Op.getOperand(Idx));
5874       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5875     }
5876     return SDValue();
5877   }
5878
5879   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5880   if (EVTBits == 8 && NumElems == 16)
5881     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5882                                         Subtarget, *this))
5883       return V;
5884
5885   if (EVTBits == 16 && NumElems == 8)
5886     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5887                                       Subtarget, *this))
5888       return V;
5889
5890   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5891   if (EVTBits == 32 && NumElems == 4)
5892     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5893       return V;
5894
5895   // If element VT is == 32 bits, turn it into a number of shuffles.
5896   SmallVector<SDValue, 8> V(NumElems);
5897   if (NumElems == 4 && NumZero > 0) {
5898     for (unsigned i = 0; i < 4; ++i) {
5899       bool isZero = !(NonZeros & (1 << i));
5900       if (isZero)
5901         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5902       else
5903         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5904     }
5905
5906     for (unsigned i = 0; i < 2; ++i) {
5907       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5908         default: break;
5909         case 0:
5910           V[i] = V[i*2];  // Must be a zero vector.
5911           break;
5912         case 1:
5913           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5914           break;
5915         case 2:
5916           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5917           break;
5918         case 3:
5919           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5920           break;
5921       }
5922     }
5923
5924     bool Reverse1 = (NonZeros & 0x3) == 2;
5925     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5926     int MaskVec[] = {
5927       Reverse1 ? 1 : 0,
5928       Reverse1 ? 0 : 1,
5929       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5930       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5931     };
5932     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5933   }
5934
5935   if (Values.size() > 1 && VT.is128BitVector()) {
5936     // Check for a build vector of consecutive loads.
5937     for (unsigned i = 0; i < NumElems; ++i)
5938       V[i] = Op.getOperand(i);
5939
5940     // Check for elements which are consecutive loads.
5941     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5942       return LD;
5943
5944     // Check for a build vector from mostly shuffle plus few inserting.
5945     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5946       return Sh;
5947
5948     // For SSE 4.1, use insertps to put the high elements into the low element.
5949     if (Subtarget->hasSSE41()) {
5950       SDValue Result;
5951       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5952         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5953       else
5954         Result = DAG.getUNDEF(VT);
5955
5956       for (unsigned i = 1; i < NumElems; ++i) {
5957         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5958         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5959                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
5960       }
5961       return Result;
5962     }
5963
5964     // Otherwise, expand into a number of unpckl*, start by extending each of
5965     // our (non-undef) elements to the full vector width with the element in the
5966     // bottom slot of the vector (which generates no code for SSE).
5967     for (unsigned i = 0; i < NumElems; ++i) {
5968       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5969         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5970       else
5971         V[i] = DAG.getUNDEF(VT);
5972     }
5973
5974     // Next, we iteratively mix elements, e.g. for v4f32:
5975     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5976     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5977     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5978     unsigned EltStride = NumElems >> 1;
5979     while (EltStride != 0) {
5980       for (unsigned i = 0; i < EltStride; ++i) {
5981         // If V[i+EltStride] is undef and this is the first round of mixing,
5982         // then it is safe to just drop this shuffle: V[i] is already in the
5983         // right place, the one element (since it's the first round) being
5984         // inserted as undef can be dropped.  This isn't safe for successive
5985         // rounds because they will permute elements within both vectors.
5986         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5987             EltStride == NumElems/2)
5988           continue;
5989
5990         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5991       }
5992       EltStride >>= 1;
5993     }
5994     return V[0];
5995   }
5996   return SDValue();
5997 }
5998
5999 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6000 // to create 256-bit vectors from two other 128-bit ones.
6001 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6002   SDLoc dl(Op);
6003   MVT ResVT = Op.getSimpleValueType();
6004
6005   assert((ResVT.is256BitVector() ||
6006           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6007
6008   SDValue V1 = Op.getOperand(0);
6009   SDValue V2 = Op.getOperand(1);
6010   unsigned NumElems = ResVT.getVectorNumElements();
6011   if (ResVT.is256BitVector())
6012     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6013
6014   if (Op.getNumOperands() == 4) {
6015     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6016                                 ResVT.getVectorNumElements()/2);
6017     SDValue V3 = Op.getOperand(2);
6018     SDValue V4 = Op.getOperand(3);
6019     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6020       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6021   }
6022   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6023 }
6024
6025 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6026                                        const X86Subtarget *Subtarget,
6027                                        SelectionDAG & DAG) {
6028   SDLoc dl(Op);
6029   MVT ResVT = Op.getSimpleValueType();
6030   unsigned NumOfOperands = Op.getNumOperands();
6031
6032   assert(isPowerOf2_32(NumOfOperands) &&
6033          "Unexpected number of operands in CONCAT_VECTORS");
6034
6035   if (NumOfOperands > 2) {
6036     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6037                                   ResVT.getVectorNumElements()/2);
6038     SmallVector<SDValue, 2> Ops;
6039     for (unsigned i = 0; i < NumOfOperands/2; i++)
6040       Ops.push_back(Op.getOperand(i));
6041     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6042     Ops.clear();
6043     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6044       Ops.push_back(Op.getOperand(i));
6045     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6046     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6047   }
6048
6049   SDValue V1 = Op.getOperand(0);
6050   SDValue V2 = Op.getOperand(1);
6051   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6052   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6053
6054   if (IsZeroV1 && IsZeroV2)
6055     return getZeroVector(ResVT, Subtarget, DAG, dl);
6056
6057   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6058   SDValue Undef = DAG.getUNDEF(ResVT);
6059   unsigned NumElems = ResVT.getVectorNumElements();
6060   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6061
6062   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6063   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6064   if (IsZeroV1)
6065     return V2;
6066
6067   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6068   // Zero the upper bits of V1
6069   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6070   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6071   if (IsZeroV2)
6072     return V1;
6073   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6074 }
6075
6076 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6077                                    const X86Subtarget *Subtarget,
6078                                    SelectionDAG &DAG) {
6079   MVT VT = Op.getSimpleValueType();
6080   if (VT.getVectorElementType() == MVT::i1)
6081     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6082
6083   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6084          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6085           Op.getNumOperands() == 4)));
6086
6087   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6088   // from two other 128-bit ones.
6089
6090   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6091   return LowerAVXCONCAT_VECTORS(Op, DAG);
6092 }
6093
6094
6095 //===----------------------------------------------------------------------===//
6096 // Vector shuffle lowering
6097 //
6098 // This is an experimental code path for lowering vector shuffles on x86. It is
6099 // designed to handle arbitrary vector shuffles and blends, gracefully
6100 // degrading performance as necessary. It works hard to recognize idiomatic
6101 // shuffles and lower them to optimal instruction patterns without leaving
6102 // a framework that allows reasonably efficient handling of all vector shuffle
6103 // patterns.
6104 //===----------------------------------------------------------------------===//
6105
6106 /// \brief Tiny helper function to identify a no-op mask.
6107 ///
6108 /// This is a somewhat boring predicate function. It checks whether the mask
6109 /// array input, which is assumed to be a single-input shuffle mask of the kind
6110 /// used by the X86 shuffle instructions (not a fully general
6111 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6112 /// in-place shuffle are 'no-op's.
6113 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6114   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6115     if (Mask[i] != -1 && Mask[i] != i)
6116       return false;
6117   return true;
6118 }
6119
6120 /// \brief Helper function to classify a mask as a single-input mask.
6121 ///
6122 /// This isn't a generic single-input test because in the vector shuffle
6123 /// lowering we canonicalize single inputs to be the first input operand. This
6124 /// means we can more quickly test for a single input by only checking whether
6125 /// an input from the second operand exists. We also assume that the size of
6126 /// mask corresponds to the size of the input vectors which isn't true in the
6127 /// fully general case.
6128 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6129   for (int M : Mask)
6130     if (M >= (int)Mask.size())
6131       return false;
6132   return true;
6133 }
6134
6135 /// \brief Test whether there are elements crossing 128-bit lanes in this
6136 /// shuffle mask.
6137 ///
6138 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6139 /// and we routinely test for these.
6140 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6141   int LaneSize = 128 / VT.getScalarSizeInBits();
6142   int Size = Mask.size();
6143   for (int i = 0; i < Size; ++i)
6144     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6145       return true;
6146   return false;
6147 }
6148
6149 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6150 ///
6151 /// This checks a shuffle mask to see if it is performing the same
6152 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6153 /// that it is also not lane-crossing. It may however involve a blend from the
6154 /// same lane of a second vector.
6155 ///
6156 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6157 /// non-trivial to compute in the face of undef lanes. The representation is
6158 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6159 /// entries from both V1 and V2 inputs to the wider mask.
6160 static bool
6161 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6162                                 SmallVectorImpl<int> &RepeatedMask) {
6163   int LaneSize = 128 / VT.getScalarSizeInBits();
6164   RepeatedMask.resize(LaneSize, -1);
6165   int Size = Mask.size();
6166   for (int i = 0; i < Size; ++i) {
6167     if (Mask[i] < 0)
6168       continue;
6169     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6170       // This entry crosses lanes, so there is no way to model this shuffle.
6171       return false;
6172
6173     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6174     if (RepeatedMask[i % LaneSize] == -1)
6175       // This is the first non-undef entry in this slot of a 128-bit lane.
6176       RepeatedMask[i % LaneSize] =
6177           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6178     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6179       // Found a mismatch with the repeated mask.
6180       return false;
6181   }
6182   return true;
6183 }
6184
6185 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6186 /// arguments.
6187 ///
6188 /// This is a fast way to test a shuffle mask against a fixed pattern:
6189 ///
6190 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6191 ///
6192 /// It returns true if the mask is exactly as wide as the argument list, and
6193 /// each element of the mask is either -1 (signifying undef) or the value given
6194 /// in the argument.
6195 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6196                                 ArrayRef<int> ExpectedMask) {
6197   if (Mask.size() != ExpectedMask.size())
6198     return false;
6199
6200   int Size = Mask.size();
6201
6202   // If the values are build vectors, we can look through them to find
6203   // equivalent inputs that make the shuffles equivalent.
6204   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6205   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6206
6207   for (int i = 0; i < Size; ++i)
6208     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6209       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6210       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6211       if (!MaskBV || !ExpectedBV ||
6212           MaskBV->getOperand(Mask[i] % Size) !=
6213               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6214         return false;
6215     }
6216
6217   return true;
6218 }
6219
6220 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6221 ///
6222 /// This helper function produces an 8-bit shuffle immediate corresponding to
6223 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6224 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6225 /// example.
6226 ///
6227 /// NB: We rely heavily on "undef" masks preserving the input lane.
6228 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6229                                           SelectionDAG &DAG) {
6230   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6231   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6232   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6233   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6234   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6235
6236   unsigned Imm = 0;
6237   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6238   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6239   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6240   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6241   return DAG.getConstant(Imm, DL, MVT::i8);
6242 }
6243
6244 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6245 ///
6246 /// This is used as a fallback approach when first class blend instructions are
6247 /// unavailable. Currently it is only suitable for integer vectors, but could
6248 /// be generalized for floating point vectors if desirable.
6249 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6250                                             SDValue V2, ArrayRef<int> Mask,
6251                                             SelectionDAG &DAG) {
6252   assert(VT.isInteger() && "Only supports integer vector types!");
6253   MVT EltVT = VT.getScalarType();
6254   int NumEltBits = EltVT.getSizeInBits();
6255   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6256   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6257                                     EltVT);
6258   SmallVector<SDValue, 16> MaskOps;
6259   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6260     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6261       return SDValue(); // Shuffled input!
6262     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6263   }
6264
6265   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6266   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6267   // We have to cast V2 around.
6268   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6269   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6270                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6271                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6272                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6273   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6274 }
6275
6276 /// \brief Try to emit a blend instruction for a shuffle.
6277 ///
6278 /// This doesn't do any checks for the availability of instructions for blending
6279 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6280 /// be matched in the backend with the type given. What it does check for is
6281 /// that the shuffle mask is in fact a blend.
6282 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6283                                          SDValue V2, ArrayRef<int> Mask,
6284                                          const X86Subtarget *Subtarget,
6285                                          SelectionDAG &DAG) {
6286   unsigned BlendMask = 0;
6287   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6288     if (Mask[i] >= Size) {
6289       if (Mask[i] != i + Size)
6290         return SDValue(); // Shuffled V2 input!
6291       BlendMask |= 1u << i;
6292       continue;
6293     }
6294     if (Mask[i] >= 0 && Mask[i] != i)
6295       return SDValue(); // Shuffled V1 input!
6296   }
6297   switch (VT.SimpleTy) {
6298   case MVT::v2f64:
6299   case MVT::v4f32:
6300   case MVT::v4f64:
6301   case MVT::v8f32:
6302     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6303                        DAG.getConstant(BlendMask, DL, MVT::i8));
6304
6305   case MVT::v4i64:
6306   case MVT::v8i32:
6307     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6308     // FALLTHROUGH
6309   case MVT::v2i64:
6310   case MVT::v4i32:
6311     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6312     // that instruction.
6313     if (Subtarget->hasAVX2()) {
6314       // Scale the blend by the number of 32-bit dwords per element.
6315       int Scale =  VT.getScalarSizeInBits() / 32;
6316       BlendMask = 0;
6317       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6318         if (Mask[i] >= Size)
6319           for (int j = 0; j < Scale; ++j)
6320             BlendMask |= 1u << (i * Scale + j);
6321
6322       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6323       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6324       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6325       return DAG.getNode(ISD::BITCAST, DL, VT,
6326                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6327                                      DAG.getConstant(BlendMask, DL, MVT::i8)));
6328     }
6329     // FALLTHROUGH
6330   case MVT::v8i16: {
6331     // For integer shuffles we need to expand the mask and cast the inputs to
6332     // v8i16s prior to blending.
6333     int Scale = 8 / VT.getVectorNumElements();
6334     BlendMask = 0;
6335     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6336       if (Mask[i] >= Size)
6337         for (int j = 0; j < Scale; ++j)
6338           BlendMask |= 1u << (i * Scale + j);
6339
6340     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6341     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6342     return DAG.getNode(ISD::BITCAST, DL, VT,
6343                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6344                                    DAG.getConstant(BlendMask, DL, MVT::i8)));
6345   }
6346
6347   case MVT::v16i16: {
6348     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6349     SmallVector<int, 8> RepeatedMask;
6350     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6351       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6352       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6353       BlendMask = 0;
6354       for (int i = 0; i < 8; ++i)
6355         if (RepeatedMask[i] >= 16)
6356           BlendMask |= 1u << i;
6357       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6358                          DAG.getConstant(BlendMask, DL, MVT::i8));
6359     }
6360   }
6361     // FALLTHROUGH
6362   case MVT::v16i8:
6363   case MVT::v32i8: {
6364     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6365            "256-bit byte-blends require AVX2 support!");
6366
6367     // Scale the blend by the number of bytes per element.
6368     int Scale = VT.getScalarSizeInBits() / 8;
6369
6370     // This form of blend is always done on bytes. Compute the byte vector
6371     // type.
6372     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6373
6374     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6375     // mix of LLVM's code generator and the x86 backend. We tell the code
6376     // generator that boolean values in the elements of an x86 vector register
6377     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6378     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6379     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6380     // of the element (the remaining are ignored) and 0 in that high bit would
6381     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6382     // the LLVM model for boolean values in vector elements gets the relevant
6383     // bit set, it is set backwards and over constrained relative to x86's
6384     // actual model.
6385     SmallVector<SDValue, 32> VSELECTMask;
6386     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6387       for (int j = 0; j < Scale; ++j)
6388         VSELECTMask.push_back(
6389             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6390                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6391                                           MVT::i8));
6392
6393     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6394     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6395     return DAG.getNode(
6396         ISD::BITCAST, DL, VT,
6397         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6398                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6399                     V1, V2));
6400   }
6401
6402   default:
6403     llvm_unreachable("Not a supported integer vector type!");
6404   }
6405 }
6406
6407 /// \brief Try to lower as a blend of elements from two inputs followed by
6408 /// a single-input permutation.
6409 ///
6410 /// This matches the pattern where we can blend elements from two inputs and
6411 /// then reduce the shuffle to a single-input permutation.
6412 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6413                                                    SDValue V2,
6414                                                    ArrayRef<int> Mask,
6415                                                    SelectionDAG &DAG) {
6416   // We build up the blend mask while checking whether a blend is a viable way
6417   // to reduce the shuffle.
6418   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6419   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6420
6421   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6422     if (Mask[i] < 0)
6423       continue;
6424
6425     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6426
6427     if (BlendMask[Mask[i] % Size] == -1)
6428       BlendMask[Mask[i] % Size] = Mask[i];
6429     else if (BlendMask[Mask[i] % Size] != Mask[i])
6430       return SDValue(); // Can't blend in the needed input!
6431
6432     PermuteMask[i] = Mask[i] % Size;
6433   }
6434
6435   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6436   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6437 }
6438
6439 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6440 /// blends and permutes.
6441 ///
6442 /// This matches the extremely common pattern for handling combined
6443 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6444 /// operations. It will try to pick the best arrangement of shuffles and
6445 /// blends.
6446 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6447                                                           SDValue V1,
6448                                                           SDValue V2,
6449                                                           ArrayRef<int> Mask,
6450                                                           SelectionDAG &DAG) {
6451   // Shuffle the input elements into the desired positions in V1 and V2 and
6452   // blend them together.
6453   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6454   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6455   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6456   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6457     if (Mask[i] >= 0 && Mask[i] < Size) {
6458       V1Mask[i] = Mask[i];
6459       BlendMask[i] = i;
6460     } else if (Mask[i] >= Size) {
6461       V2Mask[i] = Mask[i] - Size;
6462       BlendMask[i] = i + Size;
6463     }
6464
6465   // Try to lower with the simpler initial blend strategy unless one of the
6466   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6467   // shuffle may be able to fold with a load or other benefit. However, when
6468   // we'll have to do 2x as many shuffles in order to achieve this, blending
6469   // first is a better strategy.
6470   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6471     if (SDValue BlendPerm =
6472             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6473       return BlendPerm;
6474
6475   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6476   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6477   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6478 }
6479
6480 /// \brief Try to lower a vector shuffle as a byte rotation.
6481 ///
6482 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6483 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6484 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6485 /// try to generically lower a vector shuffle through such an pattern. It
6486 /// does not check for the profitability of lowering either as PALIGNR or
6487 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6488 /// This matches shuffle vectors that look like:
6489 ///
6490 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6491 ///
6492 /// Essentially it concatenates V1 and V2, shifts right by some number of
6493 /// elements, and takes the low elements as the result. Note that while this is
6494 /// specified as a *right shift* because x86 is little-endian, it is a *left
6495 /// rotate* of the vector lanes.
6496 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6497                                               SDValue V2,
6498                                               ArrayRef<int> Mask,
6499                                               const X86Subtarget *Subtarget,
6500                                               SelectionDAG &DAG) {
6501   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6502
6503   int NumElts = Mask.size();
6504   int NumLanes = VT.getSizeInBits() / 128;
6505   int NumLaneElts = NumElts / NumLanes;
6506
6507   // We need to detect various ways of spelling a rotation:
6508   //   [11, 12, 13, 14, 15,  0,  1,  2]
6509   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6510   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6511   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6512   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6513   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6514   int Rotation = 0;
6515   SDValue Lo, Hi;
6516   for (int l = 0; l < NumElts; l += NumLaneElts) {
6517     for (int i = 0; i < NumLaneElts; ++i) {
6518       if (Mask[l + i] == -1)
6519         continue;
6520       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6521
6522       // Get the mod-Size index and lane correct it.
6523       int LaneIdx = (Mask[l + i] % NumElts) - l;
6524       // Make sure it was in this lane.
6525       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6526         return SDValue();
6527
6528       // Determine where a rotated vector would have started.
6529       int StartIdx = i - LaneIdx;
6530       if (StartIdx == 0)
6531         // The identity rotation isn't interesting, stop.
6532         return SDValue();
6533
6534       // If we found the tail of a vector the rotation must be the missing
6535       // front. If we found the head of a vector, it must be how much of the
6536       // head.
6537       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6538
6539       if (Rotation == 0)
6540         Rotation = CandidateRotation;
6541       else if (Rotation != CandidateRotation)
6542         // The rotations don't match, so we can't match this mask.
6543         return SDValue();
6544
6545       // Compute which value this mask is pointing at.
6546       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6547
6548       // Compute which of the two target values this index should be assigned
6549       // to. This reflects whether the high elements are remaining or the low
6550       // elements are remaining.
6551       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6552
6553       // Either set up this value if we've not encountered it before, or check
6554       // that it remains consistent.
6555       if (!TargetV)
6556         TargetV = MaskV;
6557       else if (TargetV != MaskV)
6558         // This may be a rotation, but it pulls from the inputs in some
6559         // unsupported interleaving.
6560         return SDValue();
6561     }
6562   }
6563
6564   // Check that we successfully analyzed the mask, and normalize the results.
6565   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6566   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6567   if (!Lo)
6568     Lo = Hi;
6569   else if (!Hi)
6570     Hi = Lo;
6571
6572   // The actual rotate instruction rotates bytes, so we need to scale the
6573   // rotation based on how many bytes are in the vector lane.
6574   int Scale = 16 / NumLaneElts;
6575
6576   // SSSE3 targets can use the palignr instruction.
6577   if (Subtarget->hasSSSE3()) {
6578     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6579     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6580     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6581     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6582
6583     return DAG.getNode(ISD::BITCAST, DL, VT,
6584                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6585                                    DAG.getConstant(Rotation * Scale, DL,
6586                                                    MVT::i8)));
6587   }
6588
6589   assert(VT.getSizeInBits() == 128 &&
6590          "Rotate-based lowering only supports 128-bit lowering!");
6591   assert(Mask.size() <= 16 &&
6592          "Can shuffle at most 16 bytes in a 128-bit vector!");
6593
6594   // Default SSE2 implementation
6595   int LoByteShift = 16 - Rotation * Scale;
6596   int HiByteShift = Rotation * Scale;
6597
6598   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6599   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6600   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6601
6602   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6603                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6604   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6605                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6606   return DAG.getNode(ISD::BITCAST, DL, VT,
6607                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6608 }
6609
6610 /// \brief Compute whether each element of a shuffle is zeroable.
6611 ///
6612 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6613 /// Either it is an undef element in the shuffle mask, the element of the input
6614 /// referenced is undef, or the element of the input referenced is known to be
6615 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6616 /// as many lanes with this technique as possible to simplify the remaining
6617 /// shuffle.
6618 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6619                                                      SDValue V1, SDValue V2) {
6620   SmallBitVector Zeroable(Mask.size(), false);
6621
6622   while (V1.getOpcode() == ISD::BITCAST)
6623     V1 = V1->getOperand(0);
6624   while (V2.getOpcode() == ISD::BITCAST)
6625     V2 = V2->getOperand(0);
6626
6627   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6628   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6629
6630   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6631     int M = Mask[i];
6632     // Handle the easy cases.
6633     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6634       Zeroable[i] = true;
6635       continue;
6636     }
6637
6638     // If this is an index into a build_vector node (which has the same number
6639     // of elements), dig out the input value and use it.
6640     SDValue V = M < Size ? V1 : V2;
6641     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6642       continue;
6643
6644     SDValue Input = V.getOperand(M % Size);
6645     // The UNDEF opcode check really should be dead code here, but not quite
6646     // worth asserting on (it isn't invalid, just unexpected).
6647     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6648       Zeroable[i] = true;
6649   }
6650
6651   return Zeroable;
6652 }
6653
6654 /// \brief Try to emit a bitmask instruction for a shuffle.
6655 ///
6656 /// This handles cases where we can model a blend exactly as a bitmask due to
6657 /// one of the inputs being zeroable.
6658 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6659                                            SDValue V2, ArrayRef<int> Mask,
6660                                            SelectionDAG &DAG) {
6661   MVT EltVT = VT.getScalarType();
6662   int NumEltBits = EltVT.getSizeInBits();
6663   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6664   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6665   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6666                                     IntEltVT);
6667   if (EltVT.isFloatingPoint()) {
6668     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6669     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6670   }
6671   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6672   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6673   SDValue V;
6674   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6675     if (Zeroable[i])
6676       continue;
6677     if (Mask[i] % Size != i)
6678       return SDValue(); // Not a blend.
6679     if (!V)
6680       V = Mask[i] < Size ? V1 : V2;
6681     else if (V != (Mask[i] < Size ? V1 : V2))
6682       return SDValue(); // Can only let one input through the mask.
6683
6684     VMaskOps[i] = AllOnes;
6685   }
6686   if (!V)
6687     return SDValue(); // No non-zeroable elements!
6688
6689   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6690   V = DAG.getNode(VT.isFloatingPoint()
6691                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6692                   DL, VT, V, VMask);
6693   return V;
6694 }
6695
6696 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6697 ///
6698 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6699 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6700 /// matches elements from one of the input vectors shuffled to the left or
6701 /// right with zeroable elements 'shifted in'. It handles both the strictly
6702 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6703 /// quad word lane.
6704 ///
6705 /// PSHL : (little-endian) left bit shift.
6706 /// [ zz, 0, zz,  2 ]
6707 /// [ -1, 4, zz, -1 ]
6708 /// PSRL : (little-endian) right bit shift.
6709 /// [  1, zz,  3, zz]
6710 /// [ -1, -1,  7, zz]
6711 /// PSLLDQ : (little-endian) left byte shift
6712 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6713 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6714 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6715 /// PSRLDQ : (little-endian) right byte shift
6716 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6717 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6718 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6719 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6720                                          SDValue V2, ArrayRef<int> Mask,
6721                                          SelectionDAG &DAG) {
6722   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6723
6724   int Size = Mask.size();
6725   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6726
6727   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6728     for (int i = 0; i < Size; i += Scale)
6729       for (int j = 0; j < Shift; ++j)
6730         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6731           return false;
6732
6733     return true;
6734   };
6735
6736   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6737     for (int i = 0; i != Size; i += Scale) {
6738       unsigned Pos = Left ? i + Shift : i;
6739       unsigned Low = Left ? i : i + Shift;
6740       unsigned Len = Scale - Shift;
6741       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6742                                       Low + (V == V1 ? 0 : Size)))
6743         return SDValue();
6744     }
6745
6746     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6747     bool ByteShift = ShiftEltBits > 64;
6748     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6749                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6750     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6751
6752     // Normalize the scale for byte shifts to still produce an i64 element
6753     // type.
6754     Scale = ByteShift ? Scale / 2 : Scale;
6755
6756     // We need to round trip through the appropriate type for the shift.
6757     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6758     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6759     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6760            "Illegal integer vector type");
6761     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6762
6763     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6764                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6765     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6766   };
6767
6768   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6769   // keep doubling the size of the integer elements up to that. We can
6770   // then shift the elements of the integer vector by whole multiples of
6771   // their width within the elements of the larger integer vector. Test each
6772   // multiple to see if we can find a match with the moved element indices
6773   // and that the shifted in elements are all zeroable.
6774   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6775     for (int Shift = 1; Shift != Scale; ++Shift)
6776       for (bool Left : {true, false})
6777         if (CheckZeros(Shift, Scale, Left))
6778           for (SDValue V : {V1, V2})
6779             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6780               return Match;
6781
6782   // no match
6783   return SDValue();
6784 }
6785
6786 /// \brief Lower a vector shuffle as a zero or any extension.
6787 ///
6788 /// Given a specific number of elements, element bit width, and extension
6789 /// stride, produce either a zero or any extension based on the available
6790 /// features of the subtarget.
6791 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6792     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6793     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6794   assert(Scale > 1 && "Need a scale to extend.");
6795   int NumElements = VT.getVectorNumElements();
6796   int EltBits = VT.getScalarSizeInBits();
6797   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6798          "Only 8, 16, and 32 bit elements can be extended.");
6799   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6800
6801   // Found a valid zext mask! Try various lowering strategies based on the
6802   // input type and available ISA extensions.
6803   if (Subtarget->hasSSE41()) {
6804     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6805                                  NumElements / Scale);
6806     return DAG.getNode(ISD::BITCAST, DL, VT,
6807                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6808   }
6809
6810   // For any extends we can cheat for larger element sizes and use shuffle
6811   // instructions that can fold with a load and/or copy.
6812   if (AnyExt && EltBits == 32) {
6813     int PSHUFDMask[4] = {0, -1, 1, -1};
6814     return DAG.getNode(
6815         ISD::BITCAST, DL, VT,
6816         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6817                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6818                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6819   }
6820   if (AnyExt && EltBits == 16 && Scale > 2) {
6821     int PSHUFDMask[4] = {0, -1, 0, -1};
6822     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6823                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6824                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6825     int PSHUFHWMask[4] = {1, -1, -1, -1};
6826     return DAG.getNode(
6827         ISD::BITCAST, DL, VT,
6828         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6829                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6830                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6831   }
6832
6833   // If this would require more than 2 unpack instructions to expand, use
6834   // pshufb when available. We can only use more than 2 unpack instructions
6835   // when zero extending i8 elements which also makes it easier to use pshufb.
6836   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6837     assert(NumElements == 16 && "Unexpected byte vector width!");
6838     SDValue PSHUFBMask[16];
6839     for (int i = 0; i < 16; ++i)
6840       PSHUFBMask[i] =
6841           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6842     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6843     return DAG.getNode(ISD::BITCAST, DL, VT,
6844                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6845                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6846                                                MVT::v16i8, PSHUFBMask)));
6847   }
6848
6849   // Otherwise emit a sequence of unpacks.
6850   do {
6851     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6852     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6853                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6854     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6855     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6856     Scale /= 2;
6857     EltBits *= 2;
6858     NumElements /= 2;
6859   } while (Scale > 1);
6860   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6861 }
6862
6863 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6864 ///
6865 /// This routine will try to do everything in its power to cleverly lower
6866 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6867 /// check for the profitability of this lowering,  it tries to aggressively
6868 /// match this pattern. It will use all of the micro-architectural details it
6869 /// can to emit an efficient lowering. It handles both blends with all-zero
6870 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6871 /// masking out later).
6872 ///
6873 /// The reason we have dedicated lowering for zext-style shuffles is that they
6874 /// are both incredibly common and often quite performance sensitive.
6875 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6876     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6877     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6878   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6879
6880   int Bits = VT.getSizeInBits();
6881   int NumElements = VT.getVectorNumElements();
6882   assert(VT.getScalarSizeInBits() <= 32 &&
6883          "Exceeds 32-bit integer zero extension limit");
6884   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6885
6886   // Define a helper function to check a particular ext-scale and lower to it if
6887   // valid.
6888   auto Lower = [&](int Scale) -> SDValue {
6889     SDValue InputV;
6890     bool AnyExt = true;
6891     for (int i = 0; i < NumElements; ++i) {
6892       if (Mask[i] == -1)
6893         continue; // Valid anywhere but doesn't tell us anything.
6894       if (i % Scale != 0) {
6895         // Each of the extended elements need to be zeroable.
6896         if (!Zeroable[i])
6897           return SDValue();
6898
6899         // We no longer are in the anyext case.
6900         AnyExt = false;
6901         continue;
6902       }
6903
6904       // Each of the base elements needs to be consecutive indices into the
6905       // same input vector.
6906       SDValue V = Mask[i] < NumElements ? V1 : V2;
6907       if (!InputV)
6908         InputV = V;
6909       else if (InputV != V)
6910         return SDValue(); // Flip-flopping inputs.
6911
6912       if (Mask[i] % NumElements != i / Scale)
6913         return SDValue(); // Non-consecutive strided elements.
6914     }
6915
6916     // If we fail to find an input, we have a zero-shuffle which should always
6917     // have already been handled.
6918     // FIXME: Maybe handle this here in case during blending we end up with one?
6919     if (!InputV)
6920       return SDValue();
6921
6922     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6923         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6924   };
6925
6926   // The widest scale possible for extending is to a 64-bit integer.
6927   assert(Bits % 64 == 0 &&
6928          "The number of bits in a vector must be divisible by 64 on x86!");
6929   int NumExtElements = Bits / 64;
6930
6931   // Each iteration, try extending the elements half as much, but into twice as
6932   // many elements.
6933   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6934     assert(NumElements % NumExtElements == 0 &&
6935            "The input vector size must be divisible by the extended size.");
6936     if (SDValue V = Lower(NumElements / NumExtElements))
6937       return V;
6938   }
6939
6940   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6941   if (Bits != 128)
6942     return SDValue();
6943
6944   // Returns one of the source operands if the shuffle can be reduced to a
6945   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6946   auto CanZExtLowHalf = [&]() {
6947     for (int i = NumElements / 2; i != NumElements; ++i)
6948       if (!Zeroable[i])
6949         return SDValue();
6950     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6951       return V1;
6952     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6953       return V2;
6954     return SDValue();
6955   };
6956
6957   if (SDValue V = CanZExtLowHalf()) {
6958     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6959     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6960     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6961   }
6962
6963   // No viable ext lowering found.
6964   return SDValue();
6965 }
6966
6967 /// \brief Try to get a scalar value for a specific element of a vector.
6968 ///
6969 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6970 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6971                                               SelectionDAG &DAG) {
6972   MVT VT = V.getSimpleValueType();
6973   MVT EltVT = VT.getVectorElementType();
6974   while (V.getOpcode() == ISD::BITCAST)
6975     V = V.getOperand(0);
6976   // If the bitcasts shift the element size, we can't extract an equivalent
6977   // element from it.
6978   MVT NewVT = V.getSimpleValueType();
6979   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6980     return SDValue();
6981
6982   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6983       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
6984     // Ensure the scalar operand is the same size as the destination.
6985     // FIXME: Add support for scalar truncation where possible.
6986     SDValue S = V.getOperand(Idx);
6987     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
6988       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
6989   }
6990
6991   return SDValue();
6992 }
6993
6994 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6995 ///
6996 /// This is particularly important because the set of instructions varies
6997 /// significantly based on whether the operand is a load or not.
6998 static bool isShuffleFoldableLoad(SDValue V) {
6999   while (V.getOpcode() == ISD::BITCAST)
7000     V = V.getOperand(0);
7001
7002   return ISD::isNON_EXTLoad(V.getNode());
7003 }
7004
7005 /// \brief Try to lower insertion of a single element into a zero vector.
7006 ///
7007 /// This is a common pattern that we have especially efficient patterns to lower
7008 /// across all subtarget feature sets.
7009 static SDValue lowerVectorShuffleAsElementInsertion(
7010     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7011     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7012   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7013   MVT ExtVT = VT;
7014   MVT EltVT = VT.getVectorElementType();
7015
7016   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7017                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7018                 Mask.begin();
7019   bool IsV1Zeroable = true;
7020   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7021     if (i != V2Index && !Zeroable[i]) {
7022       IsV1Zeroable = false;
7023       break;
7024     }
7025
7026   // Check for a single input from a SCALAR_TO_VECTOR node.
7027   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7028   // all the smarts here sunk into that routine. However, the current
7029   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7030   // vector shuffle lowering is dead.
7031   if (SDValue V2S = getScalarValueForVectorElement(
7032           V2, Mask[V2Index] - Mask.size(), DAG)) {
7033     // We need to zext the scalar if it is smaller than an i32.
7034     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7035     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7036       // Using zext to expand a narrow element won't work for non-zero
7037       // insertions.
7038       if (!IsV1Zeroable)
7039         return SDValue();
7040
7041       // Zero-extend directly to i32.
7042       ExtVT = MVT::v4i32;
7043       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7044     }
7045     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7046   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7047              EltVT == MVT::i16) {
7048     // Either not inserting from the low element of the input or the input
7049     // element size is too small to use VZEXT_MOVL to clear the high bits.
7050     return SDValue();
7051   }
7052
7053   if (!IsV1Zeroable) {
7054     // If V1 can't be treated as a zero vector we have fewer options to lower
7055     // this. We can't support integer vectors or non-zero targets cheaply, and
7056     // the V1 elements can't be permuted in any way.
7057     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7058     if (!VT.isFloatingPoint() || V2Index != 0)
7059       return SDValue();
7060     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7061     V1Mask[V2Index] = -1;
7062     if (!isNoopShuffleMask(V1Mask))
7063       return SDValue();
7064     // This is essentially a special case blend operation, but if we have
7065     // general purpose blend operations, they are always faster. Bail and let
7066     // the rest of the lowering handle these as blends.
7067     if (Subtarget->hasSSE41())
7068       return SDValue();
7069
7070     // Otherwise, use MOVSD or MOVSS.
7071     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7072            "Only two types of floating point element types to handle!");
7073     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7074                        ExtVT, V1, V2);
7075   }
7076
7077   // This lowering only works for the low element with floating point vectors.
7078   if (VT.isFloatingPoint() && V2Index != 0)
7079     return SDValue();
7080
7081   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7082   if (ExtVT != VT)
7083     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7084
7085   if (V2Index != 0) {
7086     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7087     // the desired position. Otherwise it is more efficient to do a vector
7088     // shift left. We know that we can do a vector shift left because all
7089     // the inputs are zero.
7090     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7091       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7092       V2Shuffle[V2Index] = 0;
7093       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7094     } else {
7095       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7096       V2 = DAG.getNode(
7097           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7098           DAG.getConstant(
7099               V2Index * EltVT.getSizeInBits()/8, DL,
7100               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7101       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7102     }
7103   }
7104   return V2;
7105 }
7106
7107 /// \brief Try to lower broadcast of a single element.
7108 ///
7109 /// For convenience, this code also bundles all of the subtarget feature set
7110 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7111 /// a convenient way to factor it out.
7112 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7113                                              ArrayRef<int> Mask,
7114                                              const X86Subtarget *Subtarget,
7115                                              SelectionDAG &DAG) {
7116   if (!Subtarget->hasAVX())
7117     return SDValue();
7118   if (VT.isInteger() && !Subtarget->hasAVX2())
7119     return SDValue();
7120
7121   // Check that the mask is a broadcast.
7122   int BroadcastIdx = -1;
7123   for (int M : Mask)
7124     if (M >= 0 && BroadcastIdx == -1)
7125       BroadcastIdx = M;
7126     else if (M >= 0 && M != BroadcastIdx)
7127       return SDValue();
7128
7129   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7130                                             "a sorted mask where the broadcast "
7131                                             "comes from V1.");
7132
7133   // Go up the chain of (vector) values to find a scalar load that we can
7134   // combine with the broadcast.
7135   for (;;) {
7136     switch (V.getOpcode()) {
7137     case ISD::CONCAT_VECTORS: {
7138       int OperandSize = Mask.size() / V.getNumOperands();
7139       V = V.getOperand(BroadcastIdx / OperandSize);
7140       BroadcastIdx %= OperandSize;
7141       continue;
7142     }
7143
7144     case ISD::INSERT_SUBVECTOR: {
7145       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7146       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7147       if (!ConstantIdx)
7148         break;
7149
7150       int BeginIdx = (int)ConstantIdx->getZExtValue();
7151       int EndIdx =
7152           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7153       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7154         BroadcastIdx -= BeginIdx;
7155         V = VInner;
7156       } else {
7157         V = VOuter;
7158       }
7159       continue;
7160     }
7161     }
7162     break;
7163   }
7164
7165   // Check if this is a broadcast of a scalar. We special case lowering
7166   // for scalars so that we can more effectively fold with loads.
7167   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7168       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7169     V = V.getOperand(BroadcastIdx);
7170
7171     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7172     // Only AVX2 has register broadcasts.
7173     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7174       return SDValue();
7175   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7176     // We can't broadcast from a vector register without AVX2, and we can only
7177     // broadcast from the zero-element of a vector register.
7178     return SDValue();
7179   }
7180
7181   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7182 }
7183
7184 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7185 // INSERTPS when the V1 elements are already in the correct locations
7186 // because otherwise we can just always use two SHUFPS instructions which
7187 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7188 // perform INSERTPS if a single V1 element is out of place and all V2
7189 // elements are zeroable.
7190 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7191                                             ArrayRef<int> Mask,
7192                                             SelectionDAG &DAG) {
7193   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7194   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7195   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7196   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7197
7198   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7199
7200   unsigned ZMask = 0;
7201   int V1DstIndex = -1;
7202   int V2DstIndex = -1;
7203   bool V1UsedInPlace = false;
7204
7205   for (int i = 0; i < 4; ++i) {
7206     // Synthesize a zero mask from the zeroable elements (includes undefs).
7207     if (Zeroable[i]) {
7208       ZMask |= 1 << i;
7209       continue;
7210     }
7211
7212     // Flag if we use any V1 inputs in place.
7213     if (i == Mask[i]) {
7214       V1UsedInPlace = true;
7215       continue;
7216     }
7217
7218     // We can only insert a single non-zeroable element.
7219     if (V1DstIndex != -1 || V2DstIndex != -1)
7220       return SDValue();
7221
7222     if (Mask[i] < 4) {
7223       // V1 input out of place for insertion.
7224       V1DstIndex = i;
7225     } else {
7226       // V2 input for insertion.
7227       V2DstIndex = i;
7228     }
7229   }
7230
7231   // Don't bother if we have no (non-zeroable) element for insertion.
7232   if (V1DstIndex == -1 && V2DstIndex == -1)
7233     return SDValue();
7234
7235   // Determine element insertion src/dst indices. The src index is from the
7236   // start of the inserted vector, not the start of the concatenated vector.
7237   unsigned V2SrcIndex = 0;
7238   if (V1DstIndex != -1) {
7239     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7240     // and don't use the original V2 at all.
7241     V2SrcIndex = Mask[V1DstIndex];
7242     V2DstIndex = V1DstIndex;
7243     V2 = V1;
7244   } else {
7245     V2SrcIndex = Mask[V2DstIndex] - 4;
7246   }
7247
7248   // If no V1 inputs are used in place, then the result is created only from
7249   // the zero mask and the V2 insertion - so remove V1 dependency.
7250   if (!V1UsedInPlace)
7251     V1 = DAG.getUNDEF(MVT::v4f32);
7252
7253   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7254   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7255
7256   // Insert the V2 element into the desired position.
7257   SDLoc DL(Op);
7258   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7259                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7260 }
7261
7262 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7263 /// UNPCK instruction.
7264 ///
7265 /// This specifically targets cases where we end up with alternating between
7266 /// the two inputs, and so can permute them into something that feeds a single
7267 /// UNPCK instruction. Note that this routine only targets integer vectors
7268 /// because for floating point vectors we have a generalized SHUFPS lowering
7269 /// strategy that handles everything that doesn't *exactly* match an unpack,
7270 /// making this clever lowering unnecessary.
7271 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7272                                           SDValue V2, ArrayRef<int> Mask,
7273                                           SelectionDAG &DAG) {
7274   assert(!VT.isFloatingPoint() &&
7275          "This routine only supports integer vectors.");
7276   assert(!isSingleInputShuffleMask(Mask) &&
7277          "This routine should only be used when blending two inputs.");
7278   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7279
7280   int Size = Mask.size();
7281
7282   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7283     return M >= 0 && M % Size < Size / 2;
7284   });
7285   int NumHiInputs = std::count_if(
7286       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7287
7288   bool UnpackLo = NumLoInputs >= NumHiInputs;
7289
7290   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7291     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7292     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7293
7294     for (int i = 0; i < Size; ++i) {
7295       if (Mask[i] < 0)
7296         continue;
7297
7298       // Each element of the unpack contains Scale elements from this mask.
7299       int UnpackIdx = i / Scale;
7300
7301       // We only handle the case where V1 feeds the first slots of the unpack.
7302       // We rely on canonicalization to ensure this is the case.
7303       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7304         return SDValue();
7305
7306       // Setup the mask for this input. The indexing is tricky as we have to
7307       // handle the unpack stride.
7308       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7309       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7310           Mask[i] % Size;
7311     }
7312
7313     // If we will have to shuffle both inputs to use the unpack, check whether
7314     // we can just unpack first and shuffle the result. If so, skip this unpack.
7315     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7316         !isNoopShuffleMask(V2Mask))
7317       return SDValue();
7318
7319     // Shuffle the inputs into place.
7320     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7321     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7322
7323     // Cast the inputs to the type we will use to unpack them.
7324     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7325     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7326
7327     // Unpack the inputs and cast the result back to the desired type.
7328     return DAG.getNode(ISD::BITCAST, DL, VT,
7329                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7330                                    DL, UnpackVT, V1, V2));
7331   };
7332
7333   // We try each unpack from the largest to the smallest to try and find one
7334   // that fits this mask.
7335   int OrigNumElements = VT.getVectorNumElements();
7336   int OrigScalarSize = VT.getScalarSizeInBits();
7337   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7338     int Scale = ScalarSize / OrigScalarSize;
7339     int NumElements = OrigNumElements / Scale;
7340     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7341     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7342       return Unpack;
7343   }
7344
7345   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7346   // initial unpack.
7347   if (NumLoInputs == 0 || NumHiInputs == 0) {
7348     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7349            "We have to have *some* inputs!");
7350     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7351
7352     // FIXME: We could consider the total complexity of the permute of each
7353     // possible unpacking. Or at the least we should consider how many
7354     // half-crossings are created.
7355     // FIXME: We could consider commuting the unpacks.
7356
7357     SmallVector<int, 32> PermMask;
7358     PermMask.assign(Size, -1);
7359     for (int i = 0; i < Size; ++i) {
7360       if (Mask[i] < 0)
7361         continue;
7362
7363       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7364
7365       PermMask[i] =
7366           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7367     }
7368     return DAG.getVectorShuffle(
7369         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7370                             DL, VT, V1, V2),
7371         DAG.getUNDEF(VT), PermMask);
7372   }
7373
7374   return SDValue();
7375 }
7376
7377 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7378 ///
7379 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7380 /// support for floating point shuffles but not integer shuffles. These
7381 /// instructions will incur a domain crossing penalty on some chips though so
7382 /// it is better to avoid lowering through this for integer vectors where
7383 /// possible.
7384 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7385                                        const X86Subtarget *Subtarget,
7386                                        SelectionDAG &DAG) {
7387   SDLoc DL(Op);
7388   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7389   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7390   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7391   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7392   ArrayRef<int> Mask = SVOp->getMask();
7393   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7394
7395   if (isSingleInputShuffleMask(Mask)) {
7396     // Use low duplicate instructions for masks that match their pattern.
7397     if (Subtarget->hasSSE3())
7398       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7399         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7400
7401     // Straight shuffle of a single input vector. Simulate this by using the
7402     // single input as both of the "inputs" to this instruction..
7403     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7404
7405     if (Subtarget->hasAVX()) {
7406       // If we have AVX, we can use VPERMILPS which will allow folding a load
7407       // into the shuffle.
7408       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7409                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7410     }
7411
7412     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7413                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7414   }
7415   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7416   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7417
7418   // If we have a single input, insert that into V1 if we can do so cheaply.
7419   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7420     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7421             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7422       return Insertion;
7423     // Try inverting the insertion since for v2 masks it is easy to do and we
7424     // can't reliably sort the mask one way or the other.
7425     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7426                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7427     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7428             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7429       return Insertion;
7430   }
7431
7432   // Try to use one of the special instruction patterns to handle two common
7433   // blend patterns if a zero-blend above didn't work.
7434   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7435       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7436     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7437       // We can either use a special instruction to load over the low double or
7438       // to move just the low double.
7439       return DAG.getNode(
7440           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7441           DL, MVT::v2f64, V2,
7442           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7443
7444   if (Subtarget->hasSSE41())
7445     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7446                                                   Subtarget, DAG))
7447       return Blend;
7448
7449   // Use dedicated unpack instructions for masks that match their pattern.
7450   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7451     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7452   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7453     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7454
7455   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7456   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7457                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7458 }
7459
7460 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7461 ///
7462 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7463 /// the integer unit to minimize domain crossing penalties. However, for blends
7464 /// it falls back to the floating point shuffle operation with appropriate bit
7465 /// casting.
7466 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7467                                        const X86Subtarget *Subtarget,
7468                                        SelectionDAG &DAG) {
7469   SDLoc DL(Op);
7470   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7471   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7472   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7473   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7474   ArrayRef<int> Mask = SVOp->getMask();
7475   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7476
7477   if (isSingleInputShuffleMask(Mask)) {
7478     // Check for being able to broadcast a single element.
7479     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7480                                                           Mask, Subtarget, DAG))
7481       return Broadcast;
7482
7483     // Straight shuffle of a single input vector. For everything from SSE2
7484     // onward this has a single fast instruction with no scary immediates.
7485     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7486     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7487     int WidenedMask[4] = {
7488         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7489         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7490     return DAG.getNode(
7491         ISD::BITCAST, DL, MVT::v2i64,
7492         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7493                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7494   }
7495   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7496   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7497   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7498   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7499
7500   // If we have a blend of two PACKUS operations an the blend aligns with the
7501   // low and half halves, we can just merge the PACKUS operations. This is
7502   // particularly important as it lets us merge shuffles that this routine itself
7503   // creates.
7504   auto GetPackNode = [](SDValue V) {
7505     while (V.getOpcode() == ISD::BITCAST)
7506       V = V.getOperand(0);
7507
7508     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7509   };
7510   if (SDValue V1Pack = GetPackNode(V1))
7511     if (SDValue V2Pack = GetPackNode(V2))
7512       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7513                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7514                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7515                                                   : V1Pack.getOperand(1),
7516                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7517                                                   : V2Pack.getOperand(1)));
7518
7519   // Try to use shift instructions.
7520   if (SDValue Shift =
7521           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7522     return Shift;
7523
7524   // When loading a scalar and then shuffling it into a vector we can often do
7525   // the insertion cheaply.
7526   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7527           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7528     return Insertion;
7529   // Try inverting the insertion since for v2 masks it is easy to do and we
7530   // can't reliably sort the mask one way or the other.
7531   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7532   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7533           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7534     return Insertion;
7535
7536   // We have different paths for blend lowering, but they all must use the
7537   // *exact* same predicate.
7538   bool IsBlendSupported = Subtarget->hasSSE41();
7539   if (IsBlendSupported)
7540     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7541                                                   Subtarget, DAG))
7542       return Blend;
7543
7544   // Use dedicated unpack instructions for masks that match their pattern.
7545   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7546     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7547   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7548     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7549
7550   // Try to use byte rotation instructions.
7551   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7552   if (Subtarget->hasSSSE3())
7553     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7554             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7555       return Rotate;
7556
7557   // If we have direct support for blends, we should lower by decomposing into
7558   // a permute. That will be faster than the domain cross.
7559   if (IsBlendSupported)
7560     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7561                                                       Mask, DAG);
7562
7563   // We implement this with SHUFPD which is pretty lame because it will likely
7564   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7565   // However, all the alternatives are still more cycles and newer chips don't
7566   // have this problem. It would be really nice if x86 had better shuffles here.
7567   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7568   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7569   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7570                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7571 }
7572
7573 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7574 ///
7575 /// This is used to disable more specialized lowerings when the shufps lowering
7576 /// will happen to be efficient.
7577 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7578   // This routine only handles 128-bit shufps.
7579   assert(Mask.size() == 4 && "Unsupported mask size!");
7580
7581   // To lower with a single SHUFPS we need to have the low half and high half
7582   // each requiring a single input.
7583   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7584     return false;
7585   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7586     return false;
7587
7588   return true;
7589 }
7590
7591 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7592 ///
7593 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7594 /// It makes no assumptions about whether this is the *best* lowering, it simply
7595 /// uses it.
7596 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7597                                             ArrayRef<int> Mask, SDValue V1,
7598                                             SDValue V2, SelectionDAG &DAG) {
7599   SDValue LowV = V1, HighV = V2;
7600   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7601
7602   int NumV2Elements =
7603       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7604
7605   if (NumV2Elements == 1) {
7606     int V2Index =
7607         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7608         Mask.begin();
7609
7610     // Compute the index adjacent to V2Index and in the same half by toggling
7611     // the low bit.
7612     int V2AdjIndex = V2Index ^ 1;
7613
7614     if (Mask[V2AdjIndex] == -1) {
7615       // Handles all the cases where we have a single V2 element and an undef.
7616       // This will only ever happen in the high lanes because we commute the
7617       // vector otherwise.
7618       if (V2Index < 2)
7619         std::swap(LowV, HighV);
7620       NewMask[V2Index] -= 4;
7621     } else {
7622       // Handle the case where the V2 element ends up adjacent to a V1 element.
7623       // To make this work, blend them together as the first step.
7624       int V1Index = V2AdjIndex;
7625       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7626       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7627                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7628
7629       // Now proceed to reconstruct the final blend as we have the necessary
7630       // high or low half formed.
7631       if (V2Index < 2) {
7632         LowV = V2;
7633         HighV = V1;
7634       } else {
7635         HighV = V2;
7636       }
7637       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7638       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7639     }
7640   } else if (NumV2Elements == 2) {
7641     if (Mask[0] < 4 && Mask[1] < 4) {
7642       // Handle the easy case where we have V1 in the low lanes and V2 in the
7643       // high lanes.
7644       NewMask[2] -= 4;
7645       NewMask[3] -= 4;
7646     } else if (Mask[2] < 4 && Mask[3] < 4) {
7647       // We also handle the reversed case because this utility may get called
7648       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7649       // arrange things in the right direction.
7650       NewMask[0] -= 4;
7651       NewMask[1] -= 4;
7652       HighV = V1;
7653       LowV = V2;
7654     } else {
7655       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7656       // trying to place elements directly, just blend them and set up the final
7657       // shuffle to place them.
7658
7659       // The first two blend mask elements are for V1, the second two are for
7660       // V2.
7661       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7662                           Mask[2] < 4 ? Mask[2] : Mask[3],
7663                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7664                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7665       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7666                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7667
7668       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7669       // a blend.
7670       LowV = HighV = V1;
7671       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7672       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7673       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7674       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7675     }
7676   }
7677   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7678                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7679 }
7680
7681 /// \brief Lower 4-lane 32-bit floating point shuffles.
7682 ///
7683 /// Uses instructions exclusively from the floating point unit to minimize
7684 /// domain crossing penalties, as these are sufficient to implement all v4f32
7685 /// shuffles.
7686 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7687                                        const X86Subtarget *Subtarget,
7688                                        SelectionDAG &DAG) {
7689   SDLoc DL(Op);
7690   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7691   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7692   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7693   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7694   ArrayRef<int> Mask = SVOp->getMask();
7695   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7696
7697   int NumV2Elements =
7698       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7699
7700   if (NumV2Elements == 0) {
7701     // Check for being able to broadcast a single element.
7702     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7703                                                           Mask, Subtarget, DAG))
7704       return Broadcast;
7705
7706     // Use even/odd duplicate instructions for masks that match their pattern.
7707     if (Subtarget->hasSSE3()) {
7708       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7709         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7710       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7711         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7712     }
7713
7714     if (Subtarget->hasAVX()) {
7715       // If we have AVX, we can use VPERMILPS which will allow folding a load
7716       // into the shuffle.
7717       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7718                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7719     }
7720
7721     // Otherwise, use a straight shuffle of a single input vector. We pass the
7722     // input vector to both operands to simulate this with a SHUFPS.
7723     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7724                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7725   }
7726
7727   // There are special ways we can lower some single-element blends. However, we
7728   // have custom ways we can lower more complex single-element blends below that
7729   // we defer to if both this and BLENDPS fail to match, so restrict this to
7730   // when the V2 input is targeting element 0 of the mask -- that is the fast
7731   // case here.
7732   if (NumV2Elements == 1 && Mask[0] >= 4)
7733     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7734                                                          Mask, Subtarget, DAG))
7735       return V;
7736
7737   if (Subtarget->hasSSE41()) {
7738     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7739                                                   Subtarget, DAG))
7740       return Blend;
7741
7742     // Use INSERTPS if we can complete the shuffle efficiently.
7743     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7744       return V;
7745
7746     if (!isSingleSHUFPSMask(Mask))
7747       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7748               DL, MVT::v4f32, V1, V2, Mask, DAG))
7749         return BlendPerm;
7750   }
7751
7752   // Use dedicated unpack instructions for masks that match their pattern.
7753   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7754     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7755   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7756     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7757   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7758     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7759   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7760     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7761
7762   // Otherwise fall back to a SHUFPS lowering strategy.
7763   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7764 }
7765
7766 /// \brief Lower 4-lane i32 vector shuffles.
7767 ///
7768 /// We try to handle these with integer-domain shuffles where we can, but for
7769 /// blends we use the floating point domain blend instructions.
7770 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7771                                        const X86Subtarget *Subtarget,
7772                                        SelectionDAG &DAG) {
7773   SDLoc DL(Op);
7774   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7775   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7776   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7777   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7778   ArrayRef<int> Mask = SVOp->getMask();
7779   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7780
7781   // Whenever we can lower this as a zext, that instruction is strictly faster
7782   // than any alternative. It also allows us to fold memory operands into the
7783   // shuffle in many cases.
7784   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7785                                                          Mask, Subtarget, DAG))
7786     return ZExt;
7787
7788   int NumV2Elements =
7789       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7790
7791   if (NumV2Elements == 0) {
7792     // Check for being able to broadcast a single element.
7793     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7794                                                           Mask, Subtarget, DAG))
7795       return Broadcast;
7796
7797     // Straight shuffle of a single input vector. For everything from SSE2
7798     // onward this has a single fast instruction with no scary immediates.
7799     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7800     // but we aren't actually going to use the UNPCK instruction because doing
7801     // so prevents folding a load into this instruction or making a copy.
7802     const int UnpackLoMask[] = {0, 0, 1, 1};
7803     const int UnpackHiMask[] = {2, 2, 3, 3};
7804     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7805       Mask = UnpackLoMask;
7806     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7807       Mask = UnpackHiMask;
7808
7809     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7810                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7811   }
7812
7813   // Try to use shift instructions.
7814   if (SDValue Shift =
7815           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7816     return Shift;
7817
7818   // There are special ways we can lower some single-element blends.
7819   if (NumV2Elements == 1)
7820     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7821                                                          Mask, Subtarget, DAG))
7822       return V;
7823
7824   // We have different paths for blend lowering, but they all must use the
7825   // *exact* same predicate.
7826   bool IsBlendSupported = Subtarget->hasSSE41();
7827   if (IsBlendSupported)
7828     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7829                                                   Subtarget, DAG))
7830       return Blend;
7831
7832   if (SDValue Masked =
7833           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7834     return Masked;
7835
7836   // Use dedicated unpack instructions for masks that match their pattern.
7837   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7838     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7839   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7840     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7841   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7842     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7843   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7844     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7845
7846   // Try to use byte rotation instructions.
7847   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7848   if (Subtarget->hasSSSE3())
7849     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7850             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7851       return Rotate;
7852
7853   // If we have direct support for blends, we should lower by decomposing into
7854   // a permute. That will be faster than the domain cross.
7855   if (IsBlendSupported)
7856     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7857                                                       Mask, DAG);
7858
7859   // Try to lower by permuting the inputs into an unpack instruction.
7860   if (SDValue Unpack =
7861           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7862     return Unpack;
7863
7864   // We implement this with SHUFPS because it can blend from two vectors.
7865   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7866   // up the inputs, bypassing domain shift penalties that we would encur if we
7867   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7868   // relevant.
7869   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7870                      DAG.getVectorShuffle(
7871                          MVT::v4f32, DL,
7872                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7873                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7874 }
7875
7876 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7877 /// shuffle lowering, and the most complex part.
7878 ///
7879 /// The lowering strategy is to try to form pairs of input lanes which are
7880 /// targeted at the same half of the final vector, and then use a dword shuffle
7881 /// to place them onto the right half, and finally unpack the paired lanes into
7882 /// their final position.
7883 ///
7884 /// The exact breakdown of how to form these dword pairs and align them on the
7885 /// correct sides is really tricky. See the comments within the function for
7886 /// more of the details.
7887 ///
7888 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7889 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7890 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7891 /// vector, form the analogous 128-bit 8-element Mask.
7892 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7893     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7894     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7895   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7896   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7897
7898   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7899   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7900   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7901
7902   SmallVector<int, 4> LoInputs;
7903   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7904                [](int M) { return M >= 0; });
7905   std::sort(LoInputs.begin(), LoInputs.end());
7906   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7907   SmallVector<int, 4> HiInputs;
7908   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7909                [](int M) { return M >= 0; });
7910   std::sort(HiInputs.begin(), HiInputs.end());
7911   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7912   int NumLToL =
7913       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7914   int NumHToL = LoInputs.size() - NumLToL;
7915   int NumLToH =
7916       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7917   int NumHToH = HiInputs.size() - NumLToH;
7918   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7919   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7920   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7921   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7922
7923   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7924   // such inputs we can swap two of the dwords across the half mark and end up
7925   // with <=2 inputs to each half in each half. Once there, we can fall through
7926   // to the generic code below. For example:
7927   //
7928   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7929   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7930   //
7931   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7932   // and an existing 2-into-2 on the other half. In this case we may have to
7933   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7934   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7935   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7936   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7937   // half than the one we target for fixing) will be fixed when we re-enter this
7938   // path. We will also combine away any sequence of PSHUFD instructions that
7939   // result into a single instruction. Here is an example of the tricky case:
7940   //
7941   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7942   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7943   //
7944   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7945   //
7946   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7947   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7948   //
7949   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7950   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7951   //
7952   // The result is fine to be handled by the generic logic.
7953   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7954                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7955                           int AOffset, int BOffset) {
7956     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7957            "Must call this with A having 3 or 1 inputs from the A half.");
7958     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7959            "Must call this with B having 1 or 3 inputs from the B half.");
7960     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7961            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7962
7963     // Compute the index of dword with only one word among the three inputs in
7964     // a half by taking the sum of the half with three inputs and subtracting
7965     // the sum of the actual three inputs. The difference is the remaining
7966     // slot.
7967     int ADWord, BDWord;
7968     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7969     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7970     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7971     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7972     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7973     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7974     int TripleNonInputIdx =
7975         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7976     TripleDWord = TripleNonInputIdx / 2;
7977
7978     // We use xor with one to compute the adjacent DWord to whichever one the
7979     // OneInput is in.
7980     OneInputDWord = (OneInput / 2) ^ 1;
7981
7982     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7983     // and BToA inputs. If there is also such a problem with the BToB and AToB
7984     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7985     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7986     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7987     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7988       // Compute how many inputs will be flipped by swapping these DWords. We
7989       // need
7990       // to balance this to ensure we don't form a 3-1 shuffle in the other
7991       // half.
7992       int NumFlippedAToBInputs =
7993           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7994           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7995       int NumFlippedBToBInputs =
7996           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7997           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7998       if ((NumFlippedAToBInputs == 1 &&
7999            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8000           (NumFlippedBToBInputs == 1 &&
8001            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8002         // We choose whether to fix the A half or B half based on whether that
8003         // half has zero flipped inputs. At zero, we may not be able to fix it
8004         // with that half. We also bias towards fixing the B half because that
8005         // will more commonly be the high half, and we have to bias one way.
8006         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8007                                                        ArrayRef<int> Inputs) {
8008           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8009           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8010                                          PinnedIdx ^ 1) != Inputs.end();
8011           // Determine whether the free index is in the flipped dword or the
8012           // unflipped dword based on where the pinned index is. We use this bit
8013           // in an xor to conditionally select the adjacent dword.
8014           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8015           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8016                                              FixFreeIdx) != Inputs.end();
8017           if (IsFixIdxInput == IsFixFreeIdxInput)
8018             FixFreeIdx += 1;
8019           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8020                                         FixFreeIdx) != Inputs.end();
8021           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8022                  "We need to be changing the number of flipped inputs!");
8023           int PSHUFHalfMask[] = {0, 1, 2, 3};
8024           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8025           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8026                           MVT::v8i16, V,
8027                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8028
8029           for (int &M : Mask)
8030             if (M != -1 && M == FixIdx)
8031               M = FixFreeIdx;
8032             else if (M != -1 && M == FixFreeIdx)
8033               M = FixIdx;
8034         };
8035         if (NumFlippedBToBInputs != 0) {
8036           int BPinnedIdx =
8037               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8038           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8039         } else {
8040           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8041           int APinnedIdx =
8042               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8043           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8044         }
8045       }
8046     }
8047
8048     int PSHUFDMask[] = {0, 1, 2, 3};
8049     PSHUFDMask[ADWord] = BDWord;
8050     PSHUFDMask[BDWord] = ADWord;
8051     V = DAG.getNode(ISD::BITCAST, DL, VT,
8052                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8053                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8054                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8055                                                            DAG)));
8056
8057     // Adjust the mask to match the new locations of A and B.
8058     for (int &M : Mask)
8059       if (M != -1 && M/2 == ADWord)
8060         M = 2 * BDWord + M % 2;
8061       else if (M != -1 && M/2 == BDWord)
8062         M = 2 * ADWord + M % 2;
8063
8064     // Recurse back into this routine to re-compute state now that this isn't
8065     // a 3 and 1 problem.
8066     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8067                                                      DAG);
8068   };
8069   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8070     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8071   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8072     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8073
8074   // At this point there are at most two inputs to the low and high halves from
8075   // each half. That means the inputs can always be grouped into dwords and
8076   // those dwords can then be moved to the correct half with a dword shuffle.
8077   // We use at most one low and one high word shuffle to collect these paired
8078   // inputs into dwords, and finally a dword shuffle to place them.
8079   int PSHUFLMask[4] = {-1, -1, -1, -1};
8080   int PSHUFHMask[4] = {-1, -1, -1, -1};
8081   int PSHUFDMask[4] = {-1, -1, -1, -1};
8082
8083   // First fix the masks for all the inputs that are staying in their
8084   // original halves. This will then dictate the targets of the cross-half
8085   // shuffles.
8086   auto fixInPlaceInputs =
8087       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8088                     MutableArrayRef<int> SourceHalfMask,
8089                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8090     if (InPlaceInputs.empty())
8091       return;
8092     if (InPlaceInputs.size() == 1) {
8093       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8094           InPlaceInputs[0] - HalfOffset;
8095       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8096       return;
8097     }
8098     if (IncomingInputs.empty()) {
8099       // Just fix all of the in place inputs.
8100       for (int Input : InPlaceInputs) {
8101         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8102         PSHUFDMask[Input / 2] = Input / 2;
8103       }
8104       return;
8105     }
8106
8107     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8108     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8109         InPlaceInputs[0] - HalfOffset;
8110     // Put the second input next to the first so that they are packed into
8111     // a dword. We find the adjacent index by toggling the low bit.
8112     int AdjIndex = InPlaceInputs[0] ^ 1;
8113     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8114     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8115     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8116   };
8117   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8118   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8119
8120   // Now gather the cross-half inputs and place them into a free dword of
8121   // their target half.
8122   // FIXME: This operation could almost certainly be simplified dramatically to
8123   // look more like the 3-1 fixing operation.
8124   auto moveInputsToRightHalf = [&PSHUFDMask](
8125       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8126       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8127       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8128       int DestOffset) {
8129     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8130       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8131     };
8132     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8133                                                int Word) {
8134       int LowWord = Word & ~1;
8135       int HighWord = Word | 1;
8136       return isWordClobbered(SourceHalfMask, LowWord) ||
8137              isWordClobbered(SourceHalfMask, HighWord);
8138     };
8139
8140     if (IncomingInputs.empty())
8141       return;
8142
8143     if (ExistingInputs.empty()) {
8144       // Map any dwords with inputs from them into the right half.
8145       for (int Input : IncomingInputs) {
8146         // If the source half mask maps over the inputs, turn those into
8147         // swaps and use the swapped lane.
8148         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8149           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8150             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8151                 Input - SourceOffset;
8152             // We have to swap the uses in our half mask in one sweep.
8153             for (int &M : HalfMask)
8154               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8155                 M = Input;
8156               else if (M == Input)
8157                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8158           } else {
8159             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8160                        Input - SourceOffset &&
8161                    "Previous placement doesn't match!");
8162           }
8163           // Note that this correctly re-maps both when we do a swap and when
8164           // we observe the other side of the swap above. We rely on that to
8165           // avoid swapping the members of the input list directly.
8166           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8167         }
8168
8169         // Map the input's dword into the correct half.
8170         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8171           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8172         else
8173           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8174                      Input / 2 &&
8175                  "Previous placement doesn't match!");
8176       }
8177
8178       // And just directly shift any other-half mask elements to be same-half
8179       // as we will have mirrored the dword containing the element into the
8180       // same position within that half.
8181       for (int &M : HalfMask)
8182         if (M >= SourceOffset && M < SourceOffset + 4) {
8183           M = M - SourceOffset + DestOffset;
8184           assert(M >= 0 && "This should never wrap below zero!");
8185         }
8186       return;
8187     }
8188
8189     // Ensure we have the input in a viable dword of its current half. This
8190     // is particularly tricky because the original position may be clobbered
8191     // by inputs being moved and *staying* in that half.
8192     if (IncomingInputs.size() == 1) {
8193       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8194         int InputFixed = std::find(std::begin(SourceHalfMask),
8195                                    std::end(SourceHalfMask), -1) -
8196                          std::begin(SourceHalfMask) + SourceOffset;
8197         SourceHalfMask[InputFixed - SourceOffset] =
8198             IncomingInputs[0] - SourceOffset;
8199         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8200                      InputFixed);
8201         IncomingInputs[0] = InputFixed;
8202       }
8203     } else if (IncomingInputs.size() == 2) {
8204       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8205           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8206         // We have two non-adjacent or clobbered inputs we need to extract from
8207         // the source half. To do this, we need to map them into some adjacent
8208         // dword slot in the source mask.
8209         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8210                               IncomingInputs[1] - SourceOffset};
8211
8212         // If there is a free slot in the source half mask adjacent to one of
8213         // the inputs, place the other input in it. We use (Index XOR 1) to
8214         // compute an adjacent index.
8215         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8216             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8217           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8218           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8219           InputsFixed[1] = InputsFixed[0] ^ 1;
8220         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8221                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8222           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8223           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8224           InputsFixed[0] = InputsFixed[1] ^ 1;
8225         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8226                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8227           // The two inputs are in the same DWord but it is clobbered and the
8228           // adjacent DWord isn't used at all. Move both inputs to the free
8229           // slot.
8230           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8231           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8232           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8233           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8234         } else {
8235           // The only way we hit this point is if there is no clobbering
8236           // (because there are no off-half inputs to this half) and there is no
8237           // free slot adjacent to one of the inputs. In this case, we have to
8238           // swap an input with a non-input.
8239           for (int i = 0; i < 4; ++i)
8240             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8241                    "We can't handle any clobbers here!");
8242           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8243                  "Cannot have adjacent inputs here!");
8244
8245           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8246           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8247
8248           // We also have to update the final source mask in this case because
8249           // it may need to undo the above swap.
8250           for (int &M : FinalSourceHalfMask)
8251             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8252               M = InputsFixed[1] + SourceOffset;
8253             else if (M == InputsFixed[1] + SourceOffset)
8254               M = (InputsFixed[0] ^ 1) + SourceOffset;
8255
8256           InputsFixed[1] = InputsFixed[0] ^ 1;
8257         }
8258
8259         // Point everything at the fixed inputs.
8260         for (int &M : HalfMask)
8261           if (M == IncomingInputs[0])
8262             M = InputsFixed[0] + SourceOffset;
8263           else if (M == IncomingInputs[1])
8264             M = InputsFixed[1] + SourceOffset;
8265
8266         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8267         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8268       }
8269     } else {
8270       llvm_unreachable("Unhandled input size!");
8271     }
8272
8273     // Now hoist the DWord down to the right half.
8274     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8275     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8276     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8277     for (int &M : HalfMask)
8278       for (int Input : IncomingInputs)
8279         if (M == Input)
8280           M = FreeDWord * 2 + Input % 2;
8281   };
8282   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8283                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8284   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8285                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8286
8287   // Now enact all the shuffles we've computed to move the inputs into their
8288   // target half.
8289   if (!isNoopShuffleMask(PSHUFLMask))
8290     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8291                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8292   if (!isNoopShuffleMask(PSHUFHMask))
8293     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8294                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8295   if (!isNoopShuffleMask(PSHUFDMask))
8296     V = DAG.getNode(ISD::BITCAST, DL, VT,
8297                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8298                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8299                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8300                                                            DAG)));
8301
8302   // At this point, each half should contain all its inputs, and we can then
8303   // just shuffle them into their final position.
8304   assert(std::count_if(LoMask.begin(), LoMask.end(),
8305                        [](int M) { return M >= 4; }) == 0 &&
8306          "Failed to lift all the high half inputs to the low mask!");
8307   assert(std::count_if(HiMask.begin(), HiMask.end(),
8308                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8309          "Failed to lift all the low half inputs to the high mask!");
8310
8311   // Do a half shuffle for the low mask.
8312   if (!isNoopShuffleMask(LoMask))
8313     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8314                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8315
8316   // Do a half shuffle with the high mask after shifting its values down.
8317   for (int &M : HiMask)
8318     if (M >= 0)
8319       M -= 4;
8320   if (!isNoopShuffleMask(HiMask))
8321     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8322                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8323
8324   return V;
8325 }
8326
8327 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8328 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8329                                           SDValue V2, ArrayRef<int> Mask,
8330                                           SelectionDAG &DAG, bool &V1InUse,
8331                                           bool &V2InUse) {
8332   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8333   SDValue V1Mask[16];
8334   SDValue V2Mask[16];
8335   V1InUse = false;
8336   V2InUse = false;
8337
8338   int Size = Mask.size();
8339   int Scale = 16 / Size;
8340   for (int i = 0; i < 16; ++i) {
8341     if (Mask[i / Scale] == -1) {
8342       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8343     } else {
8344       const int ZeroMask = 0x80;
8345       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8346                                           : ZeroMask;
8347       int V2Idx = Mask[i / Scale] < Size
8348                       ? ZeroMask
8349                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8350       if (Zeroable[i / Scale])
8351         V1Idx = V2Idx = ZeroMask;
8352       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8353       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8354       V1InUse |= (ZeroMask != V1Idx);
8355       V2InUse |= (ZeroMask != V2Idx);
8356     }
8357   }
8358
8359   if (V1InUse)
8360     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8361                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8362                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8363   if (V2InUse)
8364     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8365                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8366                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8367
8368   // If we need shuffled inputs from both, blend the two.
8369   SDValue V;
8370   if (V1InUse && V2InUse)
8371     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8372   else
8373     V = V1InUse ? V1 : V2;
8374
8375   // Cast the result back to the correct type.
8376   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8377 }
8378
8379 /// \brief Generic lowering of 8-lane i16 shuffles.
8380 ///
8381 /// This handles both single-input shuffles and combined shuffle/blends with
8382 /// two inputs. The single input shuffles are immediately delegated to
8383 /// a dedicated lowering routine.
8384 ///
8385 /// The blends are lowered in one of three fundamental ways. If there are few
8386 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8387 /// of the input is significantly cheaper when lowered as an interleaving of
8388 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8389 /// halves of the inputs separately (making them have relatively few inputs)
8390 /// and then concatenate them.
8391 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8392                                        const X86Subtarget *Subtarget,
8393                                        SelectionDAG &DAG) {
8394   SDLoc DL(Op);
8395   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8396   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8397   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8398   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8399   ArrayRef<int> OrigMask = SVOp->getMask();
8400   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8401                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8402   MutableArrayRef<int> Mask(MaskStorage);
8403
8404   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8405
8406   // Whenever we can lower this as a zext, that instruction is strictly faster
8407   // than any alternative.
8408   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8409           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8410     return ZExt;
8411
8412   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8413   (void)isV1;
8414   auto isV2 = [](int M) { return M >= 8; };
8415
8416   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8417
8418   if (NumV2Inputs == 0) {
8419     // Check for being able to broadcast a single element.
8420     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8421                                                           Mask, Subtarget, DAG))
8422       return Broadcast;
8423
8424     // Try to use shift instructions.
8425     if (SDValue Shift =
8426             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8427       return Shift;
8428
8429     // Use dedicated unpack instructions for masks that match their pattern.
8430     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8431       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8432     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8433       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8434
8435     // Try to use byte rotation instructions.
8436     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8437                                                         Mask, Subtarget, DAG))
8438       return Rotate;
8439
8440     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8441                                                      Subtarget, DAG);
8442   }
8443
8444   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8445          "All single-input shuffles should be canonicalized to be V1-input "
8446          "shuffles.");
8447
8448   // Try to use shift instructions.
8449   if (SDValue Shift =
8450           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8451     return Shift;
8452
8453   // There are special ways we can lower some single-element blends.
8454   if (NumV2Inputs == 1)
8455     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8456                                                          Mask, Subtarget, DAG))
8457       return V;
8458
8459   // We have different paths for blend lowering, but they all must use the
8460   // *exact* same predicate.
8461   bool IsBlendSupported = Subtarget->hasSSE41();
8462   if (IsBlendSupported)
8463     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8464                                                   Subtarget, DAG))
8465       return Blend;
8466
8467   if (SDValue Masked =
8468           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8469     return Masked;
8470
8471   // Use dedicated unpack instructions for masks that match their pattern.
8472   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8473     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8474   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8475     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8476
8477   // Try to use byte rotation instructions.
8478   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8479           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8480     return Rotate;
8481
8482   if (SDValue BitBlend =
8483           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8484     return BitBlend;
8485
8486   if (SDValue Unpack =
8487           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8488     return Unpack;
8489
8490   // If we can't directly blend but can use PSHUFB, that will be better as it
8491   // can both shuffle and set up the inefficient blend.
8492   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8493     bool V1InUse, V2InUse;
8494     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8495                                       V1InUse, V2InUse);
8496   }
8497
8498   // We can always bit-blend if we have to so the fallback strategy is to
8499   // decompose into single-input permutes and blends.
8500   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8501                                                       Mask, DAG);
8502 }
8503
8504 /// \brief Check whether a compaction lowering can be done by dropping even
8505 /// elements and compute how many times even elements must be dropped.
8506 ///
8507 /// This handles shuffles which take every Nth element where N is a power of
8508 /// two. Example shuffle masks:
8509 ///
8510 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8511 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8512 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8513 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8514 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8515 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8516 ///
8517 /// Any of these lanes can of course be undef.
8518 ///
8519 /// This routine only supports N <= 3.
8520 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8521 /// for larger N.
8522 ///
8523 /// \returns N above, or the number of times even elements must be dropped if
8524 /// there is such a number. Otherwise returns zero.
8525 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8526   // Figure out whether we're looping over two inputs or just one.
8527   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8528
8529   // The modulus for the shuffle vector entries is based on whether this is
8530   // a single input or not.
8531   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8532   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8533          "We should only be called with masks with a power-of-2 size!");
8534
8535   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8536
8537   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8538   // and 2^3 simultaneously. This is because we may have ambiguity with
8539   // partially undef inputs.
8540   bool ViableForN[3] = {true, true, true};
8541
8542   for (int i = 0, e = Mask.size(); i < e; ++i) {
8543     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8544     // want.
8545     if (Mask[i] == -1)
8546       continue;
8547
8548     bool IsAnyViable = false;
8549     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8550       if (ViableForN[j]) {
8551         uint64_t N = j + 1;
8552
8553         // The shuffle mask must be equal to (i * 2^N) % M.
8554         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8555           IsAnyViable = true;
8556         else
8557           ViableForN[j] = false;
8558       }
8559     // Early exit if we exhaust the possible powers of two.
8560     if (!IsAnyViable)
8561       break;
8562   }
8563
8564   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8565     if (ViableForN[j])
8566       return j + 1;
8567
8568   // Return 0 as there is no viable power of two.
8569   return 0;
8570 }
8571
8572 /// \brief Generic lowering of v16i8 shuffles.
8573 ///
8574 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8575 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8576 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8577 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8578 /// back together.
8579 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8580                                        const X86Subtarget *Subtarget,
8581                                        SelectionDAG &DAG) {
8582   SDLoc DL(Op);
8583   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8584   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8585   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8586   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8587   ArrayRef<int> Mask = SVOp->getMask();
8588   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8589
8590   // Try to use shift instructions.
8591   if (SDValue Shift =
8592           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8593     return Shift;
8594
8595   // Try to use byte rotation instructions.
8596   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8597           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8598     return Rotate;
8599
8600   // Try to use a zext lowering.
8601   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8602           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8603     return ZExt;
8604
8605   int NumV2Elements =
8606       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8607
8608   // For single-input shuffles, there are some nicer lowering tricks we can use.
8609   if (NumV2Elements == 0) {
8610     // Check for being able to broadcast a single element.
8611     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8612                                                           Mask, Subtarget, DAG))
8613       return Broadcast;
8614
8615     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8616     // Notably, this handles splat and partial-splat shuffles more efficiently.
8617     // However, it only makes sense if the pre-duplication shuffle simplifies
8618     // things significantly. Currently, this means we need to be able to
8619     // express the pre-duplication shuffle as an i16 shuffle.
8620     //
8621     // FIXME: We should check for other patterns which can be widened into an
8622     // i16 shuffle as well.
8623     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8624       for (int i = 0; i < 16; i += 2)
8625         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8626           return false;
8627
8628       return true;
8629     };
8630     auto tryToWidenViaDuplication = [&]() -> SDValue {
8631       if (!canWidenViaDuplication(Mask))
8632         return SDValue();
8633       SmallVector<int, 4> LoInputs;
8634       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8635                    [](int M) { return M >= 0 && M < 8; });
8636       std::sort(LoInputs.begin(), LoInputs.end());
8637       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8638                      LoInputs.end());
8639       SmallVector<int, 4> HiInputs;
8640       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8641                    [](int M) { return M >= 8; });
8642       std::sort(HiInputs.begin(), HiInputs.end());
8643       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8644                      HiInputs.end());
8645
8646       bool TargetLo = LoInputs.size() >= HiInputs.size();
8647       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8648       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8649
8650       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8651       SmallDenseMap<int, int, 8> LaneMap;
8652       for (int I : InPlaceInputs) {
8653         PreDupI16Shuffle[I/2] = I/2;
8654         LaneMap[I] = I;
8655       }
8656       int j = TargetLo ? 0 : 4, je = j + 4;
8657       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8658         // Check if j is already a shuffle of this input. This happens when
8659         // there are two adjacent bytes after we move the low one.
8660         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8661           // If we haven't yet mapped the input, search for a slot into which
8662           // we can map it.
8663           while (j < je && PreDupI16Shuffle[j] != -1)
8664             ++j;
8665
8666           if (j == je)
8667             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8668             return SDValue();
8669
8670           // Map this input with the i16 shuffle.
8671           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8672         }
8673
8674         // Update the lane map based on the mapping we ended up with.
8675         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8676       }
8677       V1 = DAG.getNode(
8678           ISD::BITCAST, DL, MVT::v16i8,
8679           DAG.getVectorShuffle(MVT::v8i16, DL,
8680                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8681                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8682
8683       // Unpack the bytes to form the i16s that will be shuffled into place.
8684       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8685                        MVT::v16i8, V1, V1);
8686
8687       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8688       for (int i = 0; i < 16; ++i)
8689         if (Mask[i] != -1) {
8690           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8691           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8692           if (PostDupI16Shuffle[i / 2] == -1)
8693             PostDupI16Shuffle[i / 2] = MappedMask;
8694           else
8695             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8696                    "Conflicting entrties in the original shuffle!");
8697         }
8698       return DAG.getNode(
8699           ISD::BITCAST, DL, MVT::v16i8,
8700           DAG.getVectorShuffle(MVT::v8i16, DL,
8701                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8702                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8703     };
8704     if (SDValue V = tryToWidenViaDuplication())
8705       return V;
8706   }
8707
8708   // Use dedicated unpack instructions for masks that match their pattern.
8709   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8710                                          0, 16, 1, 17, 2, 18, 3, 19,
8711                                          // High half.
8712                                          4, 20, 5, 21, 6, 22, 7, 23}))
8713     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8714   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8715                                          8, 24, 9, 25, 10, 26, 11, 27,
8716                                          // High half.
8717                                          12, 28, 13, 29, 14, 30, 15, 31}))
8718     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8719
8720   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8721   // with PSHUFB. It is important to do this before we attempt to generate any
8722   // blends but after all of the single-input lowerings. If the single input
8723   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8724   // want to preserve that and we can DAG combine any longer sequences into
8725   // a PSHUFB in the end. But once we start blending from multiple inputs,
8726   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8727   // and there are *very* few patterns that would actually be faster than the
8728   // PSHUFB approach because of its ability to zero lanes.
8729   //
8730   // FIXME: The only exceptions to the above are blends which are exact
8731   // interleavings with direct instructions supporting them. We currently don't
8732   // handle those well here.
8733   if (Subtarget->hasSSSE3()) {
8734     bool V1InUse = false;
8735     bool V2InUse = false;
8736
8737     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8738                                                 DAG, V1InUse, V2InUse);
8739
8740     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8741     // do so. This avoids using them to handle blends-with-zero which is
8742     // important as a single pshufb is significantly faster for that.
8743     if (V1InUse && V2InUse) {
8744       if (Subtarget->hasSSE41())
8745         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8746                                                       Mask, Subtarget, DAG))
8747           return Blend;
8748
8749       // We can use an unpack to do the blending rather than an or in some
8750       // cases. Even though the or may be (very minorly) more efficient, we
8751       // preference this lowering because there are common cases where part of
8752       // the complexity of the shuffles goes away when we do the final blend as
8753       // an unpack.
8754       // FIXME: It might be worth trying to detect if the unpack-feeding
8755       // shuffles will both be pshufb, in which case we shouldn't bother with
8756       // this.
8757       if (SDValue Unpack =
8758               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8759         return Unpack;
8760     }
8761
8762     return PSHUFB;
8763   }
8764
8765   // There are special ways we can lower some single-element blends.
8766   if (NumV2Elements == 1)
8767     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8768                                                          Mask, Subtarget, DAG))
8769       return V;
8770
8771   if (SDValue BitBlend =
8772           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8773     return BitBlend;
8774
8775   // Check whether a compaction lowering can be done. This handles shuffles
8776   // which take every Nth element for some even N. See the helper function for
8777   // details.
8778   //
8779   // We special case these as they can be particularly efficiently handled with
8780   // the PACKUSB instruction on x86 and they show up in common patterns of
8781   // rearranging bytes to truncate wide elements.
8782   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8783     // NumEvenDrops is the power of two stride of the elements. Another way of
8784     // thinking about it is that we need to drop the even elements this many
8785     // times to get the original input.
8786     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8787
8788     // First we need to zero all the dropped bytes.
8789     assert(NumEvenDrops <= 3 &&
8790            "No support for dropping even elements more than 3 times.");
8791     // We use the mask type to pick which bytes are preserved based on how many
8792     // elements are dropped.
8793     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8794     SDValue ByteClearMask =
8795         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8796                     DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8797     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8798     if (!IsSingleInput)
8799       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8800
8801     // Now pack things back together.
8802     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8803     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8804     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8805     for (int i = 1; i < NumEvenDrops; ++i) {
8806       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8807       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8808     }
8809
8810     return Result;
8811   }
8812
8813   // Handle multi-input cases by blending single-input shuffles.
8814   if (NumV2Elements > 0)
8815     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8816                                                       Mask, DAG);
8817
8818   // The fallback path for single-input shuffles widens this into two v8i16
8819   // vectors with unpacks, shuffles those, and then pulls them back together
8820   // with a pack.
8821   SDValue V = V1;
8822
8823   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8824   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8825   for (int i = 0; i < 16; ++i)
8826     if (Mask[i] >= 0)
8827       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8828
8829   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8830
8831   SDValue VLoHalf, VHiHalf;
8832   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8833   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8834   // i16s.
8835   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8836                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8837       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8838                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8839     // Use a mask to drop the high bytes.
8840     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8841     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8842                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8843
8844     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8845     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8846
8847     // Squash the masks to point directly into VLoHalf.
8848     for (int &M : LoBlendMask)
8849       if (M >= 0)
8850         M /= 2;
8851     for (int &M : HiBlendMask)
8852       if (M >= 0)
8853         M /= 2;
8854   } else {
8855     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8856     // VHiHalf so that we can blend them as i16s.
8857     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8858                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8859     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8860                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8861   }
8862
8863   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8864   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8865
8866   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8867 }
8868
8869 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8870 ///
8871 /// This routine breaks down the specific type of 128-bit shuffle and
8872 /// dispatches to the lowering routines accordingly.
8873 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8874                                         MVT VT, const X86Subtarget *Subtarget,
8875                                         SelectionDAG &DAG) {
8876   switch (VT.SimpleTy) {
8877   case MVT::v2i64:
8878     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8879   case MVT::v2f64:
8880     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8881   case MVT::v4i32:
8882     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8883   case MVT::v4f32:
8884     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8885   case MVT::v8i16:
8886     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8887   case MVT::v16i8:
8888     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8889
8890   default:
8891     llvm_unreachable("Unimplemented!");
8892   }
8893 }
8894
8895 /// \brief Helper function to test whether a shuffle mask could be
8896 /// simplified by widening the elements being shuffled.
8897 ///
8898 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8899 /// leaves it in an unspecified state.
8900 ///
8901 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8902 /// shuffle masks. The latter have the special property of a '-2' representing
8903 /// a zero-ed lane of a vector.
8904 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8905                                     SmallVectorImpl<int> &WidenedMask) {
8906   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8907     // If both elements are undef, its trivial.
8908     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8909       WidenedMask.push_back(SM_SentinelUndef);
8910       continue;
8911     }
8912
8913     // Check for an undef mask and a mask value properly aligned to fit with
8914     // a pair of values. If we find such a case, use the non-undef mask's value.
8915     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8916       WidenedMask.push_back(Mask[i + 1] / 2);
8917       continue;
8918     }
8919     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8920       WidenedMask.push_back(Mask[i] / 2);
8921       continue;
8922     }
8923
8924     // When zeroing, we need to spread the zeroing across both lanes to widen.
8925     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8926       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8927           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8928         WidenedMask.push_back(SM_SentinelZero);
8929         continue;
8930       }
8931       return false;
8932     }
8933
8934     // Finally check if the two mask values are adjacent and aligned with
8935     // a pair.
8936     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8937       WidenedMask.push_back(Mask[i] / 2);
8938       continue;
8939     }
8940
8941     // Otherwise we can't safely widen the elements used in this shuffle.
8942     return false;
8943   }
8944   assert(WidenedMask.size() == Mask.size() / 2 &&
8945          "Incorrect size of mask after widening the elements!");
8946
8947   return true;
8948 }
8949
8950 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8951 ///
8952 /// This routine just extracts two subvectors, shuffles them independently, and
8953 /// then concatenates them back together. This should work effectively with all
8954 /// AVX vector shuffle types.
8955 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8956                                           SDValue V2, ArrayRef<int> Mask,
8957                                           SelectionDAG &DAG) {
8958   assert(VT.getSizeInBits() >= 256 &&
8959          "Only for 256-bit or wider vector shuffles!");
8960   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8961   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8962
8963   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8964   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8965
8966   int NumElements = VT.getVectorNumElements();
8967   int SplitNumElements = NumElements / 2;
8968   MVT ScalarVT = VT.getScalarType();
8969   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8970
8971   // Rather than splitting build-vectors, just build two narrower build
8972   // vectors. This helps shuffling with splats and zeros.
8973   auto SplitVector = [&](SDValue V) {
8974     while (V.getOpcode() == ISD::BITCAST)
8975       V = V->getOperand(0);
8976
8977     MVT OrigVT = V.getSimpleValueType();
8978     int OrigNumElements = OrigVT.getVectorNumElements();
8979     int OrigSplitNumElements = OrigNumElements / 2;
8980     MVT OrigScalarVT = OrigVT.getScalarType();
8981     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8982
8983     SDValue LoV, HiV;
8984
8985     auto *BV = dyn_cast<BuildVectorSDNode>(V);
8986     if (!BV) {
8987       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8988                         DAG.getIntPtrConstant(0, DL));
8989       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8990                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
8991     } else {
8992
8993       SmallVector<SDValue, 16> LoOps, HiOps;
8994       for (int i = 0; i < OrigSplitNumElements; ++i) {
8995         LoOps.push_back(BV->getOperand(i));
8996         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8997       }
8998       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8999       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9000     }
9001     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9002                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9003   };
9004
9005   SDValue LoV1, HiV1, LoV2, HiV2;
9006   std::tie(LoV1, HiV1) = SplitVector(V1);
9007   std::tie(LoV2, HiV2) = SplitVector(V2);
9008
9009   // Now create two 4-way blends of these half-width vectors.
9010   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9011     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9012     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9013     for (int i = 0; i < SplitNumElements; ++i) {
9014       int M = HalfMask[i];
9015       if (M >= NumElements) {
9016         if (M >= NumElements + SplitNumElements)
9017           UseHiV2 = true;
9018         else
9019           UseLoV2 = true;
9020         V2BlendMask.push_back(M - NumElements);
9021         V1BlendMask.push_back(-1);
9022         BlendMask.push_back(SplitNumElements + i);
9023       } else if (M >= 0) {
9024         if (M >= SplitNumElements)
9025           UseHiV1 = true;
9026         else
9027           UseLoV1 = true;
9028         V2BlendMask.push_back(-1);
9029         V1BlendMask.push_back(M);
9030         BlendMask.push_back(i);
9031       } else {
9032         V2BlendMask.push_back(-1);
9033         V1BlendMask.push_back(-1);
9034         BlendMask.push_back(-1);
9035       }
9036     }
9037
9038     // Because the lowering happens after all combining takes place, we need to
9039     // manually combine these blend masks as much as possible so that we create
9040     // a minimal number of high-level vector shuffle nodes.
9041
9042     // First try just blending the halves of V1 or V2.
9043     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9044       return DAG.getUNDEF(SplitVT);
9045     if (!UseLoV2 && !UseHiV2)
9046       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9047     if (!UseLoV1 && !UseHiV1)
9048       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9049
9050     SDValue V1Blend, V2Blend;
9051     if (UseLoV1 && UseHiV1) {
9052       V1Blend =
9053         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9054     } else {
9055       // We only use half of V1 so map the usage down into the final blend mask.
9056       V1Blend = UseLoV1 ? LoV1 : HiV1;
9057       for (int i = 0; i < SplitNumElements; ++i)
9058         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9059           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9060     }
9061     if (UseLoV2 && UseHiV2) {
9062       V2Blend =
9063         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9064     } else {
9065       // We only use half of V2 so map the usage down into the final blend mask.
9066       V2Blend = UseLoV2 ? LoV2 : HiV2;
9067       for (int i = 0; i < SplitNumElements; ++i)
9068         if (BlendMask[i] >= SplitNumElements)
9069           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9070     }
9071     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9072   };
9073   SDValue Lo = HalfBlend(LoMask);
9074   SDValue Hi = HalfBlend(HiMask);
9075   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9076 }
9077
9078 /// \brief Either split a vector in halves or decompose the shuffles and the
9079 /// blend.
9080 ///
9081 /// This is provided as a good fallback for many lowerings of non-single-input
9082 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9083 /// between splitting the shuffle into 128-bit components and stitching those
9084 /// back together vs. extracting the single-input shuffles and blending those
9085 /// results.
9086 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9087                                                 SDValue V2, ArrayRef<int> Mask,
9088                                                 SelectionDAG &DAG) {
9089   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9090                                             "lower single-input shuffles as it "
9091                                             "could then recurse on itself.");
9092   int Size = Mask.size();
9093
9094   // If this can be modeled as a broadcast of two elements followed by a blend,
9095   // prefer that lowering. This is especially important because broadcasts can
9096   // often fold with memory operands.
9097   auto DoBothBroadcast = [&] {
9098     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9099     for (int M : Mask)
9100       if (M >= Size) {
9101         if (V2BroadcastIdx == -1)
9102           V2BroadcastIdx = M - Size;
9103         else if (M - Size != V2BroadcastIdx)
9104           return false;
9105       } else if (M >= 0) {
9106         if (V1BroadcastIdx == -1)
9107           V1BroadcastIdx = M;
9108         else if (M != V1BroadcastIdx)
9109           return false;
9110       }
9111     return true;
9112   };
9113   if (DoBothBroadcast())
9114     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9115                                                       DAG);
9116
9117   // If the inputs all stem from a single 128-bit lane of each input, then we
9118   // split them rather than blending because the split will decompose to
9119   // unusually few instructions.
9120   int LaneCount = VT.getSizeInBits() / 128;
9121   int LaneSize = Size / LaneCount;
9122   SmallBitVector LaneInputs[2];
9123   LaneInputs[0].resize(LaneCount, false);
9124   LaneInputs[1].resize(LaneCount, false);
9125   for (int i = 0; i < Size; ++i)
9126     if (Mask[i] >= 0)
9127       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9128   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9129     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9130
9131   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9132   // that the decomposed single-input shuffles don't end up here.
9133   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9134 }
9135
9136 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9137 /// a permutation and blend of those lanes.
9138 ///
9139 /// This essentially blends the out-of-lane inputs to each lane into the lane
9140 /// from a permuted copy of the vector. This lowering strategy results in four
9141 /// instructions in the worst case for a single-input cross lane shuffle which
9142 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9143 /// of. Special cases for each particular shuffle pattern should be handled
9144 /// prior to trying this lowering.
9145 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9146                                                        SDValue V1, SDValue V2,
9147                                                        ArrayRef<int> Mask,
9148                                                        SelectionDAG &DAG) {
9149   // FIXME: This should probably be generalized for 512-bit vectors as well.
9150   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9151   int LaneSize = Mask.size() / 2;
9152
9153   // If there are only inputs from one 128-bit lane, splitting will in fact be
9154   // less expensive. The flags track whether the given lane contains an element
9155   // that crosses to another lane.
9156   bool LaneCrossing[2] = {false, false};
9157   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9158     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9159       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9160   if (!LaneCrossing[0] || !LaneCrossing[1])
9161     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9162
9163   if (isSingleInputShuffleMask(Mask)) {
9164     SmallVector<int, 32> FlippedBlendMask;
9165     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9166       FlippedBlendMask.push_back(
9167           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9168                                   ? Mask[i]
9169                                   : Mask[i] % LaneSize +
9170                                         (i / LaneSize) * LaneSize + Size));
9171
9172     // Flip the vector, and blend the results which should now be in-lane. The
9173     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9174     // 5 for the high source. The value 3 selects the high half of source 2 and
9175     // the value 2 selects the low half of source 2. We only use source 2 to
9176     // allow folding it into a memory operand.
9177     unsigned PERMMask = 3 | 2 << 4;
9178     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9179                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9180     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9181   }
9182
9183   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9184   // will be handled by the above logic and a blend of the results, much like
9185   // other patterns in AVX.
9186   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9187 }
9188
9189 /// \brief Handle lowering 2-lane 128-bit shuffles.
9190 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9191                                         SDValue V2, ArrayRef<int> Mask,
9192                                         const X86Subtarget *Subtarget,
9193                                         SelectionDAG &DAG) {
9194   // TODO: If minimizing size and one of the inputs is a zero vector and the
9195   // the zero vector has only one use, we could use a VPERM2X128 to save the
9196   // instruction bytes needed to explicitly generate the zero vector.
9197
9198   // Blends are faster and handle all the non-lane-crossing cases.
9199   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9200                                                 Subtarget, DAG))
9201     return Blend;
9202
9203   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9204   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9205
9206   // If either input operand is a zero vector, use VPERM2X128 because its mask
9207   // allows us to replace the zero input with an implicit zero.
9208   if (!IsV1Zero && !IsV2Zero) {
9209     // Check for patterns which can be matched with a single insert of a 128-bit
9210     // subvector.
9211     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9212     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9213       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9214                                    VT.getVectorNumElements() / 2);
9215       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9216                                 DAG.getIntPtrConstant(0, DL));
9217       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9218                                 OnlyUsesV1 ? V1 : V2,
9219                                 DAG.getIntPtrConstant(0, DL));
9220       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9221     }
9222   }
9223
9224   // Otherwise form a 128-bit permutation. After accounting for undefs,
9225   // convert the 64-bit shuffle mask selection values into 128-bit
9226   // selection bits by dividing the indexes by 2 and shifting into positions
9227   // defined by a vperm2*128 instruction's immediate control byte.
9228
9229   // The immediate permute control byte looks like this:
9230   //    [1:0] - select 128 bits from sources for low half of destination
9231   //    [2]   - ignore
9232   //    [3]   - zero low half of destination
9233   //    [5:4] - select 128 bits from sources for high half of destination
9234   //    [6]   - ignore
9235   //    [7]   - zero high half of destination
9236
9237   int MaskLO = Mask[0];
9238   if (MaskLO == SM_SentinelUndef)
9239     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9240
9241   int MaskHI = Mask[2];
9242   if (MaskHI == SM_SentinelUndef)
9243     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9244
9245   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9246
9247   // If either input is a zero vector, replace it with an undef input.
9248   // Shuffle mask values <  4 are selecting elements of V1.
9249   // Shuffle mask values >= 4 are selecting elements of V2.
9250   // Adjust each half of the permute mask by clearing the half that was
9251   // selecting the zero vector and setting the zero mask bit.
9252   if (IsV1Zero) {
9253     V1 = DAG.getUNDEF(VT);
9254     if (MaskLO < 4)
9255       PermMask = (PermMask & 0xf0) | 0x08;
9256     if (MaskHI < 4)
9257       PermMask = (PermMask & 0x0f) | 0x80;
9258   }
9259   if (IsV2Zero) {
9260     V2 = DAG.getUNDEF(VT);
9261     if (MaskLO >= 4)
9262       PermMask = (PermMask & 0xf0) | 0x08;
9263     if (MaskHI >= 4)
9264       PermMask = (PermMask & 0x0f) | 0x80;
9265   }
9266
9267   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9268                      DAG.getConstant(PermMask, DL, MVT::i8));
9269 }
9270
9271 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9272 /// shuffling each lane.
9273 ///
9274 /// This will only succeed when the result of fixing the 128-bit lanes results
9275 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9276 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9277 /// the lane crosses early and then use simpler shuffles within each lane.
9278 ///
9279 /// FIXME: It might be worthwhile at some point to support this without
9280 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9281 /// in x86 only floating point has interesting non-repeating shuffles, and even
9282 /// those are still *marginally* more expensive.
9283 static SDValue lowerVectorShuffleByMerging128BitLanes(
9284     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9285     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9286   assert(!isSingleInputShuffleMask(Mask) &&
9287          "This is only useful with multiple inputs.");
9288
9289   int Size = Mask.size();
9290   int LaneSize = 128 / VT.getScalarSizeInBits();
9291   int NumLanes = Size / LaneSize;
9292   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9293
9294   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9295   // check whether the in-128-bit lane shuffles share a repeating pattern.
9296   SmallVector<int, 4> Lanes;
9297   Lanes.resize(NumLanes, -1);
9298   SmallVector<int, 4> InLaneMask;
9299   InLaneMask.resize(LaneSize, -1);
9300   for (int i = 0; i < Size; ++i) {
9301     if (Mask[i] < 0)
9302       continue;
9303
9304     int j = i / LaneSize;
9305
9306     if (Lanes[j] < 0) {
9307       // First entry we've seen for this lane.
9308       Lanes[j] = Mask[i] / LaneSize;
9309     } else if (Lanes[j] != Mask[i] / LaneSize) {
9310       // This doesn't match the lane selected previously!
9311       return SDValue();
9312     }
9313
9314     // Check that within each lane we have a consistent shuffle mask.
9315     int k = i % LaneSize;
9316     if (InLaneMask[k] < 0) {
9317       InLaneMask[k] = Mask[i] % LaneSize;
9318     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9319       // This doesn't fit a repeating in-lane mask.
9320       return SDValue();
9321     }
9322   }
9323
9324   // First shuffle the lanes into place.
9325   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9326                                 VT.getSizeInBits() / 64);
9327   SmallVector<int, 8> LaneMask;
9328   LaneMask.resize(NumLanes * 2, -1);
9329   for (int i = 0; i < NumLanes; ++i)
9330     if (Lanes[i] >= 0) {
9331       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9332       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9333     }
9334
9335   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9336   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9337   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9338
9339   // Cast it back to the type we actually want.
9340   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9341
9342   // Now do a simple shuffle that isn't lane crossing.
9343   SmallVector<int, 8> NewMask;
9344   NewMask.resize(Size, -1);
9345   for (int i = 0; i < Size; ++i)
9346     if (Mask[i] >= 0)
9347       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9348   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9349          "Must not introduce lane crosses at this point!");
9350
9351   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9352 }
9353
9354 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9355 /// given mask.
9356 ///
9357 /// This returns true if the elements from a particular input are already in the
9358 /// slot required by the given mask and require no permutation.
9359 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9360   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9361   int Size = Mask.size();
9362   for (int i = 0; i < Size; ++i)
9363     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9364       return false;
9365
9366   return true;
9367 }
9368
9369 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9370 ///
9371 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9372 /// isn't available.
9373 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9374                                        const X86Subtarget *Subtarget,
9375                                        SelectionDAG &DAG) {
9376   SDLoc DL(Op);
9377   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9378   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9379   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9380   ArrayRef<int> Mask = SVOp->getMask();
9381   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9382
9383   SmallVector<int, 4> WidenedMask;
9384   if (canWidenShuffleElements(Mask, WidenedMask))
9385     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9386                                     DAG);
9387
9388   if (isSingleInputShuffleMask(Mask)) {
9389     // Check for being able to broadcast a single element.
9390     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9391                                                           Mask, Subtarget, DAG))
9392       return Broadcast;
9393
9394     // Use low duplicate instructions for masks that match their pattern.
9395     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9396       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9397
9398     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9399       // Non-half-crossing single input shuffles can be lowerid with an
9400       // interleaved permutation.
9401       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9402                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9403       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9404                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9405     }
9406
9407     // With AVX2 we have direct support for this permutation.
9408     if (Subtarget->hasAVX2())
9409       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9410                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9411
9412     // Otherwise, fall back.
9413     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9414                                                    DAG);
9415   }
9416
9417   // X86 has dedicated unpack instructions that can handle specific blend
9418   // operations: UNPCKH and UNPCKL.
9419   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9420     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9421   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9422     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9423   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9424     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9425   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9426     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9427
9428   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9429                                                 Subtarget, DAG))
9430     return Blend;
9431
9432   // Check if the blend happens to exactly fit that of SHUFPD.
9433   if ((Mask[0] == -1 || Mask[0] < 2) &&
9434       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9435       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9436       (Mask[3] == -1 || Mask[3] >= 6)) {
9437     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9438                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9439     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9440                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9441   }
9442   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9443       (Mask[1] == -1 || Mask[1] < 2) &&
9444       (Mask[2] == -1 || Mask[2] >= 6) &&
9445       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9446     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9447                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9448     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9449                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9450   }
9451
9452   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9453   // shuffle. However, if we have AVX2 and either inputs are already in place,
9454   // we will be able to shuffle even across lanes the other input in a single
9455   // instruction so skip this pattern.
9456   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9457                                  isShuffleMaskInputInPlace(1, Mask))))
9458     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9459             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9460       return Result;
9461
9462   // If we have AVX2 then we always want to lower with a blend because an v4 we
9463   // can fully permute the elements.
9464   if (Subtarget->hasAVX2())
9465     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9466                                                       Mask, DAG);
9467
9468   // Otherwise fall back on generic lowering.
9469   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9470 }
9471
9472 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9473 ///
9474 /// This routine is only called when we have AVX2 and thus a reasonable
9475 /// instruction set for v4i64 shuffling..
9476 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9477                                        const X86Subtarget *Subtarget,
9478                                        SelectionDAG &DAG) {
9479   SDLoc DL(Op);
9480   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9481   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9482   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9483   ArrayRef<int> Mask = SVOp->getMask();
9484   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9485   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9486
9487   SmallVector<int, 4> WidenedMask;
9488   if (canWidenShuffleElements(Mask, WidenedMask))
9489     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9490                                     DAG);
9491
9492   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9493                                                 Subtarget, DAG))
9494     return Blend;
9495
9496   // Check for being able to broadcast a single element.
9497   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9498                                                         Mask, Subtarget, DAG))
9499     return Broadcast;
9500
9501   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9502   // use lower latency instructions that will operate on both 128-bit lanes.
9503   SmallVector<int, 2> RepeatedMask;
9504   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9505     if (isSingleInputShuffleMask(Mask)) {
9506       int PSHUFDMask[] = {-1, -1, -1, -1};
9507       for (int i = 0; i < 2; ++i)
9508         if (RepeatedMask[i] >= 0) {
9509           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9510           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9511         }
9512       return DAG.getNode(
9513           ISD::BITCAST, DL, MVT::v4i64,
9514           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9515                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9516                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9517     }
9518   }
9519
9520   // AVX2 provides a direct instruction for permuting a single input across
9521   // lanes.
9522   if (isSingleInputShuffleMask(Mask))
9523     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9524                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9525
9526   // Try to use shift instructions.
9527   if (SDValue Shift =
9528           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9529     return Shift;
9530
9531   // Use dedicated unpack instructions for masks that match their pattern.
9532   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9533     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9534   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9535     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9536   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9537     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9538   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9539     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9540
9541   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9542   // shuffle. However, if we have AVX2 and either inputs are already in place,
9543   // we will be able to shuffle even across lanes the other input in a single
9544   // instruction so skip this pattern.
9545   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9546                                  isShuffleMaskInputInPlace(1, Mask))))
9547     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9548             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9549       return Result;
9550
9551   // Otherwise fall back on generic blend lowering.
9552   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9553                                                     Mask, DAG);
9554 }
9555
9556 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9557 ///
9558 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9559 /// isn't available.
9560 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9561                                        const X86Subtarget *Subtarget,
9562                                        SelectionDAG &DAG) {
9563   SDLoc DL(Op);
9564   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9565   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9566   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9567   ArrayRef<int> Mask = SVOp->getMask();
9568   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9569
9570   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9571                                                 Subtarget, DAG))
9572     return Blend;
9573
9574   // Check for being able to broadcast a single element.
9575   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9576                                                         Mask, Subtarget, DAG))
9577     return Broadcast;
9578
9579   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9580   // options to efficiently lower the shuffle.
9581   SmallVector<int, 4> RepeatedMask;
9582   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9583     assert(RepeatedMask.size() == 4 &&
9584            "Repeated masks must be half the mask width!");
9585
9586     // Use even/odd duplicate instructions for masks that match their pattern.
9587     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9588       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9589     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9590       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9591
9592     if (isSingleInputShuffleMask(Mask))
9593       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9594                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9595
9596     // Use dedicated unpack instructions for masks that match their pattern.
9597     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9598       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9599     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9600       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9601     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9602       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9603     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9604       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9605
9606     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9607     // have already handled any direct blends. We also need to squash the
9608     // repeated mask into a simulated v4f32 mask.
9609     for (int i = 0; i < 4; ++i)
9610       if (RepeatedMask[i] >= 8)
9611         RepeatedMask[i] -= 4;
9612     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9613   }
9614
9615   // If we have a single input shuffle with different shuffle patterns in the
9616   // two 128-bit lanes use the variable mask to VPERMILPS.
9617   if (isSingleInputShuffleMask(Mask)) {
9618     SDValue VPermMask[8];
9619     for (int i = 0; i < 8; ++i)
9620       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9621                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9622     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9623       return DAG.getNode(
9624           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9625           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9626
9627     if (Subtarget->hasAVX2())
9628       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9629                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9630                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9631                                                  MVT::v8i32, VPermMask)),
9632                          V1);
9633
9634     // Otherwise, fall back.
9635     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9636                                                    DAG);
9637   }
9638
9639   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9640   // shuffle.
9641   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9642           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9643     return Result;
9644
9645   // If we have AVX2 then we always want to lower with a blend because at v8 we
9646   // can fully permute the elements.
9647   if (Subtarget->hasAVX2())
9648     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9649                                                       Mask, DAG);
9650
9651   // Otherwise fall back on generic lowering.
9652   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9653 }
9654
9655 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9656 ///
9657 /// This routine is only called when we have AVX2 and thus a reasonable
9658 /// instruction set for v8i32 shuffling..
9659 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9660                                        const X86Subtarget *Subtarget,
9661                                        SelectionDAG &DAG) {
9662   SDLoc DL(Op);
9663   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9664   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9665   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9666   ArrayRef<int> Mask = SVOp->getMask();
9667   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9668   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9669
9670   // Whenever we can lower this as a zext, that instruction is strictly faster
9671   // than any alternative. It also allows us to fold memory operands into the
9672   // shuffle in many cases.
9673   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9674                                                          Mask, Subtarget, DAG))
9675     return ZExt;
9676
9677   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9678                                                 Subtarget, DAG))
9679     return Blend;
9680
9681   // Check for being able to broadcast a single element.
9682   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9683                                                         Mask, Subtarget, DAG))
9684     return Broadcast;
9685
9686   // If the shuffle mask is repeated in each 128-bit lane we can use more
9687   // efficient instructions that mirror the shuffles across the two 128-bit
9688   // lanes.
9689   SmallVector<int, 4> RepeatedMask;
9690   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9691     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9692     if (isSingleInputShuffleMask(Mask))
9693       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9694                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9695
9696     // Use dedicated unpack instructions for masks that match their pattern.
9697     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9698       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9699     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9700       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9701     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9702       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9703     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9704       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9705   }
9706
9707   // Try to use shift instructions.
9708   if (SDValue Shift =
9709           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9710     return Shift;
9711
9712   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9713           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9714     return Rotate;
9715
9716   // If the shuffle patterns aren't repeated but it is a single input, directly
9717   // generate a cross-lane VPERMD instruction.
9718   if (isSingleInputShuffleMask(Mask)) {
9719     SDValue VPermMask[8];
9720     for (int i = 0; i < 8; ++i)
9721       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9722                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9723     return DAG.getNode(
9724         X86ISD::VPERMV, DL, MVT::v8i32,
9725         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9726   }
9727
9728   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9729   // shuffle.
9730   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9731           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9732     return Result;
9733
9734   // Otherwise fall back on generic blend lowering.
9735   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9736                                                     Mask, DAG);
9737 }
9738
9739 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9740 ///
9741 /// This routine is only called when we have AVX2 and thus a reasonable
9742 /// instruction set for v16i16 shuffling..
9743 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9744                                         const X86Subtarget *Subtarget,
9745                                         SelectionDAG &DAG) {
9746   SDLoc DL(Op);
9747   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9748   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9749   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9750   ArrayRef<int> Mask = SVOp->getMask();
9751   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9752   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9753
9754   // Whenever we can lower this as a zext, that instruction is strictly faster
9755   // than any alternative. It also allows us to fold memory operands into the
9756   // shuffle in many cases.
9757   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9758                                                          Mask, Subtarget, DAG))
9759     return ZExt;
9760
9761   // Check for being able to broadcast a single element.
9762   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9763                                                         Mask, Subtarget, DAG))
9764     return Broadcast;
9765
9766   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9767                                                 Subtarget, DAG))
9768     return Blend;
9769
9770   // Use dedicated unpack instructions for masks that match their pattern.
9771   if (isShuffleEquivalent(V1, V2, Mask,
9772                           {// First 128-bit lane:
9773                            0, 16, 1, 17, 2, 18, 3, 19,
9774                            // Second 128-bit lane:
9775                            8, 24, 9, 25, 10, 26, 11, 27}))
9776     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9777   if (isShuffleEquivalent(V1, V2, Mask,
9778                           {// First 128-bit lane:
9779                            4, 20, 5, 21, 6, 22, 7, 23,
9780                            // Second 128-bit lane:
9781                            12, 28, 13, 29, 14, 30, 15, 31}))
9782     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9783
9784   // Try to use shift instructions.
9785   if (SDValue Shift =
9786           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9787     return Shift;
9788
9789   // Try to use byte rotation instructions.
9790   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9791           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9792     return Rotate;
9793
9794   if (isSingleInputShuffleMask(Mask)) {
9795     // There are no generalized cross-lane shuffle operations available on i16
9796     // element types.
9797     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9798       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9799                                                      Mask, DAG);
9800
9801     SmallVector<int, 8> RepeatedMask;
9802     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9803       // As this is a single-input shuffle, the repeated mask should be
9804       // a strictly valid v8i16 mask that we can pass through to the v8i16
9805       // lowering to handle even the v16 case.
9806       return lowerV8I16GeneralSingleInputVectorShuffle(
9807           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9808     }
9809
9810     SDValue PSHUFBMask[32];
9811     for (int i = 0; i < 16; ++i) {
9812       if (Mask[i] == -1) {
9813         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9814         continue;
9815       }
9816
9817       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9818       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9819       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9820       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9821     }
9822     return DAG.getNode(
9823         ISD::BITCAST, DL, MVT::v16i16,
9824         DAG.getNode(
9825             X86ISD::PSHUFB, DL, MVT::v32i8,
9826             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9827             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9828   }
9829
9830   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9831   // shuffle.
9832   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9833           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9834     return Result;
9835
9836   // Otherwise fall back on generic lowering.
9837   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9838 }
9839
9840 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9841 ///
9842 /// This routine is only called when we have AVX2 and thus a reasonable
9843 /// instruction set for v32i8 shuffling..
9844 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9845                                        const X86Subtarget *Subtarget,
9846                                        SelectionDAG &DAG) {
9847   SDLoc DL(Op);
9848   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9849   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9850   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9851   ArrayRef<int> Mask = SVOp->getMask();
9852   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9853   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9854
9855   // Whenever we can lower this as a zext, that instruction is strictly faster
9856   // than any alternative. It also allows us to fold memory operands into the
9857   // shuffle in many cases.
9858   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9859                                                          Mask, Subtarget, DAG))
9860     return ZExt;
9861
9862   // Check for being able to broadcast a single element.
9863   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9864                                                         Mask, Subtarget, DAG))
9865     return Broadcast;
9866
9867   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9868                                                 Subtarget, DAG))
9869     return Blend;
9870
9871   // Use dedicated unpack instructions for masks that match their pattern.
9872   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9873   // 256-bit lanes.
9874   if (isShuffleEquivalent(
9875           V1, V2, Mask,
9876           {// First 128-bit lane:
9877            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9878            // Second 128-bit lane:
9879            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9880     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9881   if (isShuffleEquivalent(
9882           V1, V2, Mask,
9883           {// First 128-bit lane:
9884            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9885            // Second 128-bit lane:
9886            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9887     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9888
9889   // Try to use shift instructions.
9890   if (SDValue Shift =
9891           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9892     return Shift;
9893
9894   // Try to use byte rotation instructions.
9895   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9896           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9897     return Rotate;
9898
9899   if (isSingleInputShuffleMask(Mask)) {
9900     // There are no generalized cross-lane shuffle operations available on i8
9901     // element types.
9902     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9903       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9904                                                      Mask, DAG);
9905
9906     SDValue PSHUFBMask[32];
9907     for (int i = 0; i < 32; ++i)
9908       PSHUFBMask[i] =
9909           Mask[i] < 0
9910               ? DAG.getUNDEF(MVT::i8)
9911               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9912                                 MVT::i8);
9913
9914     return DAG.getNode(
9915         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9916         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9917   }
9918
9919   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9920   // shuffle.
9921   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9922           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9923     return Result;
9924
9925   // Otherwise fall back on generic lowering.
9926   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9927 }
9928
9929 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9930 ///
9931 /// This routine either breaks down the specific type of a 256-bit x86 vector
9932 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9933 /// together based on the available instructions.
9934 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9935                                         MVT VT, const X86Subtarget *Subtarget,
9936                                         SelectionDAG &DAG) {
9937   SDLoc DL(Op);
9938   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9939   ArrayRef<int> Mask = SVOp->getMask();
9940
9941   // If we have a single input to the zero element, insert that into V1 if we
9942   // can do so cheaply.
9943   int NumElts = VT.getVectorNumElements();
9944   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9945     return M >= NumElts;
9946   });
9947
9948   if (NumV2Elements == 1 && Mask[0] >= NumElts)
9949     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9950                               DL, VT, V1, V2, Mask, Subtarget, DAG))
9951       return Insertion;
9952
9953   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9954   // check for those subtargets here and avoid much of the subtarget querying in
9955   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9956   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9957   // floating point types there eventually, just immediately cast everything to
9958   // a float and operate entirely in that domain.
9959   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9960     int ElementBits = VT.getScalarSizeInBits();
9961     if (ElementBits < 32)
9962       // No floating point type available, decompose into 128-bit vectors.
9963       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9964
9965     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9966                                 VT.getVectorNumElements());
9967     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9968     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9969     return DAG.getNode(ISD::BITCAST, DL, VT,
9970                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9971   }
9972
9973   switch (VT.SimpleTy) {
9974   case MVT::v4f64:
9975     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9976   case MVT::v4i64:
9977     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9978   case MVT::v8f32:
9979     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9980   case MVT::v8i32:
9981     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9982   case MVT::v16i16:
9983     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9984   case MVT::v32i8:
9985     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9986
9987   default:
9988     llvm_unreachable("Not a valid 256-bit x86 vector type!");
9989   }
9990 }
9991
9992 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9993 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9994                                        const X86Subtarget *Subtarget,
9995                                        SelectionDAG &DAG) {
9996   SDLoc DL(Op);
9997   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9998   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9999   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10000   ArrayRef<int> Mask = SVOp->getMask();
10001   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10002
10003   // X86 has dedicated unpack instructions that can handle specific blend
10004   // operations: UNPCKH and UNPCKL.
10005   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10006     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10007   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10008     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10009
10010   // FIXME: Implement direct support for this type!
10011   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10012 }
10013
10014 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10015 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10016                                        const X86Subtarget *Subtarget,
10017                                        SelectionDAG &DAG) {
10018   SDLoc DL(Op);
10019   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10020   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10021   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10022   ArrayRef<int> Mask = SVOp->getMask();
10023   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10024
10025   // Use dedicated unpack instructions for masks that match their pattern.
10026   if (isShuffleEquivalent(V1, V2, Mask,
10027                           {// First 128-bit lane.
10028                            0, 16, 1, 17, 4, 20, 5, 21,
10029                            // Second 128-bit lane.
10030                            8, 24, 9, 25, 12, 28, 13, 29}))
10031     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10032   if (isShuffleEquivalent(V1, V2, Mask,
10033                           {// First 128-bit lane.
10034                            2, 18, 3, 19, 6, 22, 7, 23,
10035                            // Second 128-bit lane.
10036                            10, 26, 11, 27, 14, 30, 15, 31}))
10037     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10038
10039   // FIXME: Implement direct support for this type!
10040   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10041 }
10042
10043 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10044 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10045                                        const X86Subtarget *Subtarget,
10046                                        SelectionDAG &DAG) {
10047   SDLoc DL(Op);
10048   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10049   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10050   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10051   ArrayRef<int> Mask = SVOp->getMask();
10052   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10053
10054   // X86 has dedicated unpack instructions that can handle specific blend
10055   // operations: UNPCKH and UNPCKL.
10056   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10057     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10058   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10059     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10060
10061   // FIXME: Implement direct support for this type!
10062   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10063 }
10064
10065 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10066 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10067                                        const X86Subtarget *Subtarget,
10068                                        SelectionDAG &DAG) {
10069   SDLoc DL(Op);
10070   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10071   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10072   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10073   ArrayRef<int> Mask = SVOp->getMask();
10074   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10075
10076   // Use dedicated unpack instructions for masks that match their pattern.
10077   if (isShuffleEquivalent(V1, V2, Mask,
10078                           {// First 128-bit lane.
10079                            0, 16, 1, 17, 4, 20, 5, 21,
10080                            // Second 128-bit lane.
10081                            8, 24, 9, 25, 12, 28, 13, 29}))
10082     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10083   if (isShuffleEquivalent(V1, V2, Mask,
10084                           {// First 128-bit lane.
10085                            2, 18, 3, 19, 6, 22, 7, 23,
10086                            // Second 128-bit lane.
10087                            10, 26, 11, 27, 14, 30, 15, 31}))
10088     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10089
10090   // FIXME: Implement direct support for this type!
10091   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10092 }
10093
10094 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10095 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10096                                         const X86Subtarget *Subtarget,
10097                                         SelectionDAG &DAG) {
10098   SDLoc DL(Op);
10099   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10100   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10101   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10102   ArrayRef<int> Mask = SVOp->getMask();
10103   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10104   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10105
10106   // FIXME: Implement direct support for this type!
10107   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10108 }
10109
10110 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10111 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10112                                        const X86Subtarget *Subtarget,
10113                                        SelectionDAG &DAG) {
10114   SDLoc DL(Op);
10115   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10116   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10117   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10118   ArrayRef<int> Mask = SVOp->getMask();
10119   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10120   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10121
10122   // FIXME: Implement direct support for this type!
10123   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10124 }
10125
10126 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10127 ///
10128 /// This routine either breaks down the specific type of a 512-bit x86 vector
10129 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10130 /// together based on the available instructions.
10131 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10132                                         MVT VT, const X86Subtarget *Subtarget,
10133                                         SelectionDAG &DAG) {
10134   SDLoc DL(Op);
10135   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10136   ArrayRef<int> Mask = SVOp->getMask();
10137   assert(Subtarget->hasAVX512() &&
10138          "Cannot lower 512-bit vectors w/ basic ISA!");
10139
10140   // Check for being able to broadcast a single element.
10141   if (SDValue Broadcast =
10142           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10143     return Broadcast;
10144
10145   // Dispatch to each element type for lowering. If we don't have supprot for
10146   // specific element type shuffles at 512 bits, immediately split them and
10147   // lower them. Each lowering routine of a given type is allowed to assume that
10148   // the requisite ISA extensions for that element type are available.
10149   switch (VT.SimpleTy) {
10150   case MVT::v8f64:
10151     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10152   case MVT::v16f32:
10153     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10154   case MVT::v8i64:
10155     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10156   case MVT::v16i32:
10157     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10158   case MVT::v32i16:
10159     if (Subtarget->hasBWI())
10160       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10161     break;
10162   case MVT::v64i8:
10163     if (Subtarget->hasBWI())
10164       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10165     break;
10166
10167   default:
10168     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10169   }
10170
10171   // Otherwise fall back on splitting.
10172   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10173 }
10174
10175 /// \brief Top-level lowering for x86 vector shuffles.
10176 ///
10177 /// This handles decomposition, canonicalization, and lowering of all x86
10178 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10179 /// above in helper routines. The canonicalization attempts to widen shuffles
10180 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10181 /// s.t. only one of the two inputs needs to be tested, etc.
10182 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10183                                   SelectionDAG &DAG) {
10184   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10185   ArrayRef<int> Mask = SVOp->getMask();
10186   SDValue V1 = Op.getOperand(0);
10187   SDValue V2 = Op.getOperand(1);
10188   MVT VT = Op.getSimpleValueType();
10189   int NumElements = VT.getVectorNumElements();
10190   SDLoc dl(Op);
10191
10192   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10193
10194   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10195   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10196   if (V1IsUndef && V2IsUndef)
10197     return DAG.getUNDEF(VT);
10198
10199   // When we create a shuffle node we put the UNDEF node to second operand,
10200   // but in some cases the first operand may be transformed to UNDEF.
10201   // In this case we should just commute the node.
10202   if (V1IsUndef)
10203     return DAG.getCommutedVectorShuffle(*SVOp);
10204
10205   // Check for non-undef masks pointing at an undef vector and make the masks
10206   // undef as well. This makes it easier to match the shuffle based solely on
10207   // the mask.
10208   if (V2IsUndef)
10209     for (int M : Mask)
10210       if (M >= NumElements) {
10211         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10212         for (int &M : NewMask)
10213           if (M >= NumElements)
10214             M = -1;
10215         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10216       }
10217
10218   // We actually see shuffles that are entirely re-arrangements of a set of
10219   // zero inputs. This mostly happens while decomposing complex shuffles into
10220   // simple ones. Directly lower these as a buildvector of zeros.
10221   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10222   if (Zeroable.all())
10223     return getZeroVector(VT, Subtarget, DAG, dl);
10224
10225   // Try to collapse shuffles into using a vector type with fewer elements but
10226   // wider element types. We cap this to not form integers or floating point
10227   // elements wider than 64 bits, but it might be interesting to form i128
10228   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10229   SmallVector<int, 16> WidenedMask;
10230   if (VT.getScalarSizeInBits() < 64 &&
10231       canWidenShuffleElements(Mask, WidenedMask)) {
10232     MVT NewEltVT = VT.isFloatingPoint()
10233                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10234                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10235     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10236     // Make sure that the new vector type is legal. For example, v2f64 isn't
10237     // legal on SSE1.
10238     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10239       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10240       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10241       return DAG.getNode(ISD::BITCAST, dl, VT,
10242                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10243     }
10244   }
10245
10246   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10247   for (int M : SVOp->getMask())
10248     if (M < 0)
10249       ++NumUndefElements;
10250     else if (M < NumElements)
10251       ++NumV1Elements;
10252     else
10253       ++NumV2Elements;
10254
10255   // Commute the shuffle as needed such that more elements come from V1 than
10256   // V2. This allows us to match the shuffle pattern strictly on how many
10257   // elements come from V1 without handling the symmetric cases.
10258   if (NumV2Elements > NumV1Elements)
10259     return DAG.getCommutedVectorShuffle(*SVOp);
10260
10261   // When the number of V1 and V2 elements are the same, try to minimize the
10262   // number of uses of V2 in the low half of the vector. When that is tied,
10263   // ensure that the sum of indices for V1 is equal to or lower than the sum
10264   // indices for V2. When those are equal, try to ensure that the number of odd
10265   // indices for V1 is lower than the number of odd indices for V2.
10266   if (NumV1Elements == NumV2Elements) {
10267     int LowV1Elements = 0, LowV2Elements = 0;
10268     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10269       if (M >= NumElements)
10270         ++LowV2Elements;
10271       else if (M >= 0)
10272         ++LowV1Elements;
10273     if (LowV2Elements > LowV1Elements) {
10274       return DAG.getCommutedVectorShuffle(*SVOp);
10275     } else if (LowV2Elements == LowV1Elements) {
10276       int SumV1Indices = 0, SumV2Indices = 0;
10277       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10278         if (SVOp->getMask()[i] >= NumElements)
10279           SumV2Indices += i;
10280         else if (SVOp->getMask()[i] >= 0)
10281           SumV1Indices += i;
10282       if (SumV2Indices < SumV1Indices) {
10283         return DAG.getCommutedVectorShuffle(*SVOp);
10284       } else if (SumV2Indices == SumV1Indices) {
10285         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10286         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10287           if (SVOp->getMask()[i] >= NumElements)
10288             NumV2OddIndices += i % 2;
10289           else if (SVOp->getMask()[i] >= 0)
10290             NumV1OddIndices += i % 2;
10291         if (NumV2OddIndices < NumV1OddIndices)
10292           return DAG.getCommutedVectorShuffle(*SVOp);
10293       }
10294     }
10295   }
10296
10297   // For each vector width, delegate to a specialized lowering routine.
10298   if (VT.getSizeInBits() == 128)
10299     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10300
10301   if (VT.getSizeInBits() == 256)
10302     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10303
10304   // Force AVX-512 vectors to be scalarized for now.
10305   // FIXME: Implement AVX-512 support!
10306   if (VT.getSizeInBits() == 512)
10307     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10308
10309   llvm_unreachable("Unimplemented!");
10310 }
10311
10312 // This function assumes its argument is a BUILD_VECTOR of constants or
10313 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10314 // true.
10315 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10316                                     unsigned &MaskValue) {
10317   MaskValue = 0;
10318   unsigned NumElems = BuildVector->getNumOperands();
10319   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10320   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10321   unsigned NumElemsInLane = NumElems / NumLanes;
10322
10323   // Blend for v16i16 should be symetric for the both lanes.
10324   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10325     SDValue EltCond = BuildVector->getOperand(i);
10326     SDValue SndLaneEltCond =
10327         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10328
10329     int Lane1Cond = -1, Lane2Cond = -1;
10330     if (isa<ConstantSDNode>(EltCond))
10331       Lane1Cond = !isZero(EltCond);
10332     if (isa<ConstantSDNode>(SndLaneEltCond))
10333       Lane2Cond = !isZero(SndLaneEltCond);
10334
10335     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10336       // Lane1Cond != 0, means we want the first argument.
10337       // Lane1Cond == 0, means we want the second argument.
10338       // The encoding of this argument is 0 for the first argument, 1
10339       // for the second. Therefore, invert the condition.
10340       MaskValue |= !Lane1Cond << i;
10341     else if (Lane1Cond < 0)
10342       MaskValue |= !Lane2Cond << i;
10343     else
10344       return false;
10345   }
10346   return true;
10347 }
10348
10349 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10350 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10351                                            const X86Subtarget *Subtarget,
10352                                            SelectionDAG &DAG) {
10353   SDValue Cond = Op.getOperand(0);
10354   SDValue LHS = Op.getOperand(1);
10355   SDValue RHS = Op.getOperand(2);
10356   SDLoc dl(Op);
10357   MVT VT = Op.getSimpleValueType();
10358
10359   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10360     return SDValue();
10361   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10362
10363   // Only non-legal VSELECTs reach this lowering, convert those into generic
10364   // shuffles and re-use the shuffle lowering path for blends.
10365   SmallVector<int, 32> Mask;
10366   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10367     SDValue CondElt = CondBV->getOperand(i);
10368     Mask.push_back(
10369         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10370   }
10371   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10372 }
10373
10374 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10375   // A vselect where all conditions and data are constants can be optimized into
10376   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10377   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10378       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10379       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10380     return SDValue();
10381
10382   // Try to lower this to a blend-style vector shuffle. This can handle all
10383   // constant condition cases.
10384   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10385     return BlendOp;
10386
10387   // Variable blends are only legal from SSE4.1 onward.
10388   if (!Subtarget->hasSSE41())
10389     return SDValue();
10390
10391   // Only some types will be legal on some subtargets. If we can emit a legal
10392   // VSELECT-matching blend, return Op, and but if we need to expand, return
10393   // a null value.
10394   switch (Op.getSimpleValueType().SimpleTy) {
10395   default:
10396     // Most of the vector types have blends past SSE4.1.
10397     return Op;
10398
10399   case MVT::v32i8:
10400     // The byte blends for AVX vectors were introduced only in AVX2.
10401     if (Subtarget->hasAVX2())
10402       return Op;
10403
10404     return SDValue();
10405
10406   case MVT::v8i16:
10407   case MVT::v16i16:
10408     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10409     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10410       return Op;
10411
10412     // FIXME: We should custom lower this by fixing the condition and using i8
10413     // blends.
10414     return SDValue();
10415   }
10416 }
10417
10418 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10419   MVT VT = Op.getSimpleValueType();
10420   SDLoc dl(Op);
10421
10422   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10423     return SDValue();
10424
10425   if (VT.getSizeInBits() == 8) {
10426     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10427                                   Op.getOperand(0), Op.getOperand(1));
10428     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10429                                   DAG.getValueType(VT));
10430     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10431   }
10432
10433   if (VT.getSizeInBits() == 16) {
10434     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10435     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10436     if (Idx == 0)
10437       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10438                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10439                                      DAG.getNode(ISD::BITCAST, dl,
10440                                                  MVT::v4i32,
10441                                                  Op.getOperand(0)),
10442                                      Op.getOperand(1)));
10443     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10444                                   Op.getOperand(0), Op.getOperand(1));
10445     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10446                                   DAG.getValueType(VT));
10447     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10448   }
10449
10450   if (VT == MVT::f32) {
10451     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10452     // the result back to FR32 register. It's only worth matching if the
10453     // result has a single use which is a store or a bitcast to i32.  And in
10454     // the case of a store, it's not worth it if the index is a constant 0,
10455     // because a MOVSSmr can be used instead, which is smaller and faster.
10456     if (!Op.hasOneUse())
10457       return SDValue();
10458     SDNode *User = *Op.getNode()->use_begin();
10459     if ((User->getOpcode() != ISD::STORE ||
10460          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10461           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10462         (User->getOpcode() != ISD::BITCAST ||
10463          User->getValueType(0) != MVT::i32))
10464       return SDValue();
10465     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10466                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10467                                               Op.getOperand(0)),
10468                                               Op.getOperand(1));
10469     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10470   }
10471
10472   if (VT == MVT::i32 || VT == MVT::i64) {
10473     // ExtractPS/pextrq works with constant index.
10474     if (isa<ConstantSDNode>(Op.getOperand(1)))
10475       return Op;
10476   }
10477   return SDValue();
10478 }
10479
10480 /// Extract one bit from mask vector, like v16i1 or v8i1.
10481 /// AVX-512 feature.
10482 SDValue
10483 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10484   SDValue Vec = Op.getOperand(0);
10485   SDLoc dl(Vec);
10486   MVT VecVT = Vec.getSimpleValueType();
10487   SDValue Idx = Op.getOperand(1);
10488   MVT EltVT = Op.getSimpleValueType();
10489
10490   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10491   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10492          "Unexpected vector type in ExtractBitFromMaskVector");
10493
10494   // variable index can't be handled in mask registers,
10495   // extend vector to VR512
10496   if (!isa<ConstantSDNode>(Idx)) {
10497     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10498     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10499     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10500                               ExtVT.getVectorElementType(), Ext, Idx);
10501     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10502   }
10503
10504   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10505   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10506   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10507     rc = getRegClassFor(MVT::v16i1);
10508   unsigned MaxSift = rc->getSize()*8 - 1;
10509   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10510                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10511   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10512                     DAG.getConstant(MaxSift, dl, MVT::i8));
10513   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10514                        DAG.getIntPtrConstant(0, dl));
10515 }
10516
10517 SDValue
10518 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10519                                            SelectionDAG &DAG) const {
10520   SDLoc dl(Op);
10521   SDValue Vec = Op.getOperand(0);
10522   MVT VecVT = Vec.getSimpleValueType();
10523   SDValue Idx = Op.getOperand(1);
10524
10525   if (Op.getSimpleValueType() == MVT::i1)
10526     return ExtractBitFromMaskVector(Op, DAG);
10527
10528   if (!isa<ConstantSDNode>(Idx)) {
10529     if (VecVT.is512BitVector() ||
10530         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10531          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10532
10533       MVT MaskEltVT =
10534         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10535       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10536                                     MaskEltVT.getSizeInBits());
10537
10538       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10539       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10540                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10541                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10542       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10543       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10544                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10545     }
10546     return SDValue();
10547   }
10548
10549   // If this is a 256-bit vector result, first extract the 128-bit vector and
10550   // then extract the element from the 128-bit vector.
10551   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10552
10553     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10554     // Get the 128-bit vector.
10555     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10556     MVT EltVT = VecVT.getVectorElementType();
10557
10558     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10559
10560     //if (IdxVal >= NumElems/2)
10561     //  IdxVal -= NumElems/2;
10562     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10563     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10564                        DAG.getConstant(IdxVal, dl, MVT::i32));
10565   }
10566
10567   assert(VecVT.is128BitVector() && "Unexpected vector length");
10568
10569   if (Subtarget->hasSSE41()) {
10570     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10571     if (Res.getNode())
10572       return Res;
10573   }
10574
10575   MVT VT = Op.getSimpleValueType();
10576   // TODO: handle v16i8.
10577   if (VT.getSizeInBits() == 16) {
10578     SDValue Vec = Op.getOperand(0);
10579     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10580     if (Idx == 0)
10581       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10582                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10583                                      DAG.getNode(ISD::BITCAST, dl,
10584                                                  MVT::v4i32, Vec),
10585                                      Op.getOperand(1)));
10586     // Transform it so it match pextrw which produces a 32-bit result.
10587     MVT EltVT = MVT::i32;
10588     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10589                                   Op.getOperand(0), Op.getOperand(1));
10590     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10591                                   DAG.getValueType(VT));
10592     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10593   }
10594
10595   if (VT.getSizeInBits() == 32) {
10596     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10597     if (Idx == 0)
10598       return Op;
10599
10600     // SHUFPS the element to the lowest double word, then movss.
10601     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10602     MVT VVT = Op.getOperand(0).getSimpleValueType();
10603     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10604                                        DAG.getUNDEF(VVT), Mask);
10605     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10606                        DAG.getIntPtrConstant(0, dl));
10607   }
10608
10609   if (VT.getSizeInBits() == 64) {
10610     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10611     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10612     //        to match extract_elt for f64.
10613     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10614     if (Idx == 0)
10615       return Op;
10616
10617     // UNPCKHPD the element to the lowest double word, then movsd.
10618     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10619     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10620     int Mask[2] = { 1, -1 };
10621     MVT VVT = Op.getOperand(0).getSimpleValueType();
10622     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10623                                        DAG.getUNDEF(VVT), Mask);
10624     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10625                        DAG.getIntPtrConstant(0, dl));
10626   }
10627
10628   return SDValue();
10629 }
10630
10631 /// Insert one bit to mask vector, like v16i1 or v8i1.
10632 /// AVX-512 feature.
10633 SDValue
10634 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10635   SDLoc dl(Op);
10636   SDValue Vec = Op.getOperand(0);
10637   SDValue Elt = Op.getOperand(1);
10638   SDValue Idx = Op.getOperand(2);
10639   MVT VecVT = Vec.getSimpleValueType();
10640
10641   if (!isa<ConstantSDNode>(Idx)) {
10642     // Non constant index. Extend source and destination,
10643     // insert element and then truncate the result.
10644     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10645     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10646     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10647       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10648       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10649     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10650   }
10651
10652   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10653   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10654   if (Vec.getOpcode() == ISD::UNDEF)
10655     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10656                        DAG.getConstant(IdxVal, dl, MVT::i8));
10657   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10658   unsigned MaxSift = rc->getSize()*8 - 1;
10659   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10660                     DAG.getConstant(MaxSift, dl, MVT::i8));
10661   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10662                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10663   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10664 }
10665
10666 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10667                                                   SelectionDAG &DAG) const {
10668   MVT VT = Op.getSimpleValueType();
10669   MVT EltVT = VT.getVectorElementType();
10670
10671   if (EltVT == MVT::i1)
10672     return InsertBitToMaskVector(Op, DAG);
10673
10674   SDLoc dl(Op);
10675   SDValue N0 = Op.getOperand(0);
10676   SDValue N1 = Op.getOperand(1);
10677   SDValue N2 = Op.getOperand(2);
10678   if (!isa<ConstantSDNode>(N2))
10679     return SDValue();
10680   auto *N2C = cast<ConstantSDNode>(N2);
10681   unsigned IdxVal = N2C->getZExtValue();
10682
10683   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10684   // into that, and then insert the subvector back into the result.
10685   if (VT.is256BitVector() || VT.is512BitVector()) {
10686     // With a 256-bit vector, we can insert into the zero element efficiently
10687     // using a blend if we have AVX or AVX2 and the right data type.
10688     if (VT.is256BitVector() && IdxVal == 0) {
10689       // TODO: It is worthwhile to cast integer to floating point and back
10690       // and incur a domain crossing penalty if that's what we'll end up
10691       // doing anyway after extracting to a 128-bit vector.
10692       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10693           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10694         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10695         N2 = DAG.getIntPtrConstant(1, dl);
10696         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10697       }
10698     }
10699
10700     // Get the desired 128-bit vector chunk.
10701     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10702
10703     // Insert the element into the desired chunk.
10704     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10705     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10706
10707     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10708                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10709
10710     // Insert the changed part back into the bigger vector
10711     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10712   }
10713   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10714
10715   if (Subtarget->hasSSE41()) {
10716     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10717       unsigned Opc;
10718       if (VT == MVT::v8i16) {
10719         Opc = X86ISD::PINSRW;
10720       } else {
10721         assert(VT == MVT::v16i8);
10722         Opc = X86ISD::PINSRB;
10723       }
10724
10725       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10726       // argument.
10727       if (N1.getValueType() != MVT::i32)
10728         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10729       if (N2.getValueType() != MVT::i32)
10730         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10731       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10732     }
10733
10734     if (EltVT == MVT::f32) {
10735       // Bits [7:6] of the constant are the source select. This will always be
10736       //   zero here. The DAG Combiner may combine an extract_elt index into
10737       //   these bits. For example (insert (extract, 3), 2) could be matched by
10738       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10739       // Bits [5:4] of the constant are the destination select. This is the
10740       //   value of the incoming immediate.
10741       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10742       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10743
10744       const Function *F = DAG.getMachineFunction().getFunction();
10745       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10746       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10747         // If this is an insertion of 32-bits into the low 32-bits of
10748         // a vector, we prefer to generate a blend with immediate rather
10749         // than an insertps. Blends are simpler operations in hardware and so
10750         // will always have equal or better performance than insertps.
10751         // But if optimizing for size and there's a load folding opportunity,
10752         // generate insertps because blendps does not have a 32-bit memory
10753         // operand form.
10754         N2 = DAG.getIntPtrConstant(1, dl);
10755         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10756         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10757       }
10758       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10759       // Create this as a scalar to vector..
10760       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10761       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10762     }
10763
10764     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10765       // PINSR* works with constant index.
10766       return Op;
10767     }
10768   }
10769
10770   if (EltVT == MVT::i8)
10771     return SDValue();
10772
10773   if (EltVT.getSizeInBits() == 16) {
10774     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10775     // as its second argument.
10776     if (N1.getValueType() != MVT::i32)
10777       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10778     if (N2.getValueType() != MVT::i32)
10779       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10780     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10781   }
10782   return SDValue();
10783 }
10784
10785 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10786   SDLoc dl(Op);
10787   MVT OpVT = Op.getSimpleValueType();
10788
10789   // If this is a 256-bit vector result, first insert into a 128-bit
10790   // vector and then insert into the 256-bit vector.
10791   if (!OpVT.is128BitVector()) {
10792     // Insert into a 128-bit vector.
10793     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10794     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10795                                  OpVT.getVectorNumElements() / SizeFactor);
10796
10797     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10798
10799     // Insert the 128-bit vector.
10800     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10801   }
10802
10803   if (OpVT == MVT::v1i64 &&
10804       Op.getOperand(0).getValueType() == MVT::i64)
10805     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10806
10807   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10808   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10809   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10810                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10811 }
10812
10813 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10814 // a simple subregister reference or explicit instructions to grab
10815 // upper bits of a vector.
10816 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10817                                       SelectionDAG &DAG) {
10818   SDLoc dl(Op);
10819   SDValue In =  Op.getOperand(0);
10820   SDValue Idx = Op.getOperand(1);
10821   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10822   MVT ResVT   = Op.getSimpleValueType();
10823   MVT InVT    = In.getSimpleValueType();
10824
10825   if (Subtarget->hasFp256()) {
10826     if (ResVT.is128BitVector() &&
10827         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10828         isa<ConstantSDNode>(Idx)) {
10829       return Extract128BitVector(In, IdxVal, DAG, dl);
10830     }
10831     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10832         isa<ConstantSDNode>(Idx)) {
10833       return Extract256BitVector(In, IdxVal, DAG, dl);
10834     }
10835   }
10836   return SDValue();
10837 }
10838
10839 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10840 // simple superregister reference or explicit instructions to insert
10841 // the upper bits of a vector.
10842 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10843                                      SelectionDAG &DAG) {
10844   if (!Subtarget->hasAVX())
10845     return SDValue();
10846
10847   SDLoc dl(Op);
10848   SDValue Vec = Op.getOperand(0);
10849   SDValue SubVec = Op.getOperand(1);
10850   SDValue Idx = Op.getOperand(2);
10851
10852   if (!isa<ConstantSDNode>(Idx))
10853     return SDValue();
10854
10855   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10856   MVT OpVT = Op.getSimpleValueType();
10857   MVT SubVecVT = SubVec.getSimpleValueType();
10858
10859   // Fold two 16-byte subvector loads into one 32-byte load:
10860   // (insert_subvector (insert_subvector undef, (load addr), 0),
10861   //                   (load addr + 16), Elts/2)
10862   // --> load32 addr
10863   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10864       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10865       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10866       !Subtarget->isUnalignedMem32Slow()) {
10867     SDValue SubVec2 = Vec.getOperand(1);
10868     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10869       if (Idx2->getZExtValue() == 0) {
10870         SDValue Ops[] = { SubVec2, SubVec };
10871         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10872         if (LD.getNode())
10873           return LD;
10874       }
10875     }
10876   }
10877
10878   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10879       SubVecVT.is128BitVector())
10880     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10881
10882   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10883     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10884
10885   if (OpVT.getVectorElementType() == MVT::i1) {
10886     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10887       return Op;
10888     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10889     SDValue Undef = DAG.getUNDEF(OpVT);
10890     unsigned NumElems = OpVT.getVectorNumElements();
10891     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10892
10893     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10894       // Zero upper bits of the Vec
10895       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10896       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10897
10898       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10899                                  SubVec, ZeroIdx);
10900       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10901       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10902     }
10903     if (IdxVal == 0) {
10904       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10905                                  SubVec, ZeroIdx);
10906       // Zero upper bits of the Vec2
10907       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10908       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10909       // Zero lower bits of the Vec
10910       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10911       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10912       // Merge them together
10913       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10914     }
10915   }
10916   return SDValue();
10917 }
10918
10919 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10920 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10921 // one of the above mentioned nodes. It has to be wrapped because otherwise
10922 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10923 // be used to form addressing mode. These wrapped nodes will be selected
10924 // into MOV32ri.
10925 SDValue
10926 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10927   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10928
10929   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10930   // global base reg.
10931   unsigned char OpFlag = 0;
10932   unsigned WrapperKind = X86ISD::Wrapper;
10933   CodeModel::Model M = DAG.getTarget().getCodeModel();
10934
10935   if (Subtarget->isPICStyleRIPRel() &&
10936       (M == CodeModel::Small || M == CodeModel::Kernel))
10937     WrapperKind = X86ISD::WrapperRIP;
10938   else if (Subtarget->isPICStyleGOT())
10939     OpFlag = X86II::MO_GOTOFF;
10940   else if (Subtarget->isPICStyleStubPIC())
10941     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10942
10943   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10944                                              CP->getAlignment(),
10945                                              CP->getOffset(), OpFlag);
10946   SDLoc DL(CP);
10947   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10948   // With PIC, the address is actually $g + Offset.
10949   if (OpFlag) {
10950     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10951                          DAG.getNode(X86ISD::GlobalBaseReg,
10952                                      SDLoc(), getPointerTy()),
10953                          Result);
10954   }
10955
10956   return Result;
10957 }
10958
10959 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10960   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10961
10962   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10963   // global base reg.
10964   unsigned char OpFlag = 0;
10965   unsigned WrapperKind = X86ISD::Wrapper;
10966   CodeModel::Model M = DAG.getTarget().getCodeModel();
10967
10968   if (Subtarget->isPICStyleRIPRel() &&
10969       (M == CodeModel::Small || M == CodeModel::Kernel))
10970     WrapperKind = X86ISD::WrapperRIP;
10971   else if (Subtarget->isPICStyleGOT())
10972     OpFlag = X86II::MO_GOTOFF;
10973   else if (Subtarget->isPICStyleStubPIC())
10974     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10975
10976   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10977                                           OpFlag);
10978   SDLoc DL(JT);
10979   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10980
10981   // With PIC, the address is actually $g + Offset.
10982   if (OpFlag)
10983     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10984                          DAG.getNode(X86ISD::GlobalBaseReg,
10985                                      SDLoc(), getPointerTy()),
10986                          Result);
10987
10988   return Result;
10989 }
10990
10991 SDValue
10992 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10993   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10994
10995   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10996   // global base reg.
10997   unsigned char OpFlag = 0;
10998   unsigned WrapperKind = X86ISD::Wrapper;
10999   CodeModel::Model M = DAG.getTarget().getCodeModel();
11000
11001   if (Subtarget->isPICStyleRIPRel() &&
11002       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11003     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11004       OpFlag = X86II::MO_GOTPCREL;
11005     WrapperKind = X86ISD::WrapperRIP;
11006   } else if (Subtarget->isPICStyleGOT()) {
11007     OpFlag = X86II::MO_GOT;
11008   } else if (Subtarget->isPICStyleStubPIC()) {
11009     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11010   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11011     OpFlag = X86II::MO_DARWIN_NONLAZY;
11012   }
11013
11014   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11015
11016   SDLoc DL(Op);
11017   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11018
11019   // With PIC, the address is actually $g + Offset.
11020   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11021       !Subtarget->is64Bit()) {
11022     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11023                          DAG.getNode(X86ISD::GlobalBaseReg,
11024                                      SDLoc(), getPointerTy()),
11025                          Result);
11026   }
11027
11028   // For symbols that require a load from a stub to get the address, emit the
11029   // load.
11030   if (isGlobalStubReference(OpFlag))
11031     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11032                          MachinePointerInfo::getGOT(), false, false, false, 0);
11033
11034   return Result;
11035 }
11036
11037 SDValue
11038 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11039   // Create the TargetBlockAddressAddress node.
11040   unsigned char OpFlags =
11041     Subtarget->ClassifyBlockAddressReference();
11042   CodeModel::Model M = DAG.getTarget().getCodeModel();
11043   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11044   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11045   SDLoc dl(Op);
11046   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11047                                              OpFlags);
11048
11049   if (Subtarget->isPICStyleRIPRel() &&
11050       (M == CodeModel::Small || M == CodeModel::Kernel))
11051     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11052   else
11053     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11054
11055   // With PIC, the address is actually $g + Offset.
11056   if (isGlobalRelativeToPICBase(OpFlags)) {
11057     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11058                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11059                          Result);
11060   }
11061
11062   return Result;
11063 }
11064
11065 SDValue
11066 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11067                                       int64_t Offset, SelectionDAG &DAG) const {
11068   // Create the TargetGlobalAddress node, folding in the constant
11069   // offset if it is legal.
11070   unsigned char OpFlags =
11071       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11072   CodeModel::Model M = DAG.getTarget().getCodeModel();
11073   SDValue Result;
11074   if (OpFlags == X86II::MO_NO_FLAG &&
11075       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11076     // A direct static reference to a global.
11077     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11078     Offset = 0;
11079   } else {
11080     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11081   }
11082
11083   if (Subtarget->isPICStyleRIPRel() &&
11084       (M == CodeModel::Small || M == CodeModel::Kernel))
11085     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11086   else
11087     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11088
11089   // With PIC, the address is actually $g + Offset.
11090   if (isGlobalRelativeToPICBase(OpFlags)) {
11091     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11092                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11093                          Result);
11094   }
11095
11096   // For globals that require a load from a stub to get the address, emit the
11097   // load.
11098   if (isGlobalStubReference(OpFlags))
11099     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11100                          MachinePointerInfo::getGOT(), false, false, false, 0);
11101
11102   // If there was a non-zero offset that we didn't fold, create an explicit
11103   // addition for it.
11104   if (Offset != 0)
11105     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11106                          DAG.getConstant(Offset, dl, getPointerTy()));
11107
11108   return Result;
11109 }
11110
11111 SDValue
11112 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11113   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11114   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11115   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11116 }
11117
11118 static SDValue
11119 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11120            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11121            unsigned char OperandFlags, bool LocalDynamic = false) {
11122   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11123   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11124   SDLoc dl(GA);
11125   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11126                                            GA->getValueType(0),
11127                                            GA->getOffset(),
11128                                            OperandFlags);
11129
11130   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11131                                            : X86ISD::TLSADDR;
11132
11133   if (InFlag) {
11134     SDValue Ops[] = { Chain,  TGA, *InFlag };
11135     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11136   } else {
11137     SDValue Ops[]  = { Chain, TGA };
11138     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11139   }
11140
11141   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11142   MFI->setAdjustsStack(true);
11143   MFI->setHasCalls(true);
11144
11145   SDValue Flag = Chain.getValue(1);
11146   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11147 }
11148
11149 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11150 static SDValue
11151 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11152                                 const EVT PtrVT) {
11153   SDValue InFlag;
11154   SDLoc dl(GA);  // ? function entry point might be better
11155   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11156                                    DAG.getNode(X86ISD::GlobalBaseReg,
11157                                                SDLoc(), PtrVT), InFlag);
11158   InFlag = Chain.getValue(1);
11159
11160   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11161 }
11162
11163 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11164 static SDValue
11165 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11166                                 const EVT PtrVT) {
11167   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11168                     X86::RAX, X86II::MO_TLSGD);
11169 }
11170
11171 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11172                                            SelectionDAG &DAG,
11173                                            const EVT PtrVT,
11174                                            bool is64Bit) {
11175   SDLoc dl(GA);
11176
11177   // Get the start address of the TLS block for this module.
11178   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11179       .getInfo<X86MachineFunctionInfo>();
11180   MFI->incNumLocalDynamicTLSAccesses();
11181
11182   SDValue Base;
11183   if (is64Bit) {
11184     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11185                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11186   } else {
11187     SDValue InFlag;
11188     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11189         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11190     InFlag = Chain.getValue(1);
11191     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11192                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11193   }
11194
11195   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11196   // of Base.
11197
11198   // Build x@dtpoff.
11199   unsigned char OperandFlags = X86II::MO_DTPOFF;
11200   unsigned WrapperKind = X86ISD::Wrapper;
11201   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11202                                            GA->getValueType(0),
11203                                            GA->getOffset(), OperandFlags);
11204   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11205
11206   // Add x@dtpoff with the base.
11207   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11208 }
11209
11210 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11211 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11212                                    const EVT PtrVT, TLSModel::Model model,
11213                                    bool is64Bit, bool isPIC) {
11214   SDLoc dl(GA);
11215
11216   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11217   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11218                                                          is64Bit ? 257 : 256));
11219
11220   SDValue ThreadPointer =
11221       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11222                   MachinePointerInfo(Ptr), false, false, false, 0);
11223
11224   unsigned char OperandFlags = 0;
11225   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11226   // initialexec.
11227   unsigned WrapperKind = X86ISD::Wrapper;
11228   if (model == TLSModel::LocalExec) {
11229     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11230   } else if (model == TLSModel::InitialExec) {
11231     if (is64Bit) {
11232       OperandFlags = X86II::MO_GOTTPOFF;
11233       WrapperKind = X86ISD::WrapperRIP;
11234     } else {
11235       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11236     }
11237   } else {
11238     llvm_unreachable("Unexpected model");
11239   }
11240
11241   // emit "addl x@ntpoff,%eax" (local exec)
11242   // or "addl x@indntpoff,%eax" (initial exec)
11243   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11244   SDValue TGA =
11245       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11246                                  GA->getOffset(), OperandFlags);
11247   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11248
11249   if (model == TLSModel::InitialExec) {
11250     if (isPIC && !is64Bit) {
11251       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11252                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11253                            Offset);
11254     }
11255
11256     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11257                          MachinePointerInfo::getGOT(), false, false, false, 0);
11258   }
11259
11260   // The address of the thread local variable is the add of the thread
11261   // pointer with the offset of the variable.
11262   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11263 }
11264
11265 SDValue
11266 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11267
11268   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11269   const GlobalValue *GV = GA->getGlobal();
11270
11271   if (Subtarget->isTargetELF()) {
11272     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11273
11274     switch (model) {
11275       case TLSModel::GeneralDynamic:
11276         if (Subtarget->is64Bit())
11277           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11278         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11279       case TLSModel::LocalDynamic:
11280         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11281                                            Subtarget->is64Bit());
11282       case TLSModel::InitialExec:
11283       case TLSModel::LocalExec:
11284         return LowerToTLSExecModel(
11285             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11286             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11287     }
11288     llvm_unreachable("Unknown TLS model.");
11289   }
11290
11291   if (Subtarget->isTargetDarwin()) {
11292     // Darwin only has one model of TLS.  Lower to that.
11293     unsigned char OpFlag = 0;
11294     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11295                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11296
11297     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11298     // global base reg.
11299     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11300                  !Subtarget->is64Bit();
11301     if (PIC32)
11302       OpFlag = X86II::MO_TLVP_PIC_BASE;
11303     else
11304       OpFlag = X86II::MO_TLVP;
11305     SDLoc DL(Op);
11306     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11307                                                 GA->getValueType(0),
11308                                                 GA->getOffset(), OpFlag);
11309     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11310
11311     // With PIC32, the address is actually $g + Offset.
11312     if (PIC32)
11313       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11314                            DAG.getNode(X86ISD::GlobalBaseReg,
11315                                        SDLoc(), getPointerTy()),
11316                            Offset);
11317
11318     // Lowering the machine isd will make sure everything is in the right
11319     // location.
11320     SDValue Chain = DAG.getEntryNode();
11321     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11322     SDValue Args[] = { Chain, Offset };
11323     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11324
11325     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11326     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11327     MFI->setAdjustsStack(true);
11328
11329     // And our return value (tls address) is in the standard call return value
11330     // location.
11331     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11332     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11333                               Chain.getValue(1));
11334   }
11335
11336   if (Subtarget->isTargetKnownWindowsMSVC() ||
11337       Subtarget->isTargetWindowsGNU()) {
11338     // Just use the implicit TLS architecture
11339     // Need to generate someting similar to:
11340     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11341     //                                  ; from TEB
11342     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11343     //   mov     rcx, qword [rdx+rcx*8]
11344     //   mov     eax, .tls$:tlsvar
11345     //   [rax+rcx] contains the address
11346     // Windows 64bit: gs:0x58
11347     // Windows 32bit: fs:__tls_array
11348
11349     SDLoc dl(GA);
11350     SDValue Chain = DAG.getEntryNode();
11351
11352     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11353     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11354     // use its literal value of 0x2C.
11355     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11356                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11357                                                              256)
11358                                         : Type::getInt32PtrTy(*DAG.getContext(),
11359                                                               257));
11360
11361     SDValue TlsArray =
11362         Subtarget->is64Bit()
11363             ? DAG.getIntPtrConstant(0x58, dl)
11364             : (Subtarget->isTargetWindowsGNU()
11365                    ? DAG.getIntPtrConstant(0x2C, dl)
11366                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11367
11368     SDValue ThreadPointer =
11369         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11370                     MachinePointerInfo(Ptr), false, false, false, 0);
11371
11372     // Load the _tls_index variable
11373     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11374     if (Subtarget->is64Bit())
11375       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11376                            IDX, MachinePointerInfo(), MVT::i32,
11377                            false, false, false, 0);
11378     else
11379       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11380                         false, false, false, 0);
11381
11382     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11383                                     getPointerTy());
11384     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11385
11386     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11387     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11388                       false, false, false, 0);
11389
11390     // Get the offset of start of .tls section
11391     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11392                                              GA->getValueType(0),
11393                                              GA->getOffset(), X86II::MO_SECREL);
11394     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11395
11396     // The address of the thread local variable is the add of the thread
11397     // pointer with the offset of the variable.
11398     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11399   }
11400
11401   llvm_unreachable("TLS not implemented for this target.");
11402 }
11403
11404 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11405 /// and take a 2 x i32 value to shift plus a shift amount.
11406 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11407   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11408   MVT VT = Op.getSimpleValueType();
11409   unsigned VTBits = VT.getSizeInBits();
11410   SDLoc dl(Op);
11411   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11412   SDValue ShOpLo = Op.getOperand(0);
11413   SDValue ShOpHi = Op.getOperand(1);
11414   SDValue ShAmt  = Op.getOperand(2);
11415   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11416   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11417   // during isel.
11418   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11419                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11420   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11421                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11422                        : DAG.getConstant(0, dl, VT);
11423
11424   SDValue Tmp2, Tmp3;
11425   if (Op.getOpcode() == ISD::SHL_PARTS) {
11426     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11427     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11428   } else {
11429     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11430     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11431   }
11432
11433   // If the shift amount is larger or equal than the width of a part we can't
11434   // rely on the results of shld/shrd. Insert a test and select the appropriate
11435   // values for large shift amounts.
11436   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11437                                 DAG.getConstant(VTBits, dl, MVT::i8));
11438   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11439                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11440
11441   SDValue Hi, Lo;
11442   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11443   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11444   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11445
11446   if (Op.getOpcode() == ISD::SHL_PARTS) {
11447     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11448     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11449   } else {
11450     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11451     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11452   }
11453
11454   SDValue Ops[2] = { Lo, Hi };
11455   return DAG.getMergeValues(Ops, dl);
11456 }
11457
11458 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11459                                            SelectionDAG &DAG) const {
11460   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11461   SDLoc dl(Op);
11462
11463   if (SrcVT.isVector()) {
11464     if (SrcVT.getVectorElementType() == MVT::i1) {
11465       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11466       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11467                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11468                                      Op.getOperand(0)));
11469     }
11470     return SDValue();
11471   }
11472
11473   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11474          "Unknown SINT_TO_FP to lower!");
11475
11476   // These are really Legal; return the operand so the caller accepts it as
11477   // Legal.
11478   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11479     return Op;
11480   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11481       Subtarget->is64Bit()) {
11482     return Op;
11483   }
11484
11485   unsigned Size = SrcVT.getSizeInBits()/8;
11486   MachineFunction &MF = DAG.getMachineFunction();
11487   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11488   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11489   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11490                                StackSlot,
11491                                MachinePointerInfo::getFixedStack(SSFI),
11492                                false, false, 0);
11493   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11494 }
11495
11496 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11497                                      SDValue StackSlot,
11498                                      SelectionDAG &DAG) const {
11499   // Build the FILD
11500   SDLoc DL(Op);
11501   SDVTList Tys;
11502   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11503   if (useSSE)
11504     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11505   else
11506     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11507
11508   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11509
11510   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11511   MachineMemOperand *MMO;
11512   if (FI) {
11513     int SSFI = FI->getIndex();
11514     MMO =
11515       DAG.getMachineFunction()
11516       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11517                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11518   } else {
11519     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11520     StackSlot = StackSlot.getOperand(1);
11521   }
11522   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11523   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11524                                            X86ISD::FILD, DL,
11525                                            Tys, Ops, SrcVT, MMO);
11526
11527   if (useSSE) {
11528     Chain = Result.getValue(1);
11529     SDValue InFlag = Result.getValue(2);
11530
11531     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11532     // shouldn't be necessary except that RFP cannot be live across
11533     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11534     MachineFunction &MF = DAG.getMachineFunction();
11535     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11536     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11537     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11538     Tys = DAG.getVTList(MVT::Other);
11539     SDValue Ops[] = {
11540       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11541     };
11542     MachineMemOperand *MMO =
11543       DAG.getMachineFunction()
11544       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11545                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11546
11547     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11548                                     Ops, Op.getValueType(), MMO);
11549     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11550                          MachinePointerInfo::getFixedStack(SSFI),
11551                          false, false, false, 0);
11552   }
11553
11554   return Result;
11555 }
11556
11557 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11558 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11559                                                SelectionDAG &DAG) const {
11560   // This algorithm is not obvious. Here it is what we're trying to output:
11561   /*
11562      movq       %rax,  %xmm0
11563      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11564      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11565      #ifdef __SSE3__
11566        haddpd   %xmm0, %xmm0
11567      #else
11568        pshufd   $0x4e, %xmm0, %xmm1
11569        addpd    %xmm1, %xmm0
11570      #endif
11571   */
11572
11573   SDLoc dl(Op);
11574   LLVMContext *Context = DAG.getContext();
11575
11576   // Build some magic constants.
11577   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11578   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11579   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11580
11581   SmallVector<Constant*,2> CV1;
11582   CV1.push_back(
11583     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11584                                       APInt(64, 0x4330000000000000ULL))));
11585   CV1.push_back(
11586     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11587                                       APInt(64, 0x4530000000000000ULL))));
11588   Constant *C1 = ConstantVector::get(CV1);
11589   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11590
11591   // Load the 64-bit value into an XMM register.
11592   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11593                             Op.getOperand(0));
11594   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11595                               MachinePointerInfo::getConstantPool(),
11596                               false, false, false, 16);
11597   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11598                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11599                               CLod0);
11600
11601   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11602                               MachinePointerInfo::getConstantPool(),
11603                               false, false, false, 16);
11604   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11605   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11606   SDValue Result;
11607
11608   if (Subtarget->hasSSE3()) {
11609     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11610     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11611   } else {
11612     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11613     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11614                                            S2F, 0x4E, DAG);
11615     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11616                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11617                          Sub);
11618   }
11619
11620   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11621                      DAG.getIntPtrConstant(0, dl));
11622 }
11623
11624 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11625 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11626                                                SelectionDAG &DAG) const {
11627   SDLoc dl(Op);
11628   // FP constant to bias correct the final result.
11629   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11630                                    MVT::f64);
11631
11632   // Load the 32-bit value into an XMM register.
11633   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11634                              Op.getOperand(0));
11635
11636   // Zero out the upper parts of the register.
11637   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11638
11639   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11640                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11641                      DAG.getIntPtrConstant(0, dl));
11642
11643   // Or the load with the bias.
11644   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11645                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11646                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11647                                                    MVT::v2f64, Load)),
11648                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11649                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11650                                                    MVT::v2f64, Bias)));
11651   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11652                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11653                    DAG.getIntPtrConstant(0, dl));
11654
11655   // Subtract the bias.
11656   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11657
11658   // Handle final rounding.
11659   EVT DestVT = Op.getValueType();
11660
11661   if (DestVT.bitsLT(MVT::f64))
11662     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11663                        DAG.getIntPtrConstant(0, dl));
11664   if (DestVT.bitsGT(MVT::f64))
11665     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11666
11667   // Handle final rounding.
11668   return Sub;
11669 }
11670
11671 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11672                                      const X86Subtarget &Subtarget) {
11673   // The algorithm is the following:
11674   // #ifdef __SSE4_1__
11675   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11676   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11677   //                                 (uint4) 0x53000000, 0xaa);
11678   // #else
11679   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11680   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11681   // #endif
11682   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11683   //     return (float4) lo + fhi;
11684
11685   SDLoc DL(Op);
11686   SDValue V = Op->getOperand(0);
11687   EVT VecIntVT = V.getValueType();
11688   bool Is128 = VecIntVT == MVT::v4i32;
11689   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11690   // If we convert to something else than the supported type, e.g., to v4f64,
11691   // abort early.
11692   if (VecFloatVT != Op->getValueType(0))
11693     return SDValue();
11694
11695   unsigned NumElts = VecIntVT.getVectorNumElements();
11696   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11697          "Unsupported custom type");
11698   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11699
11700   // In the #idef/#else code, we have in common:
11701   // - The vector of constants:
11702   // -- 0x4b000000
11703   // -- 0x53000000
11704   // - A shift:
11705   // -- v >> 16
11706
11707   // Create the splat vector for 0x4b000000.
11708   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11709   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11710                            CstLow, CstLow, CstLow, CstLow};
11711   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11712                                   makeArrayRef(&CstLowArray[0], NumElts));
11713   // Create the splat vector for 0x53000000.
11714   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11715   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11716                             CstHigh, CstHigh, CstHigh, CstHigh};
11717   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11718                                    makeArrayRef(&CstHighArray[0], NumElts));
11719
11720   // Create the right shift.
11721   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11722   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11723                              CstShift, CstShift, CstShift, CstShift};
11724   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11725                                     makeArrayRef(&CstShiftArray[0], NumElts));
11726   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11727
11728   SDValue Low, High;
11729   if (Subtarget.hasSSE41()) {
11730     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11731     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11732     SDValue VecCstLowBitcast =
11733         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11734     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11735     // Low will be bitcasted right away, so do not bother bitcasting back to its
11736     // original type.
11737     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11738                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11739     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11740     //                                 (uint4) 0x53000000, 0xaa);
11741     SDValue VecCstHighBitcast =
11742         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11743     SDValue VecShiftBitcast =
11744         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11745     // High will be bitcasted right away, so do not bother bitcasting back to
11746     // its original type.
11747     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11748                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11749   } else {
11750     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11751     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11752                                      CstMask, CstMask, CstMask);
11753     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11754     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11755     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11756
11757     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11758     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11759   }
11760
11761   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11762   SDValue CstFAdd = DAG.getConstantFP(
11763       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11764   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11765                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11766   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11767                                    makeArrayRef(&CstFAddArray[0], NumElts));
11768
11769   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11770   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11771   SDValue FHigh =
11772       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11773   //     return (float4) lo + fhi;
11774   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11775   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11776 }
11777
11778 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11779                                                SelectionDAG &DAG) const {
11780   SDValue N0 = Op.getOperand(0);
11781   MVT SVT = N0.getSimpleValueType();
11782   SDLoc dl(Op);
11783
11784   switch (SVT.SimpleTy) {
11785   default:
11786     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11787   case MVT::v4i8:
11788   case MVT::v4i16:
11789   case MVT::v8i8:
11790   case MVT::v8i16: {
11791     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11792     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11793                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11794   }
11795   case MVT::v4i32:
11796   case MVT::v8i32:
11797     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11798   case MVT::v16i8:
11799   case MVT::v16i16:
11800     if (Subtarget->hasAVX512())
11801       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11802                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11803   }
11804   llvm_unreachable(nullptr);
11805 }
11806
11807 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11808                                            SelectionDAG &DAG) const {
11809   SDValue N0 = Op.getOperand(0);
11810   SDLoc dl(Op);
11811
11812   if (Op.getValueType().isVector())
11813     return lowerUINT_TO_FP_vec(Op, DAG);
11814
11815   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11816   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11817   // the optimization here.
11818   if (DAG.SignBitIsZero(N0))
11819     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11820
11821   MVT SrcVT = N0.getSimpleValueType();
11822   MVT DstVT = Op.getSimpleValueType();
11823   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11824     return LowerUINT_TO_FP_i64(Op, DAG);
11825   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11826     return LowerUINT_TO_FP_i32(Op, DAG);
11827   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11828     return SDValue();
11829
11830   // Make a 64-bit buffer, and use it to build an FILD.
11831   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11832   if (SrcVT == MVT::i32) {
11833     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11834     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11835                                      getPointerTy(), StackSlot, WordOff);
11836     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11837                                   StackSlot, MachinePointerInfo(),
11838                                   false, false, 0);
11839     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11840                                   OffsetSlot, MachinePointerInfo(),
11841                                   false, false, 0);
11842     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11843     return Fild;
11844   }
11845
11846   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11847   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11848                                StackSlot, MachinePointerInfo(),
11849                                false, false, 0);
11850   // For i64 source, we need to add the appropriate power of 2 if the input
11851   // was negative.  This is the same as the optimization in
11852   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11853   // we must be careful to do the computation in x87 extended precision, not
11854   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11855   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11856   MachineMemOperand *MMO =
11857     DAG.getMachineFunction()
11858     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11859                           MachineMemOperand::MOLoad, 8, 8);
11860
11861   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11862   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11863   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11864                                          MVT::i64, MMO);
11865
11866   APInt FF(32, 0x5F800000ULL);
11867
11868   // Check whether the sign bit is set.
11869   SDValue SignSet = DAG.getSetCC(dl,
11870                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11871                                  Op.getOperand(0),
11872                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11873
11874   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11875   SDValue FudgePtr = DAG.getConstantPool(
11876                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11877                                          getPointerTy());
11878
11879   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11880   SDValue Zero = DAG.getIntPtrConstant(0, dl);
11881   SDValue Four = DAG.getIntPtrConstant(4, dl);
11882   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11883                                Zero, Four);
11884   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11885
11886   // Load the value out, extending it from f32 to f80.
11887   // FIXME: Avoid the extend by constructing the right constant pool?
11888   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11889                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11890                                  MVT::f32, false, false, false, 4);
11891   // Extend everything to 80 bits to force it to be done on x87.
11892   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11893   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11894                      DAG.getIntPtrConstant(0, dl));
11895 }
11896
11897 std::pair<SDValue,SDValue>
11898 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11899                                     bool IsSigned, bool IsReplace) const {
11900   SDLoc DL(Op);
11901
11902   EVT DstTy = Op.getValueType();
11903
11904   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11905     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11906     DstTy = MVT::i64;
11907   }
11908
11909   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11910          DstTy.getSimpleVT() >= MVT::i16 &&
11911          "Unknown FP_TO_INT to lower!");
11912
11913   // These are really Legal.
11914   if (DstTy == MVT::i32 &&
11915       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11916     return std::make_pair(SDValue(), SDValue());
11917   if (Subtarget->is64Bit() &&
11918       DstTy == MVT::i64 &&
11919       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11920     return std::make_pair(SDValue(), SDValue());
11921
11922   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11923   // stack slot, or into the FTOL runtime function.
11924   MachineFunction &MF = DAG.getMachineFunction();
11925   unsigned MemSize = DstTy.getSizeInBits()/8;
11926   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11927   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11928
11929   unsigned Opc;
11930   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11931     Opc = X86ISD::WIN_FTOL;
11932   else
11933     switch (DstTy.getSimpleVT().SimpleTy) {
11934     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11935     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11936     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11937     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11938     }
11939
11940   SDValue Chain = DAG.getEntryNode();
11941   SDValue Value = Op.getOperand(0);
11942   EVT TheVT = Op.getOperand(0).getValueType();
11943   // FIXME This causes a redundant load/store if the SSE-class value is already
11944   // in memory, such as if it is on the callstack.
11945   if (isScalarFPTypeInSSEReg(TheVT)) {
11946     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11947     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11948                          MachinePointerInfo::getFixedStack(SSFI),
11949                          false, false, 0);
11950     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11951     SDValue Ops[] = {
11952       Chain, StackSlot, DAG.getValueType(TheVT)
11953     };
11954
11955     MachineMemOperand *MMO =
11956       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11957                               MachineMemOperand::MOLoad, MemSize, MemSize);
11958     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11959     Chain = Value.getValue(1);
11960     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11961     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11962   }
11963
11964   MachineMemOperand *MMO =
11965     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11966                             MachineMemOperand::MOStore, MemSize, MemSize);
11967
11968   if (Opc != X86ISD::WIN_FTOL) {
11969     // Build the FP_TO_INT*_IN_MEM
11970     SDValue Ops[] = { Chain, Value, StackSlot };
11971     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11972                                            Ops, DstTy, MMO);
11973     return std::make_pair(FIST, StackSlot);
11974   } else {
11975     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11976       DAG.getVTList(MVT::Other, MVT::Glue),
11977       Chain, Value);
11978     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11979       MVT::i32, ftol.getValue(1));
11980     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11981       MVT::i32, eax.getValue(2));
11982     SDValue Ops[] = { eax, edx };
11983     SDValue pair = IsReplace
11984       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11985       : DAG.getMergeValues(Ops, DL);
11986     return std::make_pair(pair, SDValue());
11987   }
11988 }
11989
11990 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11991                               const X86Subtarget *Subtarget) {
11992   MVT VT = Op->getSimpleValueType(0);
11993   SDValue In = Op->getOperand(0);
11994   MVT InVT = In.getSimpleValueType();
11995   SDLoc dl(Op);
11996
11997   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
11998     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
11999
12000   // Optimize vectors in AVX mode:
12001   //
12002   //   v8i16 -> v8i32
12003   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12004   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12005   //   Concat upper and lower parts.
12006   //
12007   //   v4i32 -> v4i64
12008   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12009   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12010   //   Concat upper and lower parts.
12011   //
12012
12013   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12014       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12015       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12016     return SDValue();
12017
12018   if (Subtarget->hasInt256())
12019     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12020
12021   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12022   SDValue Undef = DAG.getUNDEF(InVT);
12023   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12024   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12025   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12026
12027   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12028                              VT.getVectorNumElements()/2);
12029
12030   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12031   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12032
12033   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12034 }
12035
12036 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12037                                         SelectionDAG &DAG) {
12038   MVT VT = Op->getSimpleValueType(0);
12039   SDValue In = Op->getOperand(0);
12040   MVT InVT = In.getSimpleValueType();
12041   SDLoc DL(Op);
12042   unsigned int NumElts = VT.getVectorNumElements();
12043   if (NumElts != 8 && NumElts != 16)
12044     return SDValue();
12045
12046   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12047     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12048
12049   assert(InVT.getVectorElementType() == MVT::i1);
12050   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12051   SDValue One =
12052    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12053   SDValue Zero =
12054    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12055
12056   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12057   if (VT.is512BitVector())
12058     return V;
12059   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12060 }
12061
12062 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12063                                SelectionDAG &DAG) {
12064   if (Subtarget->hasFp256()) {
12065     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12066     if (Res.getNode())
12067       return Res;
12068   }
12069
12070   return SDValue();
12071 }
12072
12073 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12074                                 SelectionDAG &DAG) {
12075   SDLoc DL(Op);
12076   MVT VT = Op.getSimpleValueType();
12077   SDValue In = Op.getOperand(0);
12078   MVT SVT = In.getSimpleValueType();
12079
12080   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12081     return LowerZERO_EXTEND_AVX512(Op, DAG);
12082
12083   if (Subtarget->hasFp256()) {
12084     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12085     if (Res.getNode())
12086       return Res;
12087   }
12088
12089   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12090          VT.getVectorNumElements() != SVT.getVectorNumElements());
12091   return SDValue();
12092 }
12093
12094 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12095   SDLoc DL(Op);
12096   MVT VT = Op.getSimpleValueType();
12097   SDValue In = Op.getOperand(0);
12098   MVT InVT = In.getSimpleValueType();
12099
12100   if (VT == MVT::i1) {
12101     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12102            "Invalid scalar TRUNCATE operation");
12103     if (InVT.getSizeInBits() >= 32)
12104       return SDValue();
12105     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12106     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12107   }
12108   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12109          "Invalid TRUNCATE operation");
12110
12111   // move vector to mask - truncate solution for SKX
12112   if (VT.getVectorElementType() == MVT::i1) {
12113     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12114         Subtarget->hasBWI())
12115       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12116     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12117         && InVT.getScalarSizeInBits() <= 16 &&
12118         Subtarget->hasBWI() && Subtarget->hasVLX())
12119       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12120     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12121         Subtarget->hasDQI())
12122       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12123     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12124         && InVT.getScalarSizeInBits() >= 32 &&
12125         Subtarget->hasDQI() && Subtarget->hasVLX())
12126       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12127   }
12128   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12129     if (VT.getVectorElementType().getSizeInBits() >=8)
12130       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12131
12132     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12133     unsigned NumElts = InVT.getVectorNumElements();
12134     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12135     if (InVT.getSizeInBits() < 512) {
12136       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12137       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12138       InVT = ExtVT;
12139     }
12140
12141     SDValue OneV =
12142      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12143     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12144     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12145   }
12146
12147   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12148     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12149     if (Subtarget->hasInt256()) {
12150       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12151       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12152       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12153                                 ShufMask);
12154       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12155                          DAG.getIntPtrConstant(0, DL));
12156     }
12157
12158     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12159                                DAG.getIntPtrConstant(0, DL));
12160     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12161                                DAG.getIntPtrConstant(2, DL));
12162     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12163     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12164     static const int ShufMask[] = {0, 2, 4, 6};
12165     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12166   }
12167
12168   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12169     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12170     if (Subtarget->hasInt256()) {
12171       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12172
12173       SmallVector<SDValue,32> pshufbMask;
12174       for (unsigned i = 0; i < 2; ++i) {
12175         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12176         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12177         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12178         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12179         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12180         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12181         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12182         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12183         for (unsigned j = 0; j < 8; ++j)
12184           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12185       }
12186       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12187       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12188       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12189
12190       static const int ShufMask[] = {0,  2,  -1,  -1};
12191       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12192                                 &ShufMask[0]);
12193       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12194                        DAG.getIntPtrConstant(0, DL));
12195       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12196     }
12197
12198     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12199                                DAG.getIntPtrConstant(0, DL));
12200
12201     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12202                                DAG.getIntPtrConstant(4, DL));
12203
12204     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12205     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12206
12207     // The PSHUFB mask:
12208     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12209                                    -1, -1, -1, -1, -1, -1, -1, -1};
12210
12211     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12212     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12213     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12214
12215     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12216     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12217
12218     // The MOVLHPS Mask:
12219     static const int ShufMask2[] = {0, 1, 4, 5};
12220     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12221     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12222   }
12223
12224   // Handle truncation of V256 to V128 using shuffles.
12225   if (!VT.is128BitVector() || !InVT.is256BitVector())
12226     return SDValue();
12227
12228   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12229
12230   unsigned NumElems = VT.getVectorNumElements();
12231   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12232
12233   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12234   // Prepare truncation shuffle mask
12235   for (unsigned i = 0; i != NumElems; ++i)
12236     MaskVec[i] = i * 2;
12237   SDValue V = DAG.getVectorShuffle(NVT, DL,
12238                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12239                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12240   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12241                      DAG.getIntPtrConstant(0, DL));
12242 }
12243
12244 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12245                                            SelectionDAG &DAG) const {
12246   assert(!Op.getSimpleValueType().isVector());
12247
12248   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12249     /*IsSigned=*/ true, /*IsReplace=*/ false);
12250   SDValue FIST = Vals.first, StackSlot = Vals.second;
12251   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12252   if (!FIST.getNode()) return Op;
12253
12254   if (StackSlot.getNode())
12255     // Load the result.
12256     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12257                        FIST, StackSlot, MachinePointerInfo(),
12258                        false, false, false, 0);
12259
12260   // The node is the result.
12261   return FIST;
12262 }
12263
12264 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12265                                            SelectionDAG &DAG) const {
12266   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12267     /*IsSigned=*/ false, /*IsReplace=*/ false);
12268   SDValue FIST = Vals.first, StackSlot = Vals.second;
12269   assert(FIST.getNode() && "Unexpected failure");
12270
12271   if (StackSlot.getNode())
12272     // Load the result.
12273     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12274                        FIST, StackSlot, MachinePointerInfo(),
12275                        false, false, false, 0);
12276
12277   // The node is the result.
12278   return FIST;
12279 }
12280
12281 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12282   SDLoc DL(Op);
12283   MVT VT = Op.getSimpleValueType();
12284   SDValue In = Op.getOperand(0);
12285   MVT SVT = In.getSimpleValueType();
12286
12287   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12288
12289   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12290                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12291                                  In, DAG.getUNDEF(SVT)));
12292 }
12293
12294 /// The only differences between FABS and FNEG are the mask and the logic op.
12295 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12296 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12297   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12298          "Wrong opcode for lowering FABS or FNEG.");
12299
12300   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12301
12302   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12303   // into an FNABS. We'll lower the FABS after that if it is still in use.
12304   if (IsFABS)
12305     for (SDNode *User : Op->uses())
12306       if (User->getOpcode() == ISD::FNEG)
12307         return Op;
12308
12309   SDValue Op0 = Op.getOperand(0);
12310   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12311
12312   SDLoc dl(Op);
12313   MVT VT = Op.getSimpleValueType();
12314   // Assume scalar op for initialization; update for vector if needed.
12315   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12316   // generate a 16-byte vector constant and logic op even for the scalar case.
12317   // Using a 16-byte mask allows folding the load of the mask with
12318   // the logic op, so it can save (~4 bytes) on code size.
12319   MVT EltVT = VT;
12320   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12321   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12322   // decide if we should generate a 16-byte constant mask when we only need 4 or
12323   // 8 bytes for the scalar case.
12324   if (VT.isVector()) {
12325     EltVT = VT.getVectorElementType();
12326     NumElts = VT.getVectorNumElements();
12327   }
12328
12329   unsigned EltBits = EltVT.getSizeInBits();
12330   LLVMContext *Context = DAG.getContext();
12331   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12332   APInt MaskElt =
12333     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12334   Constant *C = ConstantInt::get(*Context, MaskElt);
12335   C = ConstantVector::getSplat(NumElts, C);
12336   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12337   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12338   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12339   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12340                              MachinePointerInfo::getConstantPool(),
12341                              false, false, false, Alignment);
12342
12343   if (VT.isVector()) {
12344     // For a vector, cast operands to a vector type, perform the logic op,
12345     // and cast the result back to the original value type.
12346     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12347     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12348     SDValue Operand = IsFNABS ?
12349       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12350       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12351     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12352     return DAG.getNode(ISD::BITCAST, dl, VT,
12353                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12354   }
12355
12356   // If not vector, then scalar.
12357   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12358   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12359   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12360 }
12361
12362 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12363   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12364   LLVMContext *Context = DAG.getContext();
12365   SDValue Op0 = Op.getOperand(0);
12366   SDValue Op1 = Op.getOperand(1);
12367   SDLoc dl(Op);
12368   MVT VT = Op.getSimpleValueType();
12369   MVT SrcVT = Op1.getSimpleValueType();
12370
12371   // If second operand is smaller, extend it first.
12372   if (SrcVT.bitsLT(VT)) {
12373     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12374     SrcVT = VT;
12375   }
12376   // And if it is bigger, shrink it first.
12377   if (SrcVT.bitsGT(VT)) {
12378     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12379     SrcVT = VT;
12380   }
12381
12382   // At this point the operands and the result should have the same
12383   // type, and that won't be f80 since that is not custom lowered.
12384
12385   const fltSemantics &Sem =
12386       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12387   const unsigned SizeInBits = VT.getSizeInBits();
12388
12389   SmallVector<Constant *, 4> CV(
12390       VT == MVT::f64 ? 2 : 4,
12391       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12392
12393   // First, clear all bits but the sign bit from the second operand (sign).
12394   CV[0] = ConstantFP::get(*Context,
12395                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12396   Constant *C = ConstantVector::get(CV);
12397   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12398   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12399                               MachinePointerInfo::getConstantPool(),
12400                               false, false, false, 16);
12401   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12402
12403   // Next, clear the sign bit from the first operand (magnitude).
12404   // If it's a constant, we can clear it here.
12405   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12406     APFloat APF = Op0CN->getValueAPF();
12407     // If the magnitude is a positive zero, the sign bit alone is enough.
12408     if (APF.isPosZero())
12409       return SignBit;
12410     APF.clearSign();
12411     CV[0] = ConstantFP::get(*Context, APF);
12412   } else {
12413     CV[0] = ConstantFP::get(
12414         *Context,
12415         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12416   }
12417   C = ConstantVector::get(CV);
12418   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12419   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12420                             MachinePointerInfo::getConstantPool(),
12421                             false, false, false, 16);
12422   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12423   if (!isa<ConstantFPSDNode>(Op0))
12424     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12425
12426   // OR the magnitude value with the sign bit.
12427   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12428 }
12429
12430 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12431   SDValue N0 = Op.getOperand(0);
12432   SDLoc dl(Op);
12433   MVT VT = Op.getSimpleValueType();
12434
12435   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12436   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12437                                   DAG.getConstant(1, dl, VT));
12438   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12439 }
12440
12441 // Check whether an OR'd tree is PTEST-able.
12442 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12443                                       SelectionDAG &DAG) {
12444   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12445
12446   if (!Subtarget->hasSSE41())
12447     return SDValue();
12448
12449   if (!Op->hasOneUse())
12450     return SDValue();
12451
12452   SDNode *N = Op.getNode();
12453   SDLoc DL(N);
12454
12455   SmallVector<SDValue, 8> Opnds;
12456   DenseMap<SDValue, unsigned> VecInMap;
12457   SmallVector<SDValue, 8> VecIns;
12458   EVT VT = MVT::Other;
12459
12460   // Recognize a special case where a vector is casted into wide integer to
12461   // test all 0s.
12462   Opnds.push_back(N->getOperand(0));
12463   Opnds.push_back(N->getOperand(1));
12464
12465   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12466     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12467     // BFS traverse all OR'd operands.
12468     if (I->getOpcode() == ISD::OR) {
12469       Opnds.push_back(I->getOperand(0));
12470       Opnds.push_back(I->getOperand(1));
12471       // Re-evaluate the number of nodes to be traversed.
12472       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12473       continue;
12474     }
12475
12476     // Quit if a non-EXTRACT_VECTOR_ELT
12477     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12478       return SDValue();
12479
12480     // Quit if without a constant index.
12481     SDValue Idx = I->getOperand(1);
12482     if (!isa<ConstantSDNode>(Idx))
12483       return SDValue();
12484
12485     SDValue ExtractedFromVec = I->getOperand(0);
12486     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12487     if (M == VecInMap.end()) {
12488       VT = ExtractedFromVec.getValueType();
12489       // Quit if not 128/256-bit vector.
12490       if (!VT.is128BitVector() && !VT.is256BitVector())
12491         return SDValue();
12492       // Quit if not the same type.
12493       if (VecInMap.begin() != VecInMap.end() &&
12494           VT != VecInMap.begin()->first.getValueType())
12495         return SDValue();
12496       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12497       VecIns.push_back(ExtractedFromVec);
12498     }
12499     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12500   }
12501
12502   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12503          "Not extracted from 128-/256-bit vector.");
12504
12505   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12506
12507   for (DenseMap<SDValue, unsigned>::const_iterator
12508         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12509     // Quit if not all elements are used.
12510     if (I->second != FullMask)
12511       return SDValue();
12512   }
12513
12514   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12515
12516   // Cast all vectors into TestVT for PTEST.
12517   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12518     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12519
12520   // If more than one full vectors are evaluated, OR them first before PTEST.
12521   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12522     // Each iteration will OR 2 nodes and append the result until there is only
12523     // 1 node left, i.e. the final OR'd value of all vectors.
12524     SDValue LHS = VecIns[Slot];
12525     SDValue RHS = VecIns[Slot + 1];
12526     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12527   }
12528
12529   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12530                      VecIns.back(), VecIns.back());
12531 }
12532
12533 /// \brief return true if \c Op has a use that doesn't just read flags.
12534 static bool hasNonFlagsUse(SDValue Op) {
12535   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12536        ++UI) {
12537     SDNode *User = *UI;
12538     unsigned UOpNo = UI.getOperandNo();
12539     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12540       // Look pass truncate.
12541       UOpNo = User->use_begin().getOperandNo();
12542       User = *User->use_begin();
12543     }
12544
12545     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12546         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12547       return true;
12548   }
12549   return false;
12550 }
12551
12552 /// Emit nodes that will be selected as "test Op0,Op0", or something
12553 /// equivalent.
12554 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12555                                     SelectionDAG &DAG) const {
12556   if (Op.getValueType() == MVT::i1) {
12557     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12558     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12559                        DAG.getConstant(0, dl, MVT::i8));
12560   }
12561   // CF and OF aren't always set the way we want. Determine which
12562   // of these we need.
12563   bool NeedCF = false;
12564   bool NeedOF = false;
12565   switch (X86CC) {
12566   default: break;
12567   case X86::COND_A: case X86::COND_AE:
12568   case X86::COND_B: case X86::COND_BE:
12569     NeedCF = true;
12570     break;
12571   case X86::COND_G: case X86::COND_GE:
12572   case X86::COND_L: case X86::COND_LE:
12573   case X86::COND_O: case X86::COND_NO: {
12574     // Check if we really need to set the
12575     // Overflow flag. If NoSignedWrap is present
12576     // that is not actually needed.
12577     switch (Op->getOpcode()) {
12578     case ISD::ADD:
12579     case ISD::SUB:
12580     case ISD::MUL:
12581     case ISD::SHL: {
12582       const BinaryWithFlagsSDNode *BinNode =
12583           cast<BinaryWithFlagsSDNode>(Op.getNode());
12584       if (BinNode->Flags.hasNoSignedWrap())
12585         break;
12586     }
12587     default:
12588       NeedOF = true;
12589       break;
12590     }
12591     break;
12592   }
12593   }
12594   // See if we can use the EFLAGS value from the operand instead of
12595   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12596   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12597   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12598     // Emit a CMP with 0, which is the TEST pattern.
12599     //if (Op.getValueType() == MVT::i1)
12600     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12601     //                     DAG.getConstant(0, MVT::i1));
12602     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12603                        DAG.getConstant(0, dl, Op.getValueType()));
12604   }
12605   unsigned Opcode = 0;
12606   unsigned NumOperands = 0;
12607
12608   // Truncate operations may prevent the merge of the SETCC instruction
12609   // and the arithmetic instruction before it. Attempt to truncate the operands
12610   // of the arithmetic instruction and use a reduced bit-width instruction.
12611   bool NeedTruncation = false;
12612   SDValue ArithOp = Op;
12613   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12614     SDValue Arith = Op->getOperand(0);
12615     // Both the trunc and the arithmetic op need to have one user each.
12616     if (Arith->hasOneUse())
12617       switch (Arith.getOpcode()) {
12618         default: break;
12619         case ISD::ADD:
12620         case ISD::SUB:
12621         case ISD::AND:
12622         case ISD::OR:
12623         case ISD::XOR: {
12624           NeedTruncation = true;
12625           ArithOp = Arith;
12626         }
12627       }
12628   }
12629
12630   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12631   // which may be the result of a CAST.  We use the variable 'Op', which is the
12632   // non-casted variable when we check for possible users.
12633   switch (ArithOp.getOpcode()) {
12634   case ISD::ADD:
12635     // Due to an isel shortcoming, be conservative if this add is likely to be
12636     // selected as part of a load-modify-store instruction. When the root node
12637     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12638     // uses of other nodes in the match, such as the ADD in this case. This
12639     // leads to the ADD being left around and reselected, with the result being
12640     // two adds in the output.  Alas, even if none our users are stores, that
12641     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12642     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12643     // climbing the DAG back to the root, and it doesn't seem to be worth the
12644     // effort.
12645     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12646          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12647       if (UI->getOpcode() != ISD::CopyToReg &&
12648           UI->getOpcode() != ISD::SETCC &&
12649           UI->getOpcode() != ISD::STORE)
12650         goto default_case;
12651
12652     if (ConstantSDNode *C =
12653         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12654       // An add of one will be selected as an INC.
12655       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12656         Opcode = X86ISD::INC;
12657         NumOperands = 1;
12658         break;
12659       }
12660
12661       // An add of negative one (subtract of one) will be selected as a DEC.
12662       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12663         Opcode = X86ISD::DEC;
12664         NumOperands = 1;
12665         break;
12666       }
12667     }
12668
12669     // Otherwise use a regular EFLAGS-setting add.
12670     Opcode = X86ISD::ADD;
12671     NumOperands = 2;
12672     break;
12673   case ISD::SHL:
12674   case ISD::SRL:
12675     // If we have a constant logical shift that's only used in a comparison
12676     // against zero turn it into an equivalent AND. This allows turning it into
12677     // a TEST instruction later.
12678     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12679         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12680       EVT VT = Op.getValueType();
12681       unsigned BitWidth = VT.getSizeInBits();
12682       unsigned ShAmt = Op->getConstantOperandVal(1);
12683       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12684         break;
12685       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12686                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12687                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12688       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12689         break;
12690       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12691                                 DAG.getConstant(Mask, dl, VT));
12692       DAG.ReplaceAllUsesWith(Op, New);
12693       Op = New;
12694     }
12695     break;
12696
12697   case ISD::AND:
12698     // If the primary and result isn't used, don't bother using X86ISD::AND,
12699     // because a TEST instruction will be better.
12700     if (!hasNonFlagsUse(Op))
12701       break;
12702     // FALL THROUGH
12703   case ISD::SUB:
12704   case ISD::OR:
12705   case ISD::XOR:
12706     // Due to the ISEL shortcoming noted above, be conservative if this op is
12707     // likely to be selected as part of a load-modify-store instruction.
12708     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12709            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12710       if (UI->getOpcode() == ISD::STORE)
12711         goto default_case;
12712
12713     // Otherwise use a regular EFLAGS-setting instruction.
12714     switch (ArithOp.getOpcode()) {
12715     default: llvm_unreachable("unexpected operator!");
12716     case ISD::SUB: Opcode = X86ISD::SUB; break;
12717     case ISD::XOR: Opcode = X86ISD::XOR; break;
12718     case ISD::AND: Opcode = X86ISD::AND; break;
12719     case ISD::OR: {
12720       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12721         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12722         if (EFLAGS.getNode())
12723           return EFLAGS;
12724       }
12725       Opcode = X86ISD::OR;
12726       break;
12727     }
12728     }
12729
12730     NumOperands = 2;
12731     break;
12732   case X86ISD::ADD:
12733   case X86ISD::SUB:
12734   case X86ISD::INC:
12735   case X86ISD::DEC:
12736   case X86ISD::OR:
12737   case X86ISD::XOR:
12738   case X86ISD::AND:
12739     return SDValue(Op.getNode(), 1);
12740   default:
12741   default_case:
12742     break;
12743   }
12744
12745   // If we found that truncation is beneficial, perform the truncation and
12746   // update 'Op'.
12747   if (NeedTruncation) {
12748     EVT VT = Op.getValueType();
12749     SDValue WideVal = Op->getOperand(0);
12750     EVT WideVT = WideVal.getValueType();
12751     unsigned ConvertedOp = 0;
12752     // Use a target machine opcode to prevent further DAGCombine
12753     // optimizations that may separate the arithmetic operations
12754     // from the setcc node.
12755     switch (WideVal.getOpcode()) {
12756       default: break;
12757       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12758       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12759       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12760       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12761       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12762     }
12763
12764     if (ConvertedOp) {
12765       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12766       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12767         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12768         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12769         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12770       }
12771     }
12772   }
12773
12774   if (Opcode == 0)
12775     // Emit a CMP with 0, which is the TEST pattern.
12776     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12777                        DAG.getConstant(0, dl, Op.getValueType()));
12778
12779   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12780   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12781
12782   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12783   DAG.ReplaceAllUsesWith(Op, New);
12784   return SDValue(New.getNode(), 1);
12785 }
12786
12787 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12788 /// equivalent.
12789 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12790                                    SDLoc dl, SelectionDAG &DAG) const {
12791   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12792     if (C->getAPIntValue() == 0)
12793       return EmitTest(Op0, X86CC, dl, DAG);
12794
12795      if (Op0.getValueType() == MVT::i1)
12796        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12797   }
12798
12799   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12800        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12801     // Do the comparison at i32 if it's smaller, besides the Atom case.
12802     // This avoids subregister aliasing issues. Keep the smaller reference
12803     // if we're optimizing for size, however, as that'll allow better folding
12804     // of memory operations.
12805     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12806         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12807             Attribute::MinSize) &&
12808         !Subtarget->isAtom()) {
12809       unsigned ExtendOp =
12810           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12811       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12812       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12813     }
12814     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12815     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12816     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12817                               Op0, Op1);
12818     return SDValue(Sub.getNode(), 1);
12819   }
12820   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12821 }
12822
12823 /// Convert a comparison if required by the subtarget.
12824 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12825                                                  SelectionDAG &DAG) const {
12826   // If the subtarget does not support the FUCOMI instruction, floating-point
12827   // comparisons have to be converted.
12828   if (Subtarget->hasCMov() ||
12829       Cmp.getOpcode() != X86ISD::CMP ||
12830       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12831       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12832     return Cmp;
12833
12834   // The instruction selector will select an FUCOM instruction instead of
12835   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12836   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12837   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12838   SDLoc dl(Cmp);
12839   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12840   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12841   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12842                             DAG.getConstant(8, dl, MVT::i8));
12843   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12844   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12845 }
12846
12847 /// The minimum architected relative accuracy is 2^-12. We need one
12848 /// Newton-Raphson step to have a good float result (24 bits of precision).
12849 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12850                                             DAGCombinerInfo &DCI,
12851                                             unsigned &RefinementSteps,
12852                                             bool &UseOneConstNR) const {
12853   // FIXME: We should use instruction latency models to calculate the cost of
12854   // each potential sequence, but this is very hard to do reliably because
12855   // at least Intel's Core* chips have variable timing based on the number of
12856   // significant digits in the divisor and/or sqrt operand.
12857   if (!Subtarget->useSqrtEst())
12858     return SDValue();
12859
12860   EVT VT = Op.getValueType();
12861
12862   // SSE1 has rsqrtss and rsqrtps.
12863   // TODO: Add support for AVX512 (v16f32).
12864   // It is likely not profitable to do this for f64 because a double-precision
12865   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12866   // instructions: convert to single, rsqrtss, convert back to double, refine
12867   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12868   // along with FMA, this could be a throughput win.
12869   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12870       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12871     RefinementSteps = 1;
12872     UseOneConstNR = false;
12873     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12874   }
12875   return SDValue();
12876 }
12877
12878 /// The minimum architected relative accuracy is 2^-12. We need one
12879 /// Newton-Raphson step to have a good float result (24 bits of precision).
12880 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12881                                             DAGCombinerInfo &DCI,
12882                                             unsigned &RefinementSteps) const {
12883   // FIXME: We should use instruction latency models to calculate the cost of
12884   // each potential sequence, but this is very hard to do reliably because
12885   // at least Intel's Core* chips have variable timing based on the number of
12886   // significant digits in the divisor.
12887   if (!Subtarget->useReciprocalEst())
12888     return SDValue();
12889
12890   EVT VT = Op.getValueType();
12891
12892   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12893   // TODO: Add support for AVX512 (v16f32).
12894   // It is likely not profitable to do this for f64 because a double-precision
12895   // reciprocal estimate with refinement on x86 prior to FMA requires
12896   // 15 instructions: convert to single, rcpss, convert back to double, refine
12897   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12898   // along with FMA, this could be a throughput win.
12899   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12900       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12901     RefinementSteps = ReciprocalEstimateRefinementSteps;
12902     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12903   }
12904   return SDValue();
12905 }
12906
12907 /// If we have at least two divisions that use the same divisor, convert to
12908 /// multplication by a reciprocal. This may need to be adjusted for a given
12909 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12910 /// This is because we still need one division to calculate the reciprocal and
12911 /// then we need two multiplies by that reciprocal as replacements for the
12912 /// original divisions.
12913 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12914   return NumUsers > 1;
12915 }
12916
12917 static bool isAllOnes(SDValue V) {
12918   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12919   return C && C->isAllOnesValue();
12920 }
12921
12922 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12923 /// if it's possible.
12924 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12925                                      SDLoc dl, SelectionDAG &DAG) const {
12926   SDValue Op0 = And.getOperand(0);
12927   SDValue Op1 = And.getOperand(1);
12928   if (Op0.getOpcode() == ISD::TRUNCATE)
12929     Op0 = Op0.getOperand(0);
12930   if (Op1.getOpcode() == ISD::TRUNCATE)
12931     Op1 = Op1.getOperand(0);
12932
12933   SDValue LHS, RHS;
12934   if (Op1.getOpcode() == ISD::SHL)
12935     std::swap(Op0, Op1);
12936   if (Op0.getOpcode() == ISD::SHL) {
12937     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12938       if (And00C->getZExtValue() == 1) {
12939         // If we looked past a truncate, check that it's only truncating away
12940         // known zeros.
12941         unsigned BitWidth = Op0.getValueSizeInBits();
12942         unsigned AndBitWidth = And.getValueSizeInBits();
12943         if (BitWidth > AndBitWidth) {
12944           APInt Zeros, Ones;
12945           DAG.computeKnownBits(Op0, Zeros, Ones);
12946           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12947             return SDValue();
12948         }
12949         LHS = Op1;
12950         RHS = Op0.getOperand(1);
12951       }
12952   } else if (Op1.getOpcode() == ISD::Constant) {
12953     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12954     uint64_t AndRHSVal = AndRHS->getZExtValue();
12955     SDValue AndLHS = Op0;
12956
12957     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12958       LHS = AndLHS.getOperand(0);
12959       RHS = AndLHS.getOperand(1);
12960     }
12961
12962     // Use BT if the immediate can't be encoded in a TEST instruction.
12963     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12964       LHS = AndLHS;
12965       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
12966     }
12967   }
12968
12969   if (LHS.getNode()) {
12970     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12971     // instruction.  Since the shift amount is in-range-or-undefined, we know
12972     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12973     // the encoding for the i16 version is larger than the i32 version.
12974     // Also promote i16 to i32 for performance / code size reason.
12975     if (LHS.getValueType() == MVT::i8 ||
12976         LHS.getValueType() == MVT::i16)
12977       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12978
12979     // If the operand types disagree, extend the shift amount to match.  Since
12980     // BT ignores high bits (like shifts) we can use anyextend.
12981     if (LHS.getValueType() != RHS.getValueType())
12982       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12983
12984     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12985     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12986     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12987                        DAG.getConstant(Cond, dl, MVT::i8), BT);
12988   }
12989
12990   return SDValue();
12991 }
12992
12993 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12994 /// mask CMPs.
12995 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12996                               SDValue &Op1) {
12997   unsigned SSECC;
12998   bool Swap = false;
12999
13000   // SSE Condition code mapping:
13001   //  0 - EQ
13002   //  1 - LT
13003   //  2 - LE
13004   //  3 - UNORD
13005   //  4 - NEQ
13006   //  5 - NLT
13007   //  6 - NLE
13008   //  7 - ORD
13009   switch (SetCCOpcode) {
13010   default: llvm_unreachable("Unexpected SETCC condition");
13011   case ISD::SETOEQ:
13012   case ISD::SETEQ:  SSECC = 0; break;
13013   case ISD::SETOGT:
13014   case ISD::SETGT:  Swap = true; // Fallthrough
13015   case ISD::SETLT:
13016   case ISD::SETOLT: SSECC = 1; break;
13017   case ISD::SETOGE:
13018   case ISD::SETGE:  Swap = true; // Fallthrough
13019   case ISD::SETLE:
13020   case ISD::SETOLE: SSECC = 2; break;
13021   case ISD::SETUO:  SSECC = 3; break;
13022   case ISD::SETUNE:
13023   case ISD::SETNE:  SSECC = 4; break;
13024   case ISD::SETULE: Swap = true; // Fallthrough
13025   case ISD::SETUGE: SSECC = 5; break;
13026   case ISD::SETULT: Swap = true; // Fallthrough
13027   case ISD::SETUGT: SSECC = 6; break;
13028   case ISD::SETO:   SSECC = 7; break;
13029   case ISD::SETUEQ:
13030   case ISD::SETONE: SSECC = 8; break;
13031   }
13032   if (Swap)
13033     std::swap(Op0, Op1);
13034
13035   return SSECC;
13036 }
13037
13038 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13039 // ones, and then concatenate the result back.
13040 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13041   MVT VT = Op.getSimpleValueType();
13042
13043   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13044          "Unsupported value type for operation");
13045
13046   unsigned NumElems = VT.getVectorNumElements();
13047   SDLoc dl(Op);
13048   SDValue CC = Op.getOperand(2);
13049
13050   // Extract the LHS vectors
13051   SDValue LHS = Op.getOperand(0);
13052   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13053   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13054
13055   // Extract the RHS vectors
13056   SDValue RHS = Op.getOperand(1);
13057   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13058   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13059
13060   // Issue the operation on the smaller types and concatenate the result back
13061   MVT EltVT = VT.getVectorElementType();
13062   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13063   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13064                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13065                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13066 }
13067
13068 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13069   SDValue Op0 = Op.getOperand(0);
13070   SDValue Op1 = Op.getOperand(1);
13071   SDValue CC = Op.getOperand(2);
13072   MVT VT = Op.getSimpleValueType();
13073   SDLoc dl(Op);
13074
13075   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13076          "Unexpected type for boolean compare operation");
13077   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13078   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13079                                DAG.getConstant(-1, dl, VT));
13080   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13081                                DAG.getConstant(-1, dl, VT));
13082   switch (SetCCOpcode) {
13083   default: llvm_unreachable("Unexpected SETCC condition");
13084   case ISD::SETNE:
13085     // (x != y) -> ~(x ^ y)
13086     return DAG.getNode(ISD::XOR, dl, VT,
13087                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13088                        DAG.getConstant(-1, dl, VT));
13089   case ISD::SETEQ:
13090     // (x == y) -> (x ^ y)
13091     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13092   case ISD::SETUGT:
13093   case ISD::SETGT:
13094     // (x > y) -> (x & ~y)
13095     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13096   case ISD::SETULT:
13097   case ISD::SETLT:
13098     // (x < y) -> (~x & y)
13099     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13100   case ISD::SETULE:
13101   case ISD::SETLE:
13102     // (x <= y) -> (~x | y)
13103     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13104   case ISD::SETUGE:
13105   case ISD::SETGE:
13106     // (x >=y) -> (x | ~y)
13107     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13108   }
13109 }
13110
13111 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13112                                      const X86Subtarget *Subtarget) {
13113   SDValue Op0 = Op.getOperand(0);
13114   SDValue Op1 = Op.getOperand(1);
13115   SDValue CC = Op.getOperand(2);
13116   MVT VT = Op.getSimpleValueType();
13117   SDLoc dl(Op);
13118
13119   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13120          Op.getValueType().getScalarType() == MVT::i1 &&
13121          "Cannot set masked compare for this operation");
13122
13123   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13124   unsigned  Opc = 0;
13125   bool Unsigned = false;
13126   bool Swap = false;
13127   unsigned SSECC;
13128   switch (SetCCOpcode) {
13129   default: llvm_unreachable("Unexpected SETCC condition");
13130   case ISD::SETNE:  SSECC = 4; break;
13131   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13132   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13133   case ISD::SETLT:  Swap = true; //fall-through
13134   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13135   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13136   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13137   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13138   case ISD::SETULE: Unsigned = true; //fall-through
13139   case ISD::SETLE:  SSECC = 2; break;
13140   }
13141
13142   if (Swap)
13143     std::swap(Op0, Op1);
13144   if (Opc)
13145     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13146   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13147   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13148                      DAG.getConstant(SSECC, dl, MVT::i8));
13149 }
13150
13151 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13152 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13153 /// return an empty value.
13154 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13155 {
13156   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13157   if (!BV)
13158     return SDValue();
13159
13160   MVT VT = Op1.getSimpleValueType();
13161   MVT EVT = VT.getVectorElementType();
13162   unsigned n = VT.getVectorNumElements();
13163   SmallVector<SDValue, 8> ULTOp1;
13164
13165   for (unsigned i = 0; i < n; ++i) {
13166     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13167     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13168       return SDValue();
13169
13170     // Avoid underflow.
13171     APInt Val = Elt->getAPIntValue();
13172     if (Val == 0)
13173       return SDValue();
13174
13175     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13176   }
13177
13178   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13179 }
13180
13181 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13182                            SelectionDAG &DAG) {
13183   SDValue Op0 = Op.getOperand(0);
13184   SDValue Op1 = Op.getOperand(1);
13185   SDValue CC = Op.getOperand(2);
13186   MVT VT = Op.getSimpleValueType();
13187   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13188   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13189   SDLoc dl(Op);
13190
13191   if (isFP) {
13192 #ifndef NDEBUG
13193     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13194     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13195 #endif
13196
13197     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13198     unsigned Opc = X86ISD::CMPP;
13199     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13200       assert(VT.getVectorNumElements() <= 16);
13201       Opc = X86ISD::CMPM;
13202     }
13203     // In the two special cases we can't handle, emit two comparisons.
13204     if (SSECC == 8) {
13205       unsigned CC0, CC1;
13206       unsigned CombineOpc;
13207       if (SetCCOpcode == ISD::SETUEQ) {
13208         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13209       } else {
13210         assert(SetCCOpcode == ISD::SETONE);
13211         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13212       }
13213
13214       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13215                                  DAG.getConstant(CC0, dl, MVT::i8));
13216       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13217                                  DAG.getConstant(CC1, dl, MVT::i8));
13218       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13219     }
13220     // Handle all other FP comparisons here.
13221     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13222                        DAG.getConstant(SSECC, dl, MVT::i8));
13223   }
13224
13225   // Break 256-bit integer vector compare into smaller ones.
13226   if (VT.is256BitVector() && !Subtarget->hasInt256())
13227     return Lower256IntVSETCC(Op, DAG);
13228
13229   EVT OpVT = Op1.getValueType();
13230   if (OpVT.getVectorElementType() == MVT::i1)
13231     return LowerBoolVSETCC_AVX512(Op, DAG);
13232
13233   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13234   if (Subtarget->hasAVX512()) {
13235     if (Op1.getValueType().is512BitVector() ||
13236         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13237         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13238       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13239
13240     // In AVX-512 architecture setcc returns mask with i1 elements,
13241     // But there is no compare instruction for i8 and i16 elements in KNL.
13242     // We are not talking about 512-bit operands in this case, these
13243     // types are illegal.
13244     if (MaskResult &&
13245         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13246          OpVT.getVectorElementType().getSizeInBits() >= 8))
13247       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13248                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13249   }
13250
13251   // We are handling one of the integer comparisons here.  Since SSE only has
13252   // GT and EQ comparisons for integer, swapping operands and multiple
13253   // operations may be required for some comparisons.
13254   unsigned Opc;
13255   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13256   bool Subus = false;
13257
13258   switch (SetCCOpcode) {
13259   default: llvm_unreachable("Unexpected SETCC condition");
13260   case ISD::SETNE:  Invert = true;
13261   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13262   case ISD::SETLT:  Swap = true;
13263   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13264   case ISD::SETGE:  Swap = true;
13265   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13266                     Invert = true; break;
13267   case ISD::SETULT: Swap = true;
13268   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13269                     FlipSigns = true; break;
13270   case ISD::SETUGE: Swap = true;
13271   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13272                     FlipSigns = true; Invert = true; break;
13273   }
13274
13275   // Special case: Use min/max operations for SETULE/SETUGE
13276   MVT VET = VT.getVectorElementType();
13277   bool hasMinMax =
13278        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13279     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13280
13281   if (hasMinMax) {
13282     switch (SetCCOpcode) {
13283     default: break;
13284     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13285     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13286     }
13287
13288     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13289   }
13290
13291   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13292   if (!MinMax && hasSubus) {
13293     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13294     // Op0 u<= Op1:
13295     //   t = psubus Op0, Op1
13296     //   pcmpeq t, <0..0>
13297     switch (SetCCOpcode) {
13298     default: break;
13299     case ISD::SETULT: {
13300       // If the comparison is against a constant we can turn this into a
13301       // setule.  With psubus, setule does not require a swap.  This is
13302       // beneficial because the constant in the register is no longer
13303       // destructed as the destination so it can be hoisted out of a loop.
13304       // Only do this pre-AVX since vpcmp* is no longer destructive.
13305       if (Subtarget->hasAVX())
13306         break;
13307       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13308       if (ULEOp1.getNode()) {
13309         Op1 = ULEOp1;
13310         Subus = true; Invert = false; Swap = false;
13311       }
13312       break;
13313     }
13314     // Psubus is better than flip-sign because it requires no inversion.
13315     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13316     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13317     }
13318
13319     if (Subus) {
13320       Opc = X86ISD::SUBUS;
13321       FlipSigns = false;
13322     }
13323   }
13324
13325   if (Swap)
13326     std::swap(Op0, Op1);
13327
13328   // Check that the operation in question is available (most are plain SSE2,
13329   // but PCMPGTQ and PCMPEQQ have different requirements).
13330   if (VT == MVT::v2i64) {
13331     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13332       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13333
13334       // First cast everything to the right type.
13335       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13336       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13337
13338       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13339       // bits of the inputs before performing those operations. The lower
13340       // compare is always unsigned.
13341       SDValue SB;
13342       if (FlipSigns) {
13343         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13344       } else {
13345         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13346         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13347         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13348                          Sign, Zero, Sign, Zero);
13349       }
13350       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13351       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13352
13353       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13354       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13355       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13356
13357       // Create masks for only the low parts/high parts of the 64 bit integers.
13358       static const int MaskHi[] = { 1, 1, 3, 3 };
13359       static const int MaskLo[] = { 0, 0, 2, 2 };
13360       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13361       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13362       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13363
13364       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13365       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13366
13367       if (Invert)
13368         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13369
13370       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13371     }
13372
13373     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13374       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13375       // pcmpeqd + pshufd + pand.
13376       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13377
13378       // First cast everything to the right type.
13379       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13380       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13381
13382       // Do the compare.
13383       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13384
13385       // Make sure the lower and upper halves are both all-ones.
13386       static const int Mask[] = { 1, 0, 3, 2 };
13387       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13388       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13389
13390       if (Invert)
13391         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13392
13393       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13394     }
13395   }
13396
13397   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13398   // bits of the inputs before performing those operations.
13399   if (FlipSigns) {
13400     EVT EltVT = VT.getVectorElementType();
13401     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13402                                  VT);
13403     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13404     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13405   }
13406
13407   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13408
13409   // If the logical-not of the result is required, perform that now.
13410   if (Invert)
13411     Result = DAG.getNOT(dl, Result, VT);
13412
13413   if (MinMax)
13414     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13415
13416   if (Subus)
13417     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13418                          getZeroVector(VT, Subtarget, DAG, dl));
13419
13420   return Result;
13421 }
13422
13423 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13424
13425   MVT VT = Op.getSimpleValueType();
13426
13427   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13428
13429   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13430          && "SetCC type must be 8-bit or 1-bit integer");
13431   SDValue Op0 = Op.getOperand(0);
13432   SDValue Op1 = Op.getOperand(1);
13433   SDLoc dl(Op);
13434   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13435
13436   // Optimize to BT if possible.
13437   // Lower (X & (1 << N)) == 0 to BT(X, N).
13438   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13439   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13440   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13441       Op1.getOpcode() == ISD::Constant &&
13442       cast<ConstantSDNode>(Op1)->isNullValue() &&
13443       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13444     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13445     if (NewSetCC.getNode()) {
13446       if (VT == MVT::i1)
13447         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13448       return NewSetCC;
13449     }
13450   }
13451
13452   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13453   // these.
13454   if (Op1.getOpcode() == ISD::Constant &&
13455       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13456        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13457       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13458
13459     // If the input is a setcc, then reuse the input setcc or use a new one with
13460     // the inverted condition.
13461     if (Op0.getOpcode() == X86ISD::SETCC) {
13462       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13463       bool Invert = (CC == ISD::SETNE) ^
13464         cast<ConstantSDNode>(Op1)->isNullValue();
13465       if (!Invert)
13466         return Op0;
13467
13468       CCode = X86::GetOppositeBranchCondition(CCode);
13469       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13470                                   DAG.getConstant(CCode, dl, MVT::i8),
13471                                   Op0.getOperand(1));
13472       if (VT == MVT::i1)
13473         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13474       return SetCC;
13475     }
13476   }
13477   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13478       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13479       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13480
13481     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13482     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13483   }
13484
13485   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13486   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13487   if (X86CC == X86::COND_INVALID)
13488     return SDValue();
13489
13490   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13491   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13492   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13493                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13494   if (VT == MVT::i1)
13495     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13496   return SetCC;
13497 }
13498
13499 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13500 static bool isX86LogicalCmp(SDValue Op) {
13501   unsigned Opc = Op.getNode()->getOpcode();
13502   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13503       Opc == X86ISD::SAHF)
13504     return true;
13505   if (Op.getResNo() == 1 &&
13506       (Opc == X86ISD::ADD ||
13507        Opc == X86ISD::SUB ||
13508        Opc == X86ISD::ADC ||
13509        Opc == X86ISD::SBB ||
13510        Opc == X86ISD::SMUL ||
13511        Opc == X86ISD::UMUL ||
13512        Opc == X86ISD::INC ||
13513        Opc == X86ISD::DEC ||
13514        Opc == X86ISD::OR ||
13515        Opc == X86ISD::XOR ||
13516        Opc == X86ISD::AND))
13517     return true;
13518
13519   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13520     return true;
13521
13522   return false;
13523 }
13524
13525 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13526   if (V.getOpcode() != ISD::TRUNCATE)
13527     return false;
13528
13529   SDValue VOp0 = V.getOperand(0);
13530   unsigned InBits = VOp0.getValueSizeInBits();
13531   unsigned Bits = V.getValueSizeInBits();
13532   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13533 }
13534
13535 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13536   bool addTest = true;
13537   SDValue Cond  = Op.getOperand(0);
13538   SDValue Op1 = Op.getOperand(1);
13539   SDValue Op2 = Op.getOperand(2);
13540   SDLoc DL(Op);
13541   EVT VT = Op1.getValueType();
13542   SDValue CC;
13543
13544   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13545   // are available or VBLENDV if AVX is available.
13546   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13547   if (Cond.getOpcode() == ISD::SETCC &&
13548       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13549        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13550       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13551     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13552     int SSECC = translateX86FSETCC(
13553         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13554
13555     if (SSECC != 8) {
13556       if (Subtarget->hasAVX512()) {
13557         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13558                                   DAG.getConstant(SSECC, DL, MVT::i8));
13559         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13560       }
13561
13562       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13563                                 DAG.getConstant(SSECC, DL, MVT::i8));
13564
13565       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13566       // of 3 logic instructions for size savings and potentially speed.
13567       // Unfortunately, there is no scalar form of VBLENDV.
13568
13569       // If either operand is a constant, don't try this. We can expect to
13570       // optimize away at least one of the logic instructions later in that
13571       // case, so that sequence would be faster than a variable blend.
13572
13573       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13574       // uses XMM0 as the selection register. That may need just as many
13575       // instructions as the AND/ANDN/OR sequence due to register moves, so
13576       // don't bother.
13577
13578       if (Subtarget->hasAVX() &&
13579           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13580
13581         // Convert to vectors, do a VSELECT, and convert back to scalar.
13582         // All of the conversions should be optimized away.
13583
13584         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13585         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13586         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13587         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13588
13589         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13590         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13591
13592         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13593
13594         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13595                            VSel, DAG.getIntPtrConstant(0, DL));
13596       }
13597       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13598       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13599       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13600     }
13601   }
13602
13603   if (Cond.getOpcode() == ISD::SETCC) {
13604     SDValue NewCond = LowerSETCC(Cond, DAG);
13605     if (NewCond.getNode())
13606       Cond = NewCond;
13607   }
13608
13609   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13610   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13611   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13612   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13613   if (Cond.getOpcode() == X86ISD::SETCC &&
13614       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13615       isZero(Cond.getOperand(1).getOperand(1))) {
13616     SDValue Cmp = Cond.getOperand(1);
13617
13618     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13619
13620     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13621         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13622       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13623
13624       SDValue CmpOp0 = Cmp.getOperand(0);
13625       // Apply further optimizations for special cases
13626       // (select (x != 0), -1, 0) -> neg & sbb
13627       // (select (x == 0), 0, -1) -> neg & sbb
13628       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13629         if (YC->isNullValue() &&
13630             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13631           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13632           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13633                                     DAG.getConstant(0, DL,
13634                                                     CmpOp0.getValueType()),
13635                                     CmpOp0);
13636           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13637                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13638                                     SDValue(Neg.getNode(), 1));
13639           return Res;
13640         }
13641
13642       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13643                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13644       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13645
13646       SDValue Res =   // Res = 0 or -1.
13647         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13648                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13649
13650       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13651         Res = DAG.getNOT(DL, Res, Res.getValueType());
13652
13653       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13654       if (!N2C || !N2C->isNullValue())
13655         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13656       return Res;
13657     }
13658   }
13659
13660   // Look past (and (setcc_carry (cmp ...)), 1).
13661   if (Cond.getOpcode() == ISD::AND &&
13662       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13663     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13664     if (C && C->getAPIntValue() == 1)
13665       Cond = Cond.getOperand(0);
13666   }
13667
13668   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13669   // setting operand in place of the X86ISD::SETCC.
13670   unsigned CondOpcode = Cond.getOpcode();
13671   if (CondOpcode == X86ISD::SETCC ||
13672       CondOpcode == X86ISD::SETCC_CARRY) {
13673     CC = Cond.getOperand(0);
13674
13675     SDValue Cmp = Cond.getOperand(1);
13676     unsigned Opc = Cmp.getOpcode();
13677     MVT VT = Op.getSimpleValueType();
13678
13679     bool IllegalFPCMov = false;
13680     if (VT.isFloatingPoint() && !VT.isVector() &&
13681         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13682       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13683
13684     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13685         Opc == X86ISD::BT) { // FIXME
13686       Cond = Cmp;
13687       addTest = false;
13688     }
13689   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13690              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13691              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13692               Cond.getOperand(0).getValueType() != MVT::i8)) {
13693     SDValue LHS = Cond.getOperand(0);
13694     SDValue RHS = Cond.getOperand(1);
13695     unsigned X86Opcode;
13696     unsigned X86Cond;
13697     SDVTList VTs;
13698     switch (CondOpcode) {
13699     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13700     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13701     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13702     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13703     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13704     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13705     default: llvm_unreachable("unexpected overflowing operator");
13706     }
13707     if (CondOpcode == ISD::UMULO)
13708       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13709                           MVT::i32);
13710     else
13711       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13712
13713     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13714
13715     if (CondOpcode == ISD::UMULO)
13716       Cond = X86Op.getValue(2);
13717     else
13718       Cond = X86Op.getValue(1);
13719
13720     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13721     addTest = false;
13722   }
13723
13724   if (addTest) {
13725     // Look pass the truncate if the high bits are known zero.
13726     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13727         Cond = Cond.getOperand(0);
13728
13729     // We know the result of AND is compared against zero. Try to match
13730     // it to BT.
13731     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13732       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13733       if (NewSetCC.getNode()) {
13734         CC = NewSetCC.getOperand(0);
13735         Cond = NewSetCC.getOperand(1);
13736         addTest = false;
13737       }
13738     }
13739   }
13740
13741   if (addTest) {
13742     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13743     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13744   }
13745
13746   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13747   // a <  b ?  0 : -1 -> RES = setcc_carry
13748   // a >= b ? -1 :  0 -> RES = setcc_carry
13749   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13750   if (Cond.getOpcode() == X86ISD::SUB) {
13751     Cond = ConvertCmpIfNecessary(Cond, DAG);
13752     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13753
13754     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13755         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13756       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13757                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13758                                 Cond);
13759       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13760         return DAG.getNOT(DL, Res, Res.getValueType());
13761       return Res;
13762     }
13763   }
13764
13765   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13766   // widen the cmov and push the truncate through. This avoids introducing a new
13767   // branch during isel and doesn't add any extensions.
13768   if (Op.getValueType() == MVT::i8 &&
13769       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13770     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13771     if (T1.getValueType() == T2.getValueType() &&
13772         // Blacklist CopyFromReg to avoid partial register stalls.
13773         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13774       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13775       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13776       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13777     }
13778   }
13779
13780   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13781   // condition is true.
13782   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13783   SDValue Ops[] = { Op2, Op1, CC, Cond };
13784   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13785 }
13786
13787 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13788                                        SelectionDAG &DAG) {
13789   MVT VT = Op->getSimpleValueType(0);
13790   SDValue In = Op->getOperand(0);
13791   MVT InVT = In.getSimpleValueType();
13792   MVT VTElt = VT.getVectorElementType();
13793   MVT InVTElt = InVT.getVectorElementType();
13794   SDLoc dl(Op);
13795
13796   // SKX processor
13797   if ((InVTElt == MVT::i1) &&
13798       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13799         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13800
13801        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13802         VTElt.getSizeInBits() <= 16)) ||
13803
13804        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13805         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13806
13807        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13808         VTElt.getSizeInBits() >= 32))))
13809     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13810
13811   unsigned int NumElts = VT.getVectorNumElements();
13812
13813   if (NumElts != 8 && NumElts != 16)
13814     return SDValue();
13815
13816   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13817     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13818       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13819     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13820   }
13821
13822   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13823   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13824   SDValue NegOne =
13825    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13826                    ExtVT);
13827   SDValue Zero =
13828    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13829
13830   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13831   if (VT.is512BitVector())
13832     return V;
13833   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13834 }
13835
13836 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13837                                 SelectionDAG &DAG) {
13838   MVT VT = Op->getSimpleValueType(0);
13839   SDValue In = Op->getOperand(0);
13840   MVT InVT = In.getSimpleValueType();
13841   SDLoc dl(Op);
13842
13843   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13844     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13845
13846   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13847       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13848       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13849     return SDValue();
13850
13851   if (Subtarget->hasInt256())
13852     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13853
13854   // Optimize vectors in AVX mode
13855   // Sign extend  v8i16 to v8i32 and
13856   //              v4i32 to v4i64
13857   //
13858   // Divide input vector into two parts
13859   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13860   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13861   // concat the vectors to original VT
13862
13863   unsigned NumElems = InVT.getVectorNumElements();
13864   SDValue Undef = DAG.getUNDEF(InVT);
13865
13866   SmallVector<int,8> ShufMask1(NumElems, -1);
13867   for (unsigned i = 0; i != NumElems/2; ++i)
13868     ShufMask1[i] = i;
13869
13870   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13871
13872   SmallVector<int,8> ShufMask2(NumElems, -1);
13873   for (unsigned i = 0; i != NumElems/2; ++i)
13874     ShufMask2[i] = i + NumElems/2;
13875
13876   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13877
13878   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13879                                 VT.getVectorNumElements()/2);
13880
13881   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13882   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13883
13884   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13885 }
13886
13887 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13888 // may emit an illegal shuffle but the expansion is still better than scalar
13889 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13890 // we'll emit a shuffle and a arithmetic shift.
13891 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13892 // TODO: It is possible to support ZExt by zeroing the undef values during
13893 // the shuffle phase or after the shuffle.
13894 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13895                                  SelectionDAG &DAG) {
13896   MVT RegVT = Op.getSimpleValueType();
13897   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13898   assert(RegVT.isInteger() &&
13899          "We only custom lower integer vector sext loads.");
13900
13901   // Nothing useful we can do without SSE2 shuffles.
13902   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13903
13904   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13905   SDLoc dl(Ld);
13906   EVT MemVT = Ld->getMemoryVT();
13907   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13908   unsigned RegSz = RegVT.getSizeInBits();
13909
13910   ISD::LoadExtType Ext = Ld->getExtensionType();
13911
13912   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13913          && "Only anyext and sext are currently implemented.");
13914   assert(MemVT != RegVT && "Cannot extend to the same type");
13915   assert(MemVT.isVector() && "Must load a vector from memory");
13916
13917   unsigned NumElems = RegVT.getVectorNumElements();
13918   unsigned MemSz = MemVT.getSizeInBits();
13919   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13920
13921   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13922     // The only way in which we have a legal 256-bit vector result but not the
13923     // integer 256-bit operations needed to directly lower a sextload is if we
13924     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13925     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13926     // correctly legalized. We do this late to allow the canonical form of
13927     // sextload to persist throughout the rest of the DAG combiner -- it wants
13928     // to fold together any extensions it can, and so will fuse a sign_extend
13929     // of an sextload into a sextload targeting a wider value.
13930     SDValue Load;
13931     if (MemSz == 128) {
13932       // Just switch this to a normal load.
13933       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13934                                        "it must be a legal 128-bit vector "
13935                                        "type!");
13936       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13937                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13938                   Ld->isInvariant(), Ld->getAlignment());
13939     } else {
13940       assert(MemSz < 128 &&
13941              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13942       // Do an sext load to a 128-bit vector type. We want to use the same
13943       // number of elements, but elements half as wide. This will end up being
13944       // recursively lowered by this routine, but will succeed as we definitely
13945       // have all the necessary features if we're using AVX1.
13946       EVT HalfEltVT =
13947           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13948       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13949       Load =
13950           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13951                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13952                          Ld->isNonTemporal(), Ld->isInvariant(),
13953                          Ld->getAlignment());
13954     }
13955
13956     // Replace chain users with the new chain.
13957     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13958     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13959
13960     // Finally, do a normal sign-extend to the desired register.
13961     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13962   }
13963
13964   // All sizes must be a power of two.
13965   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13966          "Non-power-of-two elements are not custom lowered!");
13967
13968   // Attempt to load the original value using scalar loads.
13969   // Find the largest scalar type that divides the total loaded size.
13970   MVT SclrLoadTy = MVT::i8;
13971   for (MVT Tp : MVT::integer_valuetypes()) {
13972     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13973       SclrLoadTy = Tp;
13974     }
13975   }
13976
13977   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13978   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13979       (64 <= MemSz))
13980     SclrLoadTy = MVT::f64;
13981
13982   // Calculate the number of scalar loads that we need to perform
13983   // in order to load our vector from memory.
13984   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13985
13986   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13987          "Can only lower sext loads with a single scalar load!");
13988
13989   unsigned loadRegZize = RegSz;
13990   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13991     loadRegZize /= 2;
13992
13993   // Represent our vector as a sequence of elements which are the
13994   // largest scalar that we can load.
13995   EVT LoadUnitVecVT = EVT::getVectorVT(
13996       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13997
13998   // Represent the data using the same element type that is stored in
13999   // memory. In practice, we ''widen'' MemVT.
14000   EVT WideVecVT =
14001       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14002                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14003
14004   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14005          "Invalid vector type");
14006
14007   // We can't shuffle using an illegal type.
14008   assert(TLI.isTypeLegal(WideVecVT) &&
14009          "We only lower types that form legal widened vector types");
14010
14011   SmallVector<SDValue, 8> Chains;
14012   SDValue Ptr = Ld->getBasePtr();
14013   SDValue Increment =
14014       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14015   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14016
14017   for (unsigned i = 0; i < NumLoads; ++i) {
14018     // Perform a single load.
14019     SDValue ScalarLoad =
14020         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14021                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14022                     Ld->getAlignment());
14023     Chains.push_back(ScalarLoad.getValue(1));
14024     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14025     // another round of DAGCombining.
14026     if (i == 0)
14027       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14028     else
14029       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14030                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14031
14032     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14033   }
14034
14035   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14036
14037   // Bitcast the loaded value to a vector of the original element type, in
14038   // the size of the target vector type.
14039   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14040   unsigned SizeRatio = RegSz / MemSz;
14041
14042   if (Ext == ISD::SEXTLOAD) {
14043     // If we have SSE4.1, we can directly emit a VSEXT node.
14044     if (Subtarget->hasSSE41()) {
14045       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14046       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14047       return Sext;
14048     }
14049
14050     // Otherwise we'll shuffle the small elements in the high bits of the
14051     // larger type and perform an arithmetic shift. If the shift is not legal
14052     // it's better to scalarize.
14053     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14054            "We can't implement a sext load without an arithmetic right shift!");
14055
14056     // Redistribute the loaded elements into the different locations.
14057     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14058     for (unsigned i = 0; i != NumElems; ++i)
14059       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14060
14061     SDValue Shuff = DAG.getVectorShuffle(
14062         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14063
14064     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14065
14066     // Build the arithmetic shift.
14067     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14068                    MemVT.getVectorElementType().getSizeInBits();
14069     Shuff =
14070         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14071                     DAG.getConstant(Amt, dl, RegVT));
14072
14073     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14074     return Shuff;
14075   }
14076
14077   // Redistribute the loaded elements into the different locations.
14078   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14079   for (unsigned i = 0; i != NumElems; ++i)
14080     ShuffleVec[i * SizeRatio] = i;
14081
14082   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14083                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14084
14085   // Bitcast to the requested type.
14086   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14087   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14088   return Shuff;
14089 }
14090
14091 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14092 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14093 // from the AND / OR.
14094 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14095   Opc = Op.getOpcode();
14096   if (Opc != ISD::OR && Opc != ISD::AND)
14097     return false;
14098   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14099           Op.getOperand(0).hasOneUse() &&
14100           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14101           Op.getOperand(1).hasOneUse());
14102 }
14103
14104 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14105 // 1 and that the SETCC node has a single use.
14106 static bool isXor1OfSetCC(SDValue Op) {
14107   if (Op.getOpcode() != ISD::XOR)
14108     return false;
14109   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14110   if (N1C && N1C->getAPIntValue() == 1) {
14111     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14112       Op.getOperand(0).hasOneUse();
14113   }
14114   return false;
14115 }
14116
14117 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14118   bool addTest = true;
14119   SDValue Chain = Op.getOperand(0);
14120   SDValue Cond  = Op.getOperand(1);
14121   SDValue Dest  = Op.getOperand(2);
14122   SDLoc dl(Op);
14123   SDValue CC;
14124   bool Inverted = false;
14125
14126   if (Cond.getOpcode() == ISD::SETCC) {
14127     // Check for setcc([su]{add,sub,mul}o == 0).
14128     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14129         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14130         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14131         Cond.getOperand(0).getResNo() == 1 &&
14132         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14133          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14134          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14135          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14136          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14137          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14138       Inverted = true;
14139       Cond = Cond.getOperand(0);
14140     } else {
14141       SDValue NewCond = LowerSETCC(Cond, DAG);
14142       if (NewCond.getNode())
14143         Cond = NewCond;
14144     }
14145   }
14146 #if 0
14147   // FIXME: LowerXALUO doesn't handle these!!
14148   else if (Cond.getOpcode() == X86ISD::ADD  ||
14149            Cond.getOpcode() == X86ISD::SUB  ||
14150            Cond.getOpcode() == X86ISD::SMUL ||
14151            Cond.getOpcode() == X86ISD::UMUL)
14152     Cond = LowerXALUO(Cond, DAG);
14153 #endif
14154
14155   // Look pass (and (setcc_carry (cmp ...)), 1).
14156   if (Cond.getOpcode() == ISD::AND &&
14157       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14158     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14159     if (C && C->getAPIntValue() == 1)
14160       Cond = Cond.getOperand(0);
14161   }
14162
14163   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14164   // setting operand in place of the X86ISD::SETCC.
14165   unsigned CondOpcode = Cond.getOpcode();
14166   if (CondOpcode == X86ISD::SETCC ||
14167       CondOpcode == X86ISD::SETCC_CARRY) {
14168     CC = Cond.getOperand(0);
14169
14170     SDValue Cmp = Cond.getOperand(1);
14171     unsigned Opc = Cmp.getOpcode();
14172     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14173     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14174       Cond = Cmp;
14175       addTest = false;
14176     } else {
14177       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14178       default: break;
14179       case X86::COND_O:
14180       case X86::COND_B:
14181         // These can only come from an arithmetic instruction with overflow,
14182         // e.g. SADDO, UADDO.
14183         Cond = Cond.getNode()->getOperand(1);
14184         addTest = false;
14185         break;
14186       }
14187     }
14188   }
14189   CondOpcode = Cond.getOpcode();
14190   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14191       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14192       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14193        Cond.getOperand(0).getValueType() != MVT::i8)) {
14194     SDValue LHS = Cond.getOperand(0);
14195     SDValue RHS = Cond.getOperand(1);
14196     unsigned X86Opcode;
14197     unsigned X86Cond;
14198     SDVTList VTs;
14199     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14200     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14201     // X86ISD::INC).
14202     switch (CondOpcode) {
14203     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14204     case ISD::SADDO:
14205       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14206         if (C->isOne()) {
14207           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14208           break;
14209         }
14210       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14211     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14212     case ISD::SSUBO:
14213       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14214         if (C->isOne()) {
14215           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14216           break;
14217         }
14218       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14219     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14220     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14221     default: llvm_unreachable("unexpected overflowing operator");
14222     }
14223     if (Inverted)
14224       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14225     if (CondOpcode == ISD::UMULO)
14226       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14227                           MVT::i32);
14228     else
14229       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14230
14231     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14232
14233     if (CondOpcode == ISD::UMULO)
14234       Cond = X86Op.getValue(2);
14235     else
14236       Cond = X86Op.getValue(1);
14237
14238     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14239     addTest = false;
14240   } else {
14241     unsigned CondOpc;
14242     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14243       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14244       if (CondOpc == ISD::OR) {
14245         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14246         // two branches instead of an explicit OR instruction with a
14247         // separate test.
14248         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14249             isX86LogicalCmp(Cmp)) {
14250           CC = Cond.getOperand(0).getOperand(0);
14251           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14252                               Chain, Dest, CC, Cmp);
14253           CC = Cond.getOperand(1).getOperand(0);
14254           Cond = Cmp;
14255           addTest = false;
14256         }
14257       } else { // ISD::AND
14258         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14259         // two branches instead of an explicit AND instruction with a
14260         // separate test. However, we only do this if this block doesn't
14261         // have a fall-through edge, because this requires an explicit
14262         // jmp when the condition is false.
14263         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14264             isX86LogicalCmp(Cmp) &&
14265             Op.getNode()->hasOneUse()) {
14266           X86::CondCode CCode =
14267             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14268           CCode = X86::GetOppositeBranchCondition(CCode);
14269           CC = DAG.getConstant(CCode, dl, MVT::i8);
14270           SDNode *User = *Op.getNode()->use_begin();
14271           // Look for an unconditional branch following this conditional branch.
14272           // We need this because we need to reverse the successors in order
14273           // to implement FCMP_OEQ.
14274           if (User->getOpcode() == ISD::BR) {
14275             SDValue FalseBB = User->getOperand(1);
14276             SDNode *NewBR =
14277               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14278             assert(NewBR == User);
14279             (void)NewBR;
14280             Dest = FalseBB;
14281
14282             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14283                                 Chain, Dest, CC, Cmp);
14284             X86::CondCode CCode =
14285               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14286             CCode = X86::GetOppositeBranchCondition(CCode);
14287             CC = DAG.getConstant(CCode, dl, MVT::i8);
14288             Cond = Cmp;
14289             addTest = false;
14290           }
14291         }
14292       }
14293     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14294       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14295       // It should be transformed during dag combiner except when the condition
14296       // is set by a arithmetics with overflow node.
14297       X86::CondCode CCode =
14298         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14299       CCode = X86::GetOppositeBranchCondition(CCode);
14300       CC = DAG.getConstant(CCode, dl, MVT::i8);
14301       Cond = Cond.getOperand(0).getOperand(1);
14302       addTest = false;
14303     } else if (Cond.getOpcode() == ISD::SETCC &&
14304                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14305       // For FCMP_OEQ, we can emit
14306       // two branches instead of an explicit AND instruction with a
14307       // separate test. However, we only do this if this block doesn't
14308       // have a fall-through edge, because this requires an explicit
14309       // jmp when the condition is false.
14310       if (Op.getNode()->hasOneUse()) {
14311         SDNode *User = *Op.getNode()->use_begin();
14312         // Look for an unconditional branch following this conditional branch.
14313         // We need this because we need to reverse the successors in order
14314         // to implement FCMP_OEQ.
14315         if (User->getOpcode() == ISD::BR) {
14316           SDValue FalseBB = User->getOperand(1);
14317           SDNode *NewBR =
14318             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14319           assert(NewBR == User);
14320           (void)NewBR;
14321           Dest = FalseBB;
14322
14323           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14324                                     Cond.getOperand(0), Cond.getOperand(1));
14325           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14326           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14327           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14328                               Chain, Dest, CC, Cmp);
14329           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14330           Cond = Cmp;
14331           addTest = false;
14332         }
14333       }
14334     } else if (Cond.getOpcode() == ISD::SETCC &&
14335                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14336       // For FCMP_UNE, we can emit
14337       // two branches instead of an explicit AND instruction with a
14338       // separate test. However, we only do this if this block doesn't
14339       // have a fall-through edge, because this requires an explicit
14340       // jmp when the condition is false.
14341       if (Op.getNode()->hasOneUse()) {
14342         SDNode *User = *Op.getNode()->use_begin();
14343         // Look for an unconditional branch following this conditional branch.
14344         // We need this because we need to reverse the successors in order
14345         // to implement FCMP_UNE.
14346         if (User->getOpcode() == ISD::BR) {
14347           SDValue FalseBB = User->getOperand(1);
14348           SDNode *NewBR =
14349             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14350           assert(NewBR == User);
14351           (void)NewBR;
14352
14353           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14354                                     Cond.getOperand(0), Cond.getOperand(1));
14355           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14356           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14357           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14358                               Chain, Dest, CC, Cmp);
14359           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14360           Cond = Cmp;
14361           addTest = false;
14362           Dest = FalseBB;
14363         }
14364       }
14365     }
14366   }
14367
14368   if (addTest) {
14369     // Look pass the truncate if the high bits are known zero.
14370     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14371         Cond = Cond.getOperand(0);
14372
14373     // We know the result of AND is compared against zero. Try to match
14374     // it to BT.
14375     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14376       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14377       if (NewSetCC.getNode()) {
14378         CC = NewSetCC.getOperand(0);
14379         Cond = NewSetCC.getOperand(1);
14380         addTest = false;
14381       }
14382     }
14383   }
14384
14385   if (addTest) {
14386     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14387     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14388     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14389   }
14390   Cond = ConvertCmpIfNecessary(Cond, DAG);
14391   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14392                      Chain, Dest, CC, Cond);
14393 }
14394
14395 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14396 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14397 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14398 // that the guard pages used by the OS virtual memory manager are allocated in
14399 // correct sequence.
14400 SDValue
14401 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14402                                            SelectionDAG &DAG) const {
14403   MachineFunction &MF = DAG.getMachineFunction();
14404   bool SplitStack = MF.shouldSplitStack();
14405   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14406                SplitStack;
14407   SDLoc dl(Op);
14408
14409   if (!Lower) {
14410     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14411     SDNode* Node = Op.getNode();
14412
14413     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14414     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14415         " not tell us which reg is the stack pointer!");
14416     EVT VT = Node->getValueType(0);
14417     SDValue Tmp1 = SDValue(Node, 0);
14418     SDValue Tmp2 = SDValue(Node, 1);
14419     SDValue Tmp3 = Node->getOperand(2);
14420     SDValue Chain = Tmp1.getOperand(0);
14421
14422     // Chain the dynamic stack allocation so that it doesn't modify the stack
14423     // pointer when other instructions are using the stack.
14424     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14425         SDLoc(Node));
14426
14427     SDValue Size = Tmp2.getOperand(1);
14428     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14429     Chain = SP.getValue(1);
14430     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14431     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14432     unsigned StackAlign = TFI.getStackAlignment();
14433     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14434     if (Align > StackAlign)
14435       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14436           DAG.getConstant(-(uint64_t)Align, dl, VT));
14437     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14438
14439     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14440         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14441         SDLoc(Node));
14442
14443     SDValue Ops[2] = { Tmp1, Tmp2 };
14444     return DAG.getMergeValues(Ops, dl);
14445   }
14446
14447   // Get the inputs.
14448   SDValue Chain = Op.getOperand(0);
14449   SDValue Size  = Op.getOperand(1);
14450   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14451   EVT VT = Op.getNode()->getValueType(0);
14452
14453   bool Is64Bit = Subtarget->is64Bit();
14454   EVT SPTy = getPointerTy();
14455
14456   if (SplitStack) {
14457     MachineRegisterInfo &MRI = MF.getRegInfo();
14458
14459     if (Is64Bit) {
14460       // The 64 bit implementation of segmented stacks needs to clobber both r10
14461       // r11. This makes it impossible to use it along with nested parameters.
14462       const Function *F = MF.getFunction();
14463
14464       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14465            I != E; ++I)
14466         if (I->hasNestAttr())
14467           report_fatal_error("Cannot use segmented stacks with functions that "
14468                              "have nested arguments.");
14469     }
14470
14471     const TargetRegisterClass *AddrRegClass =
14472       getRegClassFor(getPointerTy());
14473     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14474     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14475     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14476                                 DAG.getRegister(Vreg, SPTy));
14477     SDValue Ops1[2] = { Value, Chain };
14478     return DAG.getMergeValues(Ops1, dl);
14479   } else {
14480     SDValue Flag;
14481     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14482
14483     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14484     Flag = Chain.getValue(1);
14485     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14486
14487     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14488
14489     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14490     unsigned SPReg = RegInfo->getStackRegister();
14491     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14492     Chain = SP.getValue(1);
14493
14494     if (Align) {
14495       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14496                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14497       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14498     }
14499
14500     SDValue Ops1[2] = { SP, Chain };
14501     return DAG.getMergeValues(Ops1, dl);
14502   }
14503 }
14504
14505 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14506   MachineFunction &MF = DAG.getMachineFunction();
14507   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14508
14509   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14510   SDLoc DL(Op);
14511
14512   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14513     // vastart just stores the address of the VarArgsFrameIndex slot into the
14514     // memory location argument.
14515     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14516                                    getPointerTy());
14517     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14518                         MachinePointerInfo(SV), false, false, 0);
14519   }
14520
14521   // __va_list_tag:
14522   //   gp_offset         (0 - 6 * 8)
14523   //   fp_offset         (48 - 48 + 8 * 16)
14524   //   overflow_arg_area (point to parameters coming in memory).
14525   //   reg_save_area
14526   SmallVector<SDValue, 8> MemOps;
14527   SDValue FIN = Op.getOperand(1);
14528   // Store gp_offset
14529   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14530                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14531                                                DL, MVT::i32),
14532                                FIN, MachinePointerInfo(SV), false, false, 0);
14533   MemOps.push_back(Store);
14534
14535   // Store fp_offset
14536   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14537                     FIN, DAG.getIntPtrConstant(4, DL));
14538   Store = DAG.getStore(Op.getOperand(0), DL,
14539                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14540                                        MVT::i32),
14541                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14542   MemOps.push_back(Store);
14543
14544   // Store ptr to overflow_arg_area
14545   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14546                     FIN, DAG.getIntPtrConstant(4, DL));
14547   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14548                                     getPointerTy());
14549   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14550                        MachinePointerInfo(SV, 8),
14551                        false, false, 0);
14552   MemOps.push_back(Store);
14553
14554   // Store ptr to reg_save_area.
14555   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14556                     FIN, DAG.getIntPtrConstant(8, DL));
14557   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14558                                     getPointerTy());
14559   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14560                        MachinePointerInfo(SV, 16), false, false, 0);
14561   MemOps.push_back(Store);
14562   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14563 }
14564
14565 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14566   assert(Subtarget->is64Bit() &&
14567          "LowerVAARG only handles 64-bit va_arg!");
14568   assert((Subtarget->isTargetLinux() ||
14569           Subtarget->isTargetDarwin()) &&
14570           "Unhandled target in LowerVAARG");
14571   assert(Op.getNode()->getNumOperands() == 4);
14572   SDValue Chain = Op.getOperand(0);
14573   SDValue SrcPtr = Op.getOperand(1);
14574   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14575   unsigned Align = Op.getConstantOperandVal(3);
14576   SDLoc dl(Op);
14577
14578   EVT ArgVT = Op.getNode()->getValueType(0);
14579   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14580   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14581   uint8_t ArgMode;
14582
14583   // Decide which area this value should be read from.
14584   // TODO: Implement the AMD64 ABI in its entirety. This simple
14585   // selection mechanism works only for the basic types.
14586   if (ArgVT == MVT::f80) {
14587     llvm_unreachable("va_arg for f80 not yet implemented");
14588   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14589     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14590   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14591     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14592   } else {
14593     llvm_unreachable("Unhandled argument type in LowerVAARG");
14594   }
14595
14596   if (ArgMode == 2) {
14597     // Sanity Check: Make sure using fp_offset makes sense.
14598     assert(!DAG.getTarget().Options.UseSoftFloat &&
14599            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14600                Attribute::NoImplicitFloat)) &&
14601            Subtarget->hasSSE1());
14602   }
14603
14604   // Insert VAARG_64 node into the DAG
14605   // VAARG_64 returns two values: Variable Argument Address, Chain
14606   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14607                        DAG.getConstant(ArgMode, dl, MVT::i8),
14608                        DAG.getConstant(Align, dl, MVT::i32)};
14609   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14610   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14611                                           VTs, InstOps, MVT::i64,
14612                                           MachinePointerInfo(SV),
14613                                           /*Align=*/0,
14614                                           /*Volatile=*/false,
14615                                           /*ReadMem=*/true,
14616                                           /*WriteMem=*/true);
14617   Chain = VAARG.getValue(1);
14618
14619   // Load the next argument and return it
14620   return DAG.getLoad(ArgVT, dl,
14621                      Chain,
14622                      VAARG,
14623                      MachinePointerInfo(),
14624                      false, false, false, 0);
14625 }
14626
14627 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14628                            SelectionDAG &DAG) {
14629   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14630   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14631   SDValue Chain = Op.getOperand(0);
14632   SDValue DstPtr = Op.getOperand(1);
14633   SDValue SrcPtr = Op.getOperand(2);
14634   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14635   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14636   SDLoc DL(Op);
14637
14638   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14639                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14640                        false, false,
14641                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14642 }
14643
14644 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14645 // amount is a constant. Takes immediate version of shift as input.
14646 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14647                                           SDValue SrcOp, uint64_t ShiftAmt,
14648                                           SelectionDAG &DAG) {
14649   MVT ElementType = VT.getVectorElementType();
14650
14651   // Fold this packed shift into its first operand if ShiftAmt is 0.
14652   if (ShiftAmt == 0)
14653     return SrcOp;
14654
14655   // Check for ShiftAmt >= element width
14656   if (ShiftAmt >= ElementType.getSizeInBits()) {
14657     if (Opc == X86ISD::VSRAI)
14658       ShiftAmt = ElementType.getSizeInBits() - 1;
14659     else
14660       return DAG.getConstant(0, dl, VT);
14661   }
14662
14663   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14664          && "Unknown target vector shift-by-constant node");
14665
14666   // Fold this packed vector shift into a build vector if SrcOp is a
14667   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14668   if (VT == SrcOp.getSimpleValueType() &&
14669       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14670     SmallVector<SDValue, 8> Elts;
14671     unsigned NumElts = SrcOp->getNumOperands();
14672     ConstantSDNode *ND;
14673
14674     switch(Opc) {
14675     default: llvm_unreachable(nullptr);
14676     case X86ISD::VSHLI:
14677       for (unsigned i=0; i!=NumElts; ++i) {
14678         SDValue CurrentOp = SrcOp->getOperand(i);
14679         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14680           Elts.push_back(CurrentOp);
14681           continue;
14682         }
14683         ND = cast<ConstantSDNode>(CurrentOp);
14684         const APInt &C = ND->getAPIntValue();
14685         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14686       }
14687       break;
14688     case X86ISD::VSRLI:
14689       for (unsigned i=0; i!=NumElts; ++i) {
14690         SDValue CurrentOp = SrcOp->getOperand(i);
14691         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14692           Elts.push_back(CurrentOp);
14693           continue;
14694         }
14695         ND = cast<ConstantSDNode>(CurrentOp);
14696         const APInt &C = ND->getAPIntValue();
14697         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14698       }
14699       break;
14700     case X86ISD::VSRAI:
14701       for (unsigned i=0; i!=NumElts; ++i) {
14702         SDValue CurrentOp = SrcOp->getOperand(i);
14703         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14704           Elts.push_back(CurrentOp);
14705           continue;
14706         }
14707         ND = cast<ConstantSDNode>(CurrentOp);
14708         const APInt &C = ND->getAPIntValue();
14709         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14710       }
14711       break;
14712     }
14713
14714     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14715   }
14716
14717   return DAG.getNode(Opc, dl, VT, SrcOp,
14718                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14719 }
14720
14721 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14722 // may or may not be a constant. Takes immediate version of shift as input.
14723 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14724                                    SDValue SrcOp, SDValue ShAmt,
14725                                    SelectionDAG &DAG) {
14726   MVT SVT = ShAmt.getSimpleValueType();
14727   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14728
14729   // Catch shift-by-constant.
14730   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14731     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14732                                       CShAmt->getZExtValue(), DAG);
14733
14734   // Change opcode to non-immediate version
14735   switch (Opc) {
14736     default: llvm_unreachable("Unknown target vector shift node");
14737     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14738     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14739     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14740   }
14741
14742   const X86Subtarget &Subtarget =
14743       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14744   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14745       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14746     // Let the shuffle legalizer expand this shift amount node.
14747     SDValue Op0 = ShAmt.getOperand(0);
14748     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14749     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14750   } else {
14751     // Need to build a vector containing shift amount.
14752     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14753     SmallVector<SDValue, 4> ShOps;
14754     ShOps.push_back(ShAmt);
14755     if (SVT == MVT::i32) {
14756       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14757       ShOps.push_back(DAG.getUNDEF(SVT));
14758     }
14759     ShOps.push_back(DAG.getUNDEF(SVT));
14760
14761     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14762     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14763   }
14764
14765   // The return type has to be a 128-bit type with the same element
14766   // type as the input type.
14767   MVT EltVT = VT.getVectorElementType();
14768   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14769
14770   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14771   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14772 }
14773
14774 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14775 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14776 /// necessary casting for \p Mask when lowering masking intrinsics.
14777 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14778                                     SDValue PreservedSrc,
14779                                     const X86Subtarget *Subtarget,
14780                                     SelectionDAG &DAG) {
14781     EVT VT = Op.getValueType();
14782     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14783                                   MVT::i1, VT.getVectorNumElements());
14784     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14785                                      Mask.getValueType().getSizeInBits());
14786     SDLoc dl(Op);
14787
14788     assert(MaskVT.isSimple() && "invalid mask type");
14789
14790     if (isAllOnes(Mask))
14791       return Op;
14792
14793     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14794     // are extracted by EXTRACT_SUBVECTOR.
14795     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14796                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14797                               DAG.getIntPtrConstant(0, dl));
14798
14799     switch (Op.getOpcode()) {
14800       default: break;
14801       case X86ISD::PCMPEQM:
14802       case X86ISD::PCMPGTM:
14803       case X86ISD::CMPM:
14804       case X86ISD::CMPMU:
14805         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14806     }
14807     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14808       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14809     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14810 }
14811
14812 /// \brief Creates an SDNode for a predicated scalar operation.
14813 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14814 /// The mask is comming as MVT::i8 and it should be truncated
14815 /// to MVT::i1 while lowering masking intrinsics.
14816 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14817 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14818 /// a scalar instruction.
14819 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14820                                     SDValue PreservedSrc,
14821                                     const X86Subtarget *Subtarget,
14822                                     SelectionDAG &DAG) {
14823     if (isAllOnes(Mask))
14824       return Op;
14825
14826     EVT VT = Op.getValueType();
14827     SDLoc dl(Op);
14828     // The mask should be of type MVT::i1
14829     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14830
14831     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14832       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14833     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14834 }
14835
14836 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14837                                        SelectionDAG &DAG) {
14838   SDLoc dl(Op);
14839   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14840   EVT VT = Op.getValueType();
14841   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14842   if (IntrData) {
14843     switch(IntrData->Type) {
14844     case INTR_TYPE_1OP:
14845       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14846     case INTR_TYPE_2OP:
14847       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14848         Op.getOperand(2));
14849     case INTR_TYPE_3OP:
14850       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14851         Op.getOperand(2), Op.getOperand(3));
14852     case INTR_TYPE_1OP_MASK_RM: {
14853       SDValue Src = Op.getOperand(1);
14854       SDValue Src0 = Op.getOperand(2);
14855       SDValue Mask = Op.getOperand(3);
14856       SDValue RoundingMode = Op.getOperand(4);
14857       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14858                                               RoundingMode),
14859                                   Mask, Src0, Subtarget, DAG);
14860     }
14861     case INTR_TYPE_SCALAR_MASK_RM: {
14862       SDValue Src1 = Op.getOperand(1);
14863       SDValue Src2 = Op.getOperand(2);
14864       SDValue Src0 = Op.getOperand(3);
14865       SDValue Mask = Op.getOperand(4);
14866       // There are 2 kinds of intrinsics in this group:
14867       // (1) With supress-all-exceptions (sae) - 6 operands
14868       // (2) With rounding mode and sae - 7 operands.
14869       if (Op.getNumOperands() == 6) {
14870         SDValue Sae  = Op.getOperand(5);
14871         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14872                                                 Sae),
14873                                     Mask, Src0, Subtarget, DAG);
14874       }
14875       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14876       SDValue RoundingMode  = Op.getOperand(5);
14877       SDValue Sae  = Op.getOperand(6);
14878       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14879                                               RoundingMode, Sae),
14880                                   Mask, Src0, Subtarget, DAG);
14881     }
14882     case INTR_TYPE_2OP_MASK: {
14883       SDValue Src1 = Op.getOperand(1);
14884       SDValue Src2 = Op.getOperand(2);
14885       SDValue PassThru = Op.getOperand(3);
14886       SDValue Mask = Op.getOperand(4);
14887       // We specify 2 possible opcodes for intrinsics with rounding modes.
14888       // First, we check if the intrinsic may have non-default rounding mode,
14889       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14890       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14891       if (IntrWithRoundingModeOpcode != 0) {
14892         SDValue Rnd = Op.getOperand(5);
14893         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14894         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14895           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14896                                       dl, Op.getValueType(),
14897                                       Src1, Src2, Rnd),
14898                                       Mask, PassThru, Subtarget, DAG);
14899         }
14900       }
14901       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14902                                               Src1,Src2),
14903                                   Mask, PassThru, Subtarget, DAG);
14904     }
14905     case FMA_OP_MASK: {
14906       SDValue Src1 = Op.getOperand(1);
14907       SDValue Src2 = Op.getOperand(2);
14908       SDValue Src3 = Op.getOperand(3);
14909       SDValue Mask = Op.getOperand(4);
14910       // We specify 2 possible opcodes for intrinsics with rounding modes.
14911       // First, we check if the intrinsic may have non-default rounding mode,
14912       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14913       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14914       if (IntrWithRoundingModeOpcode != 0) {
14915         SDValue Rnd = Op.getOperand(5);
14916         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14917             X86::STATIC_ROUNDING::CUR_DIRECTION)
14918           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14919                                                   dl, Op.getValueType(),
14920                                                   Src1, Src2, Src3, Rnd),
14921                                       Mask, Src1, Subtarget, DAG);
14922       }
14923       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14924                                               dl, Op.getValueType(),
14925                                               Src1, Src2, Src3),
14926                                   Mask, Src1, Subtarget, DAG);
14927     }
14928     case CMP_MASK:
14929     case CMP_MASK_CC: {
14930       // Comparison intrinsics with masks.
14931       // Example of transformation:
14932       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14933       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14934       // (i8 (bitcast
14935       //   (v8i1 (insert_subvector undef,
14936       //           (v2i1 (and (PCMPEQM %a, %b),
14937       //                      (extract_subvector
14938       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14939       EVT VT = Op.getOperand(1).getValueType();
14940       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14941                                     VT.getVectorNumElements());
14942       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14943       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14944                                        Mask.getValueType().getSizeInBits());
14945       SDValue Cmp;
14946       if (IntrData->Type == CMP_MASK_CC) {
14947         SDValue CC = Op.getOperand(3);
14948         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
14949         // We specify 2 possible opcodes for intrinsics with rounding modes.
14950         // First, we check if the intrinsic may have non-default rounding mode,
14951         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14952         if (IntrData->Opc1 != 0) {
14953           SDValue Rnd = Op.getOperand(5);
14954           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14955               X86::STATIC_ROUNDING::CUR_DIRECTION)
14956             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
14957                               Op.getOperand(2), CC, Rnd);
14958         }
14959         //default rounding mode
14960         if(!Cmp.getNode())
14961             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14962                               Op.getOperand(2), CC);
14963
14964       } else {
14965         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14966         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14967                           Op.getOperand(2));
14968       }
14969       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14970                                              DAG.getTargetConstant(0, dl,
14971                                                                    MaskVT),
14972                                              Subtarget, DAG);
14973       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14974                                 DAG.getUNDEF(BitcastVT), CmpMask,
14975                                 DAG.getIntPtrConstant(0, dl));
14976       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14977     }
14978     case COMI: { // Comparison intrinsics
14979       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14980       SDValue LHS = Op.getOperand(1);
14981       SDValue RHS = Op.getOperand(2);
14982       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
14983       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14984       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14985       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14986                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
14987       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14988     }
14989     case VSHIFT:
14990       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14991                                  Op.getOperand(1), Op.getOperand(2), DAG);
14992     case VSHIFT_MASK:
14993       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14994                                                       Op.getSimpleValueType(),
14995                                                       Op.getOperand(1),
14996                                                       Op.getOperand(2), DAG),
14997                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
14998                                   DAG);
14999     case COMPRESS_EXPAND_IN_REG: {
15000       SDValue Mask = Op.getOperand(3);
15001       SDValue DataToCompress = Op.getOperand(1);
15002       SDValue PassThru = Op.getOperand(2);
15003       if (isAllOnes(Mask)) // return data as is
15004         return Op.getOperand(1);
15005       EVT VT = Op.getValueType();
15006       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15007                                     VT.getVectorNumElements());
15008       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15009                                        Mask.getValueType().getSizeInBits());
15010       SDLoc dl(Op);
15011       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15012                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15013                                   DAG.getIntPtrConstant(0, dl));
15014
15015       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15016                          PassThru);
15017     }
15018     case BLEND: {
15019       SDValue Mask = Op.getOperand(3);
15020       EVT VT = Op.getValueType();
15021       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15022                                     VT.getVectorNumElements());
15023       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15024                                        Mask.getValueType().getSizeInBits());
15025       SDLoc dl(Op);
15026       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15027                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15028                                   DAG.getIntPtrConstant(0, dl));
15029       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15030                          Op.getOperand(2));
15031     }
15032     default:
15033       break;
15034     }
15035   }
15036
15037   switch (IntNo) {
15038   default: return SDValue();    // Don't custom lower most intrinsics.
15039
15040   case Intrinsic::x86_avx2_permd:
15041   case Intrinsic::x86_avx2_permps:
15042     // Operands intentionally swapped. Mask is last operand to intrinsic,
15043     // but second operand for node/instruction.
15044     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15045                        Op.getOperand(2), Op.getOperand(1));
15046
15047   case Intrinsic::x86_avx512_mask_valign_q_512:
15048   case Intrinsic::x86_avx512_mask_valign_d_512:
15049     // Vector source operands are swapped.
15050     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15051                                             Op.getValueType(), Op.getOperand(2),
15052                                             Op.getOperand(1),
15053                                             Op.getOperand(3)),
15054                                 Op.getOperand(5), Op.getOperand(4),
15055                                 Subtarget, DAG);
15056
15057   // ptest and testp intrinsics. The intrinsic these come from are designed to
15058   // return an integer value, not just an instruction so lower it to the ptest
15059   // or testp pattern and a setcc for the result.
15060   case Intrinsic::x86_sse41_ptestz:
15061   case Intrinsic::x86_sse41_ptestc:
15062   case Intrinsic::x86_sse41_ptestnzc:
15063   case Intrinsic::x86_avx_ptestz_256:
15064   case Intrinsic::x86_avx_ptestc_256:
15065   case Intrinsic::x86_avx_ptestnzc_256:
15066   case Intrinsic::x86_avx_vtestz_ps:
15067   case Intrinsic::x86_avx_vtestc_ps:
15068   case Intrinsic::x86_avx_vtestnzc_ps:
15069   case Intrinsic::x86_avx_vtestz_pd:
15070   case Intrinsic::x86_avx_vtestc_pd:
15071   case Intrinsic::x86_avx_vtestnzc_pd:
15072   case Intrinsic::x86_avx_vtestz_ps_256:
15073   case Intrinsic::x86_avx_vtestc_ps_256:
15074   case Intrinsic::x86_avx_vtestnzc_ps_256:
15075   case Intrinsic::x86_avx_vtestz_pd_256:
15076   case Intrinsic::x86_avx_vtestc_pd_256:
15077   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15078     bool IsTestPacked = false;
15079     unsigned X86CC;
15080     switch (IntNo) {
15081     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15082     case Intrinsic::x86_avx_vtestz_ps:
15083     case Intrinsic::x86_avx_vtestz_pd:
15084     case Intrinsic::x86_avx_vtestz_ps_256:
15085     case Intrinsic::x86_avx_vtestz_pd_256:
15086       IsTestPacked = true; // Fallthrough
15087     case Intrinsic::x86_sse41_ptestz:
15088     case Intrinsic::x86_avx_ptestz_256:
15089       // ZF = 1
15090       X86CC = X86::COND_E;
15091       break;
15092     case Intrinsic::x86_avx_vtestc_ps:
15093     case Intrinsic::x86_avx_vtestc_pd:
15094     case Intrinsic::x86_avx_vtestc_ps_256:
15095     case Intrinsic::x86_avx_vtestc_pd_256:
15096       IsTestPacked = true; // Fallthrough
15097     case Intrinsic::x86_sse41_ptestc:
15098     case Intrinsic::x86_avx_ptestc_256:
15099       // CF = 1
15100       X86CC = X86::COND_B;
15101       break;
15102     case Intrinsic::x86_avx_vtestnzc_ps:
15103     case Intrinsic::x86_avx_vtestnzc_pd:
15104     case Intrinsic::x86_avx_vtestnzc_ps_256:
15105     case Intrinsic::x86_avx_vtestnzc_pd_256:
15106       IsTestPacked = true; // Fallthrough
15107     case Intrinsic::x86_sse41_ptestnzc:
15108     case Intrinsic::x86_avx_ptestnzc_256:
15109       // ZF and CF = 0
15110       X86CC = X86::COND_A;
15111       break;
15112     }
15113
15114     SDValue LHS = Op.getOperand(1);
15115     SDValue RHS = Op.getOperand(2);
15116     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15117     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15118     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15119     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15120     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15121   }
15122   case Intrinsic::x86_avx512_kortestz_w:
15123   case Intrinsic::x86_avx512_kortestc_w: {
15124     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15125     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15126     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15127     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15128     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15129     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15130     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15131   }
15132
15133   case Intrinsic::x86_sse42_pcmpistria128:
15134   case Intrinsic::x86_sse42_pcmpestria128:
15135   case Intrinsic::x86_sse42_pcmpistric128:
15136   case Intrinsic::x86_sse42_pcmpestric128:
15137   case Intrinsic::x86_sse42_pcmpistrio128:
15138   case Intrinsic::x86_sse42_pcmpestrio128:
15139   case Intrinsic::x86_sse42_pcmpistris128:
15140   case Intrinsic::x86_sse42_pcmpestris128:
15141   case Intrinsic::x86_sse42_pcmpistriz128:
15142   case Intrinsic::x86_sse42_pcmpestriz128: {
15143     unsigned Opcode;
15144     unsigned X86CC;
15145     switch (IntNo) {
15146     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15147     case Intrinsic::x86_sse42_pcmpistria128:
15148       Opcode = X86ISD::PCMPISTRI;
15149       X86CC = X86::COND_A;
15150       break;
15151     case Intrinsic::x86_sse42_pcmpestria128:
15152       Opcode = X86ISD::PCMPESTRI;
15153       X86CC = X86::COND_A;
15154       break;
15155     case Intrinsic::x86_sse42_pcmpistric128:
15156       Opcode = X86ISD::PCMPISTRI;
15157       X86CC = X86::COND_B;
15158       break;
15159     case Intrinsic::x86_sse42_pcmpestric128:
15160       Opcode = X86ISD::PCMPESTRI;
15161       X86CC = X86::COND_B;
15162       break;
15163     case Intrinsic::x86_sse42_pcmpistrio128:
15164       Opcode = X86ISD::PCMPISTRI;
15165       X86CC = X86::COND_O;
15166       break;
15167     case Intrinsic::x86_sse42_pcmpestrio128:
15168       Opcode = X86ISD::PCMPESTRI;
15169       X86CC = X86::COND_O;
15170       break;
15171     case Intrinsic::x86_sse42_pcmpistris128:
15172       Opcode = X86ISD::PCMPISTRI;
15173       X86CC = X86::COND_S;
15174       break;
15175     case Intrinsic::x86_sse42_pcmpestris128:
15176       Opcode = X86ISD::PCMPESTRI;
15177       X86CC = X86::COND_S;
15178       break;
15179     case Intrinsic::x86_sse42_pcmpistriz128:
15180       Opcode = X86ISD::PCMPISTRI;
15181       X86CC = X86::COND_E;
15182       break;
15183     case Intrinsic::x86_sse42_pcmpestriz128:
15184       Opcode = X86ISD::PCMPESTRI;
15185       X86CC = X86::COND_E;
15186       break;
15187     }
15188     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15189     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15190     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15191     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15192                                 DAG.getConstant(X86CC, dl, MVT::i8),
15193                                 SDValue(PCMP.getNode(), 1));
15194     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15195   }
15196
15197   case Intrinsic::x86_sse42_pcmpistri128:
15198   case Intrinsic::x86_sse42_pcmpestri128: {
15199     unsigned Opcode;
15200     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15201       Opcode = X86ISD::PCMPISTRI;
15202     else
15203       Opcode = X86ISD::PCMPESTRI;
15204
15205     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15206     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15207     return DAG.getNode(Opcode, dl, VTs, NewOps);
15208   }
15209   }
15210 }
15211
15212 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15213                               SDValue Src, SDValue Mask, SDValue Base,
15214                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15215                               const X86Subtarget * Subtarget) {
15216   SDLoc dl(Op);
15217   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15218   assert(C && "Invalid scale type");
15219   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15220   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15221                              Index.getSimpleValueType().getVectorNumElements());
15222   SDValue MaskInReg;
15223   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15224   if (MaskC)
15225     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15226   else
15227     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15228   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15229   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15230   SDValue Segment = DAG.getRegister(0, MVT::i32);
15231   if (Src.getOpcode() == ISD::UNDEF)
15232     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15233   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15234   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15235   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15236   return DAG.getMergeValues(RetOps, dl);
15237 }
15238
15239 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15240                                SDValue Src, SDValue Mask, SDValue Base,
15241                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15242   SDLoc dl(Op);
15243   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15244   assert(C && "Invalid scale type");
15245   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15246   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15247   SDValue Segment = DAG.getRegister(0, MVT::i32);
15248   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15249                              Index.getSimpleValueType().getVectorNumElements());
15250   SDValue MaskInReg;
15251   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15252   if (MaskC)
15253     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15254   else
15255     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15256   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15257   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15258   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15259   return SDValue(Res, 1);
15260 }
15261
15262 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15263                                SDValue Mask, SDValue Base, SDValue Index,
15264                                SDValue ScaleOp, SDValue Chain) {
15265   SDLoc dl(Op);
15266   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15267   assert(C && "Invalid scale type");
15268   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15269   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15270   SDValue Segment = DAG.getRegister(0, MVT::i32);
15271   EVT MaskVT =
15272     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15273   SDValue MaskInReg;
15274   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15275   if (MaskC)
15276     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15277   else
15278     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15279   //SDVTList VTs = DAG.getVTList(MVT::Other);
15280   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15281   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15282   return SDValue(Res, 0);
15283 }
15284
15285 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15286 // read performance monitor counters (x86_rdpmc).
15287 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15288                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15289                               SmallVectorImpl<SDValue> &Results) {
15290   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15291   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15292   SDValue LO, HI;
15293
15294   // The ECX register is used to select the index of the performance counter
15295   // to read.
15296   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15297                                    N->getOperand(2));
15298   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15299
15300   // Reads the content of a 64-bit performance counter and returns it in the
15301   // registers EDX:EAX.
15302   if (Subtarget->is64Bit()) {
15303     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15304     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15305                             LO.getValue(2));
15306   } else {
15307     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15308     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15309                             LO.getValue(2));
15310   }
15311   Chain = HI.getValue(1);
15312
15313   if (Subtarget->is64Bit()) {
15314     // The EAX register is loaded with the low-order 32 bits. The EDX register
15315     // is loaded with the supported high-order bits of the counter.
15316     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15317                               DAG.getConstant(32, DL, MVT::i8));
15318     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15319     Results.push_back(Chain);
15320     return;
15321   }
15322
15323   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15324   SDValue Ops[] = { LO, HI };
15325   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15326   Results.push_back(Pair);
15327   Results.push_back(Chain);
15328 }
15329
15330 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15331 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15332 // also used to custom lower READCYCLECOUNTER nodes.
15333 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15334                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15335                               SmallVectorImpl<SDValue> &Results) {
15336   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15337   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15338   SDValue LO, HI;
15339
15340   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15341   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15342   // and the EAX register is loaded with the low-order 32 bits.
15343   if (Subtarget->is64Bit()) {
15344     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15345     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15346                             LO.getValue(2));
15347   } else {
15348     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15349     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15350                             LO.getValue(2));
15351   }
15352   SDValue Chain = HI.getValue(1);
15353
15354   if (Opcode == X86ISD::RDTSCP_DAG) {
15355     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15356
15357     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15358     // the ECX register. Add 'ecx' explicitly to the chain.
15359     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15360                                      HI.getValue(2));
15361     // Explicitly store the content of ECX at the location passed in input
15362     // to the 'rdtscp' intrinsic.
15363     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15364                          MachinePointerInfo(), false, false, 0);
15365   }
15366
15367   if (Subtarget->is64Bit()) {
15368     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15369     // the EAX register is loaded with the low-order 32 bits.
15370     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15371                               DAG.getConstant(32, DL, MVT::i8));
15372     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15373     Results.push_back(Chain);
15374     return;
15375   }
15376
15377   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15378   SDValue Ops[] = { LO, HI };
15379   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15380   Results.push_back(Pair);
15381   Results.push_back(Chain);
15382 }
15383
15384 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15385                                      SelectionDAG &DAG) {
15386   SmallVector<SDValue, 2> Results;
15387   SDLoc DL(Op);
15388   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15389                           Results);
15390   return DAG.getMergeValues(Results, DL);
15391 }
15392
15393
15394 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15395                                       SelectionDAG &DAG) {
15396   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15397
15398   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15399   if (!IntrData)
15400     return SDValue();
15401
15402   SDLoc dl(Op);
15403   switch(IntrData->Type) {
15404   default:
15405     llvm_unreachable("Unknown Intrinsic Type");
15406     break;
15407   case RDSEED:
15408   case RDRAND: {
15409     // Emit the node with the right value type.
15410     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15411     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15412
15413     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15414     // Otherwise return the value from Rand, which is always 0, casted to i32.
15415     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15416                       DAG.getConstant(1, dl, Op->getValueType(1)),
15417                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15418                       SDValue(Result.getNode(), 1) };
15419     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15420                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15421                                   Ops);
15422
15423     // Return { result, isValid, chain }.
15424     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15425                        SDValue(Result.getNode(), 2));
15426   }
15427   case GATHER: {
15428   //gather(v1, mask, index, base, scale);
15429     SDValue Chain = Op.getOperand(0);
15430     SDValue Src   = Op.getOperand(2);
15431     SDValue Base  = Op.getOperand(3);
15432     SDValue Index = Op.getOperand(4);
15433     SDValue Mask  = Op.getOperand(5);
15434     SDValue Scale = Op.getOperand(6);
15435     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15436                          Chain, Subtarget);
15437   }
15438   case SCATTER: {
15439   //scatter(base, mask, index, v1, scale);
15440     SDValue Chain = Op.getOperand(0);
15441     SDValue Base  = Op.getOperand(2);
15442     SDValue Mask  = Op.getOperand(3);
15443     SDValue Index = Op.getOperand(4);
15444     SDValue Src   = Op.getOperand(5);
15445     SDValue Scale = Op.getOperand(6);
15446     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15447                           Scale, Chain);
15448   }
15449   case PREFETCH: {
15450     SDValue Hint = Op.getOperand(6);
15451     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15452     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15453     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15454     SDValue Chain = Op.getOperand(0);
15455     SDValue Mask  = Op.getOperand(2);
15456     SDValue Index = Op.getOperand(3);
15457     SDValue Base  = Op.getOperand(4);
15458     SDValue Scale = Op.getOperand(5);
15459     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15460   }
15461   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15462   case RDTSC: {
15463     SmallVector<SDValue, 2> Results;
15464     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15465                             Results);
15466     return DAG.getMergeValues(Results, dl);
15467   }
15468   // Read Performance Monitoring Counters.
15469   case RDPMC: {
15470     SmallVector<SDValue, 2> Results;
15471     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15472     return DAG.getMergeValues(Results, dl);
15473   }
15474   // XTEST intrinsics.
15475   case XTEST: {
15476     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15477     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15478     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15479                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15480                                 InTrans);
15481     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15482     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15483                        Ret, SDValue(InTrans.getNode(), 1));
15484   }
15485   // ADC/ADCX/SBB
15486   case ADX: {
15487     SmallVector<SDValue, 2> Results;
15488     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15489     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15490     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15491                                 DAG.getConstant(-1, dl, MVT::i8));
15492     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15493                               Op.getOperand(4), GenCF.getValue(1));
15494     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15495                                  Op.getOperand(5), MachinePointerInfo(),
15496                                  false, false, 0);
15497     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15498                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15499                                 Res.getValue(1));
15500     Results.push_back(SetCC);
15501     Results.push_back(Store);
15502     return DAG.getMergeValues(Results, dl);
15503   }
15504   case COMPRESS_TO_MEM: {
15505     SDLoc dl(Op);
15506     SDValue Mask = Op.getOperand(4);
15507     SDValue DataToCompress = Op.getOperand(3);
15508     SDValue Addr = Op.getOperand(2);
15509     SDValue Chain = Op.getOperand(0);
15510
15511     if (isAllOnes(Mask)) // return just a store
15512       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15513                           MachinePointerInfo(), false, false, 0);
15514
15515     EVT VT = DataToCompress.getValueType();
15516     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15517                                   VT.getVectorNumElements());
15518     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15519                                      Mask.getValueType().getSizeInBits());
15520     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15521                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15522                                 DAG.getIntPtrConstant(0, dl));
15523
15524     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15525                                       DataToCompress, DAG.getUNDEF(VT));
15526     return DAG.getStore(Chain, dl, Compressed, Addr,
15527                         MachinePointerInfo(), false, false, 0);
15528   }
15529   case EXPAND_FROM_MEM: {
15530     SDLoc dl(Op);
15531     SDValue Mask = Op.getOperand(4);
15532     SDValue PathThru = Op.getOperand(3);
15533     SDValue Addr = Op.getOperand(2);
15534     SDValue Chain = Op.getOperand(0);
15535     EVT VT = Op.getValueType();
15536
15537     if (isAllOnes(Mask)) // return just a load
15538       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15539                          false, 0);
15540     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15541                                   VT.getVectorNumElements());
15542     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15543                                      Mask.getValueType().getSizeInBits());
15544     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15545                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15546                                 DAG.getIntPtrConstant(0, dl));
15547
15548     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15549                                    false, false, false, 0);
15550
15551     SDValue Results[] = {
15552         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15553         Chain};
15554     return DAG.getMergeValues(Results, dl);
15555   }
15556   }
15557 }
15558
15559 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15560                                            SelectionDAG &DAG) const {
15561   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15562   MFI->setReturnAddressIsTaken(true);
15563
15564   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15565     return SDValue();
15566
15567   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15568   SDLoc dl(Op);
15569   EVT PtrVT = getPointerTy();
15570
15571   if (Depth > 0) {
15572     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15573     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15574     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15575     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15576                        DAG.getNode(ISD::ADD, dl, PtrVT,
15577                                    FrameAddr, Offset),
15578                        MachinePointerInfo(), false, false, false, 0);
15579   }
15580
15581   // Just load the return address.
15582   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15583   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15584                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15585 }
15586
15587 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15588   MachineFunction &MF = DAG.getMachineFunction();
15589   MachineFrameInfo *MFI = MF.getFrameInfo();
15590   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15591   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15592   EVT VT = Op.getValueType();
15593
15594   MFI->setFrameAddressIsTaken(true);
15595
15596   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15597     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15598     // is not possible to crawl up the stack without looking at the unwind codes
15599     // simultaneously.
15600     int FrameAddrIndex = FuncInfo->getFAIndex();
15601     if (!FrameAddrIndex) {
15602       // Set up a frame object for the return address.
15603       unsigned SlotSize = RegInfo->getSlotSize();
15604       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15605           SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15606       FuncInfo->setFAIndex(FrameAddrIndex);
15607     }
15608     return DAG.getFrameIndex(FrameAddrIndex, VT);
15609   }
15610
15611   unsigned FrameReg =
15612       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15613   SDLoc dl(Op);  // FIXME probably not meaningful
15614   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15615   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15616           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15617          "Invalid Frame Register!");
15618   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15619   while (Depth--)
15620     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15621                             MachinePointerInfo(),
15622                             false, false, false, 0);
15623   return FrameAddr;
15624 }
15625
15626 // FIXME? Maybe this could be a TableGen attribute on some registers and
15627 // this table could be generated automatically from RegInfo.
15628 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15629                                               EVT VT) const {
15630   unsigned Reg = StringSwitch<unsigned>(RegName)
15631                        .Case("esp", X86::ESP)
15632                        .Case("rsp", X86::RSP)
15633                        .Default(0);
15634   if (Reg)
15635     return Reg;
15636   report_fatal_error("Invalid register name global variable");
15637 }
15638
15639 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15640                                                      SelectionDAG &DAG) const {
15641   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15642   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15643 }
15644
15645 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15646   SDValue Chain     = Op.getOperand(0);
15647   SDValue Offset    = Op.getOperand(1);
15648   SDValue Handler   = Op.getOperand(2);
15649   SDLoc dl      (Op);
15650
15651   EVT PtrVT = getPointerTy();
15652   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15653   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15654   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15655           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15656          "Invalid Frame Register!");
15657   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15658   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15659
15660   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15661                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15662                                                        dl));
15663   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15664   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15665                        false, false, 0);
15666   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15667
15668   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15669                      DAG.getRegister(StoreAddrReg, PtrVT));
15670 }
15671
15672 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15673                                                SelectionDAG &DAG) const {
15674   SDLoc DL(Op);
15675   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15676                      DAG.getVTList(MVT::i32, MVT::Other),
15677                      Op.getOperand(0), Op.getOperand(1));
15678 }
15679
15680 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15681                                                 SelectionDAG &DAG) const {
15682   SDLoc DL(Op);
15683   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15684                      Op.getOperand(0), Op.getOperand(1));
15685 }
15686
15687 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15688   return Op.getOperand(0);
15689 }
15690
15691 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15692                                                 SelectionDAG &DAG) const {
15693   SDValue Root = Op.getOperand(0);
15694   SDValue Trmp = Op.getOperand(1); // trampoline
15695   SDValue FPtr = Op.getOperand(2); // nested function
15696   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15697   SDLoc dl (Op);
15698
15699   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15700   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15701
15702   if (Subtarget->is64Bit()) {
15703     SDValue OutChains[6];
15704
15705     // Large code-model.
15706     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15707     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15708
15709     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15710     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15711
15712     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15713
15714     // Load the pointer to the nested function into R11.
15715     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15716     SDValue Addr = Trmp;
15717     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15718                                 Addr, MachinePointerInfo(TrmpAddr),
15719                                 false, false, 0);
15720
15721     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15722                        DAG.getConstant(2, dl, MVT::i64));
15723     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15724                                 MachinePointerInfo(TrmpAddr, 2),
15725                                 false, false, 2);
15726
15727     // Load the 'nest' parameter value into R10.
15728     // R10 is specified in X86CallingConv.td
15729     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15730     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15731                        DAG.getConstant(10, dl, MVT::i64));
15732     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15733                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15734                                 false, false, 0);
15735
15736     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15737                        DAG.getConstant(12, dl, MVT::i64));
15738     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15739                                 MachinePointerInfo(TrmpAddr, 12),
15740                                 false, false, 2);
15741
15742     // Jump to the nested function.
15743     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15744     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15745                        DAG.getConstant(20, dl, MVT::i64));
15746     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15747                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15748                                 false, false, 0);
15749
15750     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15751     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15752                        DAG.getConstant(22, dl, MVT::i64));
15753     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15754                                 Addr, MachinePointerInfo(TrmpAddr, 22),
15755                                 false, false, 0);
15756
15757     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15758   } else {
15759     const Function *Func =
15760       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15761     CallingConv::ID CC = Func->getCallingConv();
15762     unsigned NestReg;
15763
15764     switch (CC) {
15765     default:
15766       llvm_unreachable("Unsupported calling convention");
15767     case CallingConv::C:
15768     case CallingConv::X86_StdCall: {
15769       // Pass 'nest' parameter in ECX.
15770       // Must be kept in sync with X86CallingConv.td
15771       NestReg = X86::ECX;
15772
15773       // Check that ECX wasn't needed by an 'inreg' parameter.
15774       FunctionType *FTy = Func->getFunctionType();
15775       const AttributeSet &Attrs = Func->getAttributes();
15776
15777       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15778         unsigned InRegCount = 0;
15779         unsigned Idx = 1;
15780
15781         for (FunctionType::param_iterator I = FTy->param_begin(),
15782              E = FTy->param_end(); I != E; ++I, ++Idx)
15783           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15784             // FIXME: should only count parameters that are lowered to integers.
15785             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15786
15787         if (InRegCount > 2) {
15788           report_fatal_error("Nest register in use - reduce number of inreg"
15789                              " parameters!");
15790         }
15791       }
15792       break;
15793     }
15794     case CallingConv::X86_FastCall:
15795     case CallingConv::X86_ThisCall:
15796     case CallingConv::Fast:
15797       // Pass 'nest' parameter in EAX.
15798       // Must be kept in sync with X86CallingConv.td
15799       NestReg = X86::EAX;
15800       break;
15801     }
15802
15803     SDValue OutChains[4];
15804     SDValue Addr, Disp;
15805
15806     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15807                        DAG.getConstant(10, dl, MVT::i32));
15808     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15809
15810     // This is storing the opcode for MOV32ri.
15811     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15812     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15813     OutChains[0] = DAG.getStore(Root, dl,
15814                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15815                                 Trmp, MachinePointerInfo(TrmpAddr),
15816                                 false, false, 0);
15817
15818     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15819                        DAG.getConstant(1, dl, MVT::i32));
15820     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15821                                 MachinePointerInfo(TrmpAddr, 1),
15822                                 false, false, 1);
15823
15824     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15825     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15826                        DAG.getConstant(5, dl, MVT::i32));
15827     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15828                                 Addr, MachinePointerInfo(TrmpAddr, 5),
15829                                 false, false, 1);
15830
15831     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15832                        DAG.getConstant(6, dl, MVT::i32));
15833     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15834                                 MachinePointerInfo(TrmpAddr, 6),
15835                                 false, false, 1);
15836
15837     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15838   }
15839 }
15840
15841 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15842                                             SelectionDAG &DAG) const {
15843   /*
15844    The rounding mode is in bits 11:10 of FPSR, and has the following
15845    settings:
15846      00 Round to nearest
15847      01 Round to -inf
15848      10 Round to +inf
15849      11 Round to 0
15850
15851   FLT_ROUNDS, on the other hand, expects the following:
15852     -1 Undefined
15853      0 Round to 0
15854      1 Round to nearest
15855      2 Round to +inf
15856      3 Round to -inf
15857
15858   To perform the conversion, we do:
15859     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15860   */
15861
15862   MachineFunction &MF = DAG.getMachineFunction();
15863   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15864   unsigned StackAlignment = TFI.getStackAlignment();
15865   MVT VT = Op.getSimpleValueType();
15866   SDLoc DL(Op);
15867
15868   // Save FP Control Word to stack slot
15869   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15870   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15871
15872   MachineMemOperand *MMO =
15873    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15874                            MachineMemOperand::MOStore, 2, 2);
15875
15876   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15877   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15878                                           DAG.getVTList(MVT::Other),
15879                                           Ops, MVT::i16, MMO);
15880
15881   // Load FP Control Word from stack slot
15882   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15883                             MachinePointerInfo(), false, false, false, 0);
15884
15885   // Transform as necessary
15886   SDValue CWD1 =
15887     DAG.getNode(ISD::SRL, DL, MVT::i16,
15888                 DAG.getNode(ISD::AND, DL, MVT::i16,
15889                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
15890                 DAG.getConstant(11, DL, MVT::i8));
15891   SDValue CWD2 =
15892     DAG.getNode(ISD::SRL, DL, MVT::i16,
15893                 DAG.getNode(ISD::AND, DL, MVT::i16,
15894                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
15895                 DAG.getConstant(9, DL, MVT::i8));
15896
15897   SDValue RetVal =
15898     DAG.getNode(ISD::AND, DL, MVT::i16,
15899                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15900                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15901                             DAG.getConstant(1, DL, MVT::i16)),
15902                 DAG.getConstant(3, DL, MVT::i16));
15903
15904   return DAG.getNode((VT.getSizeInBits() < 16 ?
15905                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15906 }
15907
15908 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15909   MVT VT = Op.getSimpleValueType();
15910   EVT OpVT = VT;
15911   unsigned NumBits = VT.getSizeInBits();
15912   SDLoc dl(Op);
15913
15914   Op = Op.getOperand(0);
15915   if (VT == MVT::i8) {
15916     // Zero extend to i32 since there is not an i8 bsr.
15917     OpVT = MVT::i32;
15918     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15919   }
15920
15921   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15922   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15923   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15924
15925   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15926   SDValue Ops[] = {
15927     Op,
15928     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
15929     DAG.getConstant(X86::COND_E, dl, MVT::i8),
15930     Op.getValue(1)
15931   };
15932   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15933
15934   // Finally xor with NumBits-1.
15935   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15936                    DAG.getConstant(NumBits - 1, dl, OpVT));
15937
15938   if (VT == MVT::i8)
15939     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15940   return Op;
15941 }
15942
15943 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15944   MVT VT = Op.getSimpleValueType();
15945   EVT OpVT = VT;
15946   unsigned NumBits = VT.getSizeInBits();
15947   SDLoc dl(Op);
15948
15949   Op = Op.getOperand(0);
15950   if (VT == MVT::i8) {
15951     // Zero extend to i32 since there is not an i8 bsr.
15952     OpVT = MVT::i32;
15953     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15954   }
15955
15956   // Issue a bsr (scan bits in reverse).
15957   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15958   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15959
15960   // And xor with NumBits-1.
15961   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15962                    DAG.getConstant(NumBits - 1, dl, OpVT));
15963
15964   if (VT == MVT::i8)
15965     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15966   return Op;
15967 }
15968
15969 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15970   MVT VT = Op.getSimpleValueType();
15971   unsigned NumBits = VT.getSizeInBits();
15972   SDLoc dl(Op);
15973   Op = Op.getOperand(0);
15974
15975   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15976   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15977   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15978
15979   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15980   SDValue Ops[] = {
15981     Op,
15982     DAG.getConstant(NumBits, dl, VT),
15983     DAG.getConstant(X86::COND_E, dl, MVT::i8),
15984     Op.getValue(1)
15985   };
15986   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15987 }
15988
15989 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15990 // ones, and then concatenate the result back.
15991 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15992   MVT VT = Op.getSimpleValueType();
15993
15994   assert(VT.is256BitVector() && VT.isInteger() &&
15995          "Unsupported value type for operation");
15996
15997   unsigned NumElems = VT.getVectorNumElements();
15998   SDLoc dl(Op);
15999
16000   // Extract the LHS vectors
16001   SDValue LHS = Op.getOperand(0);
16002   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16003   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16004
16005   // Extract the RHS vectors
16006   SDValue RHS = Op.getOperand(1);
16007   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16008   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16009
16010   MVT EltVT = VT.getVectorElementType();
16011   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16012
16013   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16014                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16015                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16016 }
16017
16018 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16019   assert(Op.getSimpleValueType().is256BitVector() &&
16020          Op.getSimpleValueType().isInteger() &&
16021          "Only handle AVX 256-bit vector integer operation");
16022   return Lower256IntArith(Op, DAG);
16023 }
16024
16025 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16026   assert(Op.getSimpleValueType().is256BitVector() &&
16027          Op.getSimpleValueType().isInteger() &&
16028          "Only handle AVX 256-bit vector integer operation");
16029   return Lower256IntArith(Op, DAG);
16030 }
16031
16032 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16033                         SelectionDAG &DAG) {
16034   SDLoc dl(Op);
16035   MVT VT = Op.getSimpleValueType();
16036
16037   // Decompose 256-bit ops into smaller 128-bit ops.
16038   if (VT.is256BitVector() && !Subtarget->hasInt256())
16039     return Lower256IntArith(Op, DAG);
16040
16041   SDValue A = Op.getOperand(0);
16042   SDValue B = Op.getOperand(1);
16043
16044   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16045   // pairs, multiply and truncate.
16046   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16047     if (Subtarget->hasInt256()) {
16048       if (VT == MVT::v32i8) {
16049         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16050         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16051         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16052         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16053         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16054         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16055         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16056         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16057                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16058                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16059       }
16060
16061       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16062       return DAG.getNode(
16063           ISD::TRUNCATE, dl, VT,
16064           DAG.getNode(ISD::MUL, dl, ExVT,
16065                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16066                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16067     }
16068
16069     assert(VT == MVT::v16i8 &&
16070            "Pre-AVX2 support only supports v16i8 multiplication");
16071     MVT ExVT = MVT::v8i16;
16072
16073     // Extract the lo parts and sign extend to i16
16074     SDValue ALo, BLo;
16075     if (Subtarget->hasSSE41()) {
16076       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16077       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16078     } else {
16079       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16080                               -1, 4, -1, 5, -1, 6, -1, 7};
16081       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16082       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16083       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16084       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16085       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16086       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16087     }
16088
16089     // Extract the hi parts and sign extend to i16
16090     SDValue AHi, BHi;
16091     if (Subtarget->hasSSE41()) {
16092       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16093                               -1, -1, -1, -1, -1, -1, -1, -1};
16094       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16095       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16096       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16097       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16098     } else {
16099       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16100                               -1, 12, -1, 13, -1, 14, -1, 15};
16101       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16102       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16103       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16104       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16105       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16106       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16107     }
16108
16109     // Multiply, mask the lower 8bits of the lo/hi results and pack
16110     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16111     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16112     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16113     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16114     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16115   }
16116
16117   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16118   if (VT == MVT::v4i32) {
16119     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16120            "Should not custom lower when pmuldq is available!");
16121
16122     // Extract the odd parts.
16123     static const int UnpackMask[] = { 1, -1, 3, -1 };
16124     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16125     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16126
16127     // Multiply the even parts.
16128     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16129     // Now multiply odd parts.
16130     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16131
16132     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16133     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16134
16135     // Merge the two vectors back together with a shuffle. This expands into 2
16136     // shuffles.
16137     static const int ShufMask[] = { 0, 4, 2, 6 };
16138     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16139   }
16140
16141   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16142          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16143
16144   //  Ahi = psrlqi(a, 32);
16145   //  Bhi = psrlqi(b, 32);
16146   //
16147   //  AloBlo = pmuludq(a, b);
16148   //  AloBhi = pmuludq(a, Bhi);
16149   //  AhiBlo = pmuludq(Ahi, b);
16150
16151   //  AloBhi = psllqi(AloBhi, 32);
16152   //  AhiBlo = psllqi(AhiBlo, 32);
16153   //  return AloBlo + AloBhi + AhiBlo;
16154
16155   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16156   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16157
16158   // Bit cast to 32-bit vectors for MULUDQ
16159   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16160                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16161   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16162   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16163   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16164   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16165
16166   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16167   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16168   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16169
16170   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16171   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16172
16173   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16174   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16175 }
16176
16177 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16178   assert(Subtarget->isTargetWin64() && "Unexpected target");
16179   EVT VT = Op.getValueType();
16180   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16181          "Unexpected return type for lowering");
16182
16183   RTLIB::Libcall LC;
16184   bool isSigned;
16185   switch (Op->getOpcode()) {
16186   default: llvm_unreachable("Unexpected request for libcall!");
16187   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16188   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16189   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16190   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16191   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16192   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16193   }
16194
16195   SDLoc dl(Op);
16196   SDValue InChain = DAG.getEntryNode();
16197
16198   TargetLowering::ArgListTy Args;
16199   TargetLowering::ArgListEntry Entry;
16200   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16201     EVT ArgVT = Op->getOperand(i).getValueType();
16202     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16203            "Unexpected argument type for lowering");
16204     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16205     Entry.Node = StackPtr;
16206     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16207                            false, false, 16);
16208     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16209     Entry.Ty = PointerType::get(ArgTy,0);
16210     Entry.isSExt = false;
16211     Entry.isZExt = false;
16212     Args.push_back(Entry);
16213   }
16214
16215   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16216                                          getPointerTy());
16217
16218   TargetLowering::CallLoweringInfo CLI(DAG);
16219   CLI.setDebugLoc(dl).setChain(InChain)
16220     .setCallee(getLibcallCallingConv(LC),
16221                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16222                Callee, std::move(Args), 0)
16223     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16224
16225   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16226   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16227 }
16228
16229 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16230                              SelectionDAG &DAG) {
16231   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16232   EVT VT = Op0.getValueType();
16233   SDLoc dl(Op);
16234
16235   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16236          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16237
16238   // PMULxD operations multiply each even value (starting at 0) of LHS with
16239   // the related value of RHS and produce a widen result.
16240   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16241   // => <2 x i64> <ae|cg>
16242   //
16243   // In other word, to have all the results, we need to perform two PMULxD:
16244   // 1. one with the even values.
16245   // 2. one with the odd values.
16246   // To achieve #2, with need to place the odd values at an even position.
16247   //
16248   // Place the odd value at an even position (basically, shift all values 1
16249   // step to the left):
16250   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16251   // <a|b|c|d> => <b|undef|d|undef>
16252   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16253   // <e|f|g|h> => <f|undef|h|undef>
16254   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16255
16256   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16257   // ints.
16258   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16259   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16260   unsigned Opcode =
16261       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16262   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16263   // => <2 x i64> <ae|cg>
16264   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16265                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16266   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16267   // => <2 x i64> <bf|dh>
16268   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16269                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16270
16271   // Shuffle it back into the right order.
16272   SDValue Highs, Lows;
16273   if (VT == MVT::v8i32) {
16274     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16275     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16276     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16277     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16278   } else {
16279     const int HighMask[] = {1, 5, 3, 7};
16280     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16281     const int LowMask[] = {0, 4, 2, 6};
16282     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16283   }
16284
16285   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16286   // unsigned multiply.
16287   if (IsSigned && !Subtarget->hasSSE41()) {
16288     SDValue ShAmt =
16289         DAG.getConstant(31, dl,
16290                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16291     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16292                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16293     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16294                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16295
16296     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16297     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16298   }
16299
16300   // The first result of MUL_LOHI is actually the low value, followed by the
16301   // high value.
16302   SDValue Ops[] = {Lows, Highs};
16303   return DAG.getMergeValues(Ops, dl);
16304 }
16305
16306 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16307                                          const X86Subtarget *Subtarget) {
16308   MVT VT = Op.getSimpleValueType();
16309   SDLoc dl(Op);
16310   SDValue R = Op.getOperand(0);
16311   SDValue Amt = Op.getOperand(1);
16312
16313   // Optimize shl/srl/sra with constant shift amount.
16314   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16315     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16316       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16317
16318       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16319           (Subtarget->hasInt256() &&
16320            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16321           (Subtarget->hasAVX512() &&
16322            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16323         if (Op.getOpcode() == ISD::SHL)
16324           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16325                                             DAG);
16326         if (Op.getOpcode() == ISD::SRL)
16327           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16328                                             DAG);
16329         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16330           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16331                                             DAG);
16332       }
16333
16334       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16335         unsigned NumElts = VT.getVectorNumElements();
16336         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16337
16338         if (Op.getOpcode() == ISD::SHL) {
16339           // Make a large shift.
16340           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16341                                                    R, ShiftAmt, DAG);
16342           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16343           // Zero out the rightmost bits.
16344           SmallVector<SDValue, 32> V(
16345               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16346           return DAG.getNode(ISD::AND, dl, VT, SHL,
16347                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16348         }
16349         if (Op.getOpcode() == ISD::SRL) {
16350           // Make a large shift.
16351           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16352                                                    R, ShiftAmt, DAG);
16353           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16354           // Zero out the leftmost bits.
16355           SmallVector<SDValue, 32> V(
16356               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16357           return DAG.getNode(ISD::AND, dl, VT, SRL,
16358                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16359         }
16360         if (Op.getOpcode() == ISD::SRA) {
16361           if (ShiftAmt == 7) {
16362             // R s>> 7  ===  R s< 0
16363             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16364             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16365           }
16366
16367           // R s>> a === ((R u>> a) ^ m) - m
16368           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16369           SmallVector<SDValue, 32> V(NumElts,
16370                                      DAG.getConstant(128 >> ShiftAmt, dl,
16371                                                      MVT::i8));
16372           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16373           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16374           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16375           return Res;
16376         }
16377         llvm_unreachable("Unknown shift opcode.");
16378       }
16379     }
16380   }
16381
16382   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16383   if (!Subtarget->is64Bit() &&
16384       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16385       Amt.getOpcode() == ISD::BITCAST &&
16386       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16387     Amt = Amt.getOperand(0);
16388     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16389                      VT.getVectorNumElements();
16390     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16391     uint64_t ShiftAmt = 0;
16392     for (unsigned i = 0; i != Ratio; ++i) {
16393       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16394       if (!C)
16395         return SDValue();
16396       // 6 == Log2(64)
16397       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16398     }
16399     // Check remaining shift amounts.
16400     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16401       uint64_t ShAmt = 0;
16402       for (unsigned j = 0; j != Ratio; ++j) {
16403         ConstantSDNode *C =
16404           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16405         if (!C)
16406           return SDValue();
16407         // 6 == Log2(64)
16408         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16409       }
16410       if (ShAmt != ShiftAmt)
16411         return SDValue();
16412     }
16413     switch (Op.getOpcode()) {
16414     default:
16415       llvm_unreachable("Unknown shift opcode!");
16416     case ISD::SHL:
16417       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16418                                         DAG);
16419     case ISD::SRL:
16420       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16421                                         DAG);
16422     case ISD::SRA:
16423       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16424                                         DAG);
16425     }
16426   }
16427
16428   return SDValue();
16429 }
16430
16431 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16432                                         const X86Subtarget* Subtarget) {
16433   MVT VT = Op.getSimpleValueType();
16434   SDLoc dl(Op);
16435   SDValue R = Op.getOperand(0);
16436   SDValue Amt = Op.getOperand(1);
16437
16438   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16439       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16440       (Subtarget->hasInt256() &&
16441        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16442         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16443        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16444     SDValue BaseShAmt;
16445     EVT EltVT = VT.getVectorElementType();
16446
16447     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16448       // Check if this build_vector node is doing a splat.
16449       // If so, then set BaseShAmt equal to the splat value.
16450       BaseShAmt = BV->getSplatValue();
16451       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16452         BaseShAmt = SDValue();
16453     } else {
16454       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16455         Amt = Amt.getOperand(0);
16456
16457       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16458       if (SVN && SVN->isSplat()) {
16459         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16460         SDValue InVec = Amt.getOperand(0);
16461         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16462           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16463                  "Unexpected shuffle index found!");
16464           BaseShAmt = InVec.getOperand(SplatIdx);
16465         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16466            if (ConstantSDNode *C =
16467                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16468              if (C->getZExtValue() == SplatIdx)
16469                BaseShAmt = InVec.getOperand(1);
16470            }
16471         }
16472
16473         if (!BaseShAmt)
16474           // Avoid introducing an extract element from a shuffle.
16475           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16476                                   DAG.getIntPtrConstant(SplatIdx, dl));
16477       }
16478     }
16479
16480     if (BaseShAmt.getNode()) {
16481       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16482       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16483         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16484       else if (EltVT.bitsLT(MVT::i32))
16485         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16486
16487       switch (Op.getOpcode()) {
16488       default:
16489         llvm_unreachable("Unknown shift opcode!");
16490       case ISD::SHL:
16491         switch (VT.SimpleTy) {
16492         default: return SDValue();
16493         case MVT::v2i64:
16494         case MVT::v4i32:
16495         case MVT::v8i16:
16496         case MVT::v4i64:
16497         case MVT::v8i32:
16498         case MVT::v16i16:
16499         case MVT::v16i32:
16500         case MVT::v8i64:
16501           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16502         }
16503       case ISD::SRA:
16504         switch (VT.SimpleTy) {
16505         default: return SDValue();
16506         case MVT::v4i32:
16507         case MVT::v8i16:
16508         case MVT::v8i32:
16509         case MVT::v16i16:
16510         case MVT::v16i32:
16511         case MVT::v8i64:
16512           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16513         }
16514       case ISD::SRL:
16515         switch (VT.SimpleTy) {
16516         default: return SDValue();
16517         case MVT::v2i64:
16518         case MVT::v4i32:
16519         case MVT::v8i16:
16520         case MVT::v4i64:
16521         case MVT::v8i32:
16522         case MVT::v16i16:
16523         case MVT::v16i32:
16524         case MVT::v8i64:
16525           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16526         }
16527       }
16528     }
16529   }
16530
16531   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16532   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16533       Amt.getOpcode() == ISD::BITCAST &&
16534       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16535     Amt = Amt.getOperand(0);
16536     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16537                      VT.getVectorNumElements();
16538     std::vector<SDValue> Vals(Ratio);
16539     for (unsigned i = 0; i != Ratio; ++i)
16540       Vals[i] = Amt.getOperand(i);
16541     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16542       for (unsigned j = 0; j != Ratio; ++j)
16543         if (Vals[j] != Amt.getOperand(i + j))
16544           return SDValue();
16545     }
16546     switch (Op.getOpcode()) {
16547     default:
16548       llvm_unreachable("Unknown shift opcode!");
16549     case ISD::SHL:
16550       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16551     case ISD::SRL:
16552       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16553     case ISD::SRA:
16554       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16555     }
16556   }
16557
16558   return SDValue();
16559 }
16560
16561 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16562                           SelectionDAG &DAG) {
16563   MVT VT = Op.getSimpleValueType();
16564   SDLoc dl(Op);
16565   SDValue R = Op.getOperand(0);
16566   SDValue Amt = Op.getOperand(1);
16567
16568   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16569   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16570
16571   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16572     return V;
16573
16574   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16575       return V;
16576
16577   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16578     return Op;
16579
16580   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16581   if (Subtarget->hasInt256()) {
16582     if (Op.getOpcode() == ISD::SRL &&
16583         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16584          VT == MVT::v4i64 || VT == MVT::v8i32))
16585       return Op;
16586     if (Op.getOpcode() == ISD::SHL &&
16587         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16588          VT == MVT::v4i64 || VT == MVT::v8i32))
16589       return Op;
16590     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16591       return Op;
16592   }
16593
16594   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16595   // shifts per-lane and then shuffle the partial results back together.
16596   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16597     // Splat the shift amounts so the scalar shifts above will catch it.
16598     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16599     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16600     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16601     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16602     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16603   }
16604
16605   // If possible, lower this packed shift into a vector multiply instead of
16606   // expanding it into a sequence of scalar shifts.
16607   // Do this only if the vector shift count is a constant build_vector.
16608   if (Op.getOpcode() == ISD::SHL &&
16609       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16610        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16611       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16612     SmallVector<SDValue, 8> Elts;
16613     EVT SVT = VT.getScalarType();
16614     unsigned SVTBits = SVT.getSizeInBits();
16615     const APInt &One = APInt(SVTBits, 1);
16616     unsigned NumElems = VT.getVectorNumElements();
16617
16618     for (unsigned i=0; i !=NumElems; ++i) {
16619       SDValue Op = Amt->getOperand(i);
16620       if (Op->getOpcode() == ISD::UNDEF) {
16621         Elts.push_back(Op);
16622         continue;
16623       }
16624
16625       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16626       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16627       uint64_t ShAmt = C.getZExtValue();
16628       if (ShAmt >= SVTBits) {
16629         Elts.push_back(DAG.getUNDEF(SVT));
16630         continue;
16631       }
16632       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16633     }
16634     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16635     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16636   }
16637
16638   // Lower SHL with variable shift amount.
16639   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16640     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16641
16642     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16643                      DAG.getConstant(0x3f800000U, dl, VT));
16644     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16645     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16646     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16647   }
16648
16649   // If possible, lower this shift as a sequence of two shifts by
16650   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16651   // Example:
16652   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16653   //
16654   // Could be rewritten as:
16655   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16656   //
16657   // The advantage is that the two shifts from the example would be
16658   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16659   // the vector shift into four scalar shifts plus four pairs of vector
16660   // insert/extract.
16661   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16662       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16663     unsigned TargetOpcode = X86ISD::MOVSS;
16664     bool CanBeSimplified;
16665     // The splat value for the first packed shift (the 'X' from the example).
16666     SDValue Amt1 = Amt->getOperand(0);
16667     // The splat value for the second packed shift (the 'Y' from the example).
16668     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16669                                         Amt->getOperand(2);
16670
16671     // See if it is possible to replace this node with a sequence of
16672     // two shifts followed by a MOVSS/MOVSD
16673     if (VT == MVT::v4i32) {
16674       // Check if it is legal to use a MOVSS.
16675       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16676                         Amt2 == Amt->getOperand(3);
16677       if (!CanBeSimplified) {
16678         // Otherwise, check if we can still simplify this node using a MOVSD.
16679         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16680                           Amt->getOperand(2) == Amt->getOperand(3);
16681         TargetOpcode = X86ISD::MOVSD;
16682         Amt2 = Amt->getOperand(2);
16683       }
16684     } else {
16685       // Do similar checks for the case where the machine value type
16686       // is MVT::v8i16.
16687       CanBeSimplified = Amt1 == Amt->getOperand(1);
16688       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16689         CanBeSimplified = Amt2 == Amt->getOperand(i);
16690
16691       if (!CanBeSimplified) {
16692         TargetOpcode = X86ISD::MOVSD;
16693         CanBeSimplified = true;
16694         Amt2 = Amt->getOperand(4);
16695         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16696           CanBeSimplified = Amt1 == Amt->getOperand(i);
16697         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16698           CanBeSimplified = Amt2 == Amt->getOperand(j);
16699       }
16700     }
16701
16702     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16703         isa<ConstantSDNode>(Amt2)) {
16704       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16705       EVT CastVT = MVT::v4i32;
16706       SDValue Splat1 =
16707         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16708       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16709       SDValue Splat2 =
16710         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16711       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16712       if (TargetOpcode == X86ISD::MOVSD)
16713         CastVT = MVT::v2i64;
16714       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16715       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16716       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16717                                             BitCast1, DAG);
16718       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16719     }
16720   }
16721
16722   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16723     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16724     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16725
16726     SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16727     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16728     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16729
16730     // r = VSELECT(r, shl(r, 4), a);
16731     SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16732     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16733
16734     // a += a
16735     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16736     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16737     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16738
16739     // r = VSELECT(r, shl(r, 2), a);
16740     M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16741     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16742
16743     // a += a
16744     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16745     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16746     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16747
16748     // return VSELECT(r, r+r, a);
16749     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16750                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16751     return R;
16752   }
16753
16754   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16755   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16756   // solution better.
16757   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16758     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16759     unsigned ExtOpc =
16760         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16761     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16762     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16763     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16764                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16765   }
16766
16767   // Decompose 256-bit shifts into smaller 128-bit shifts.
16768   if (VT.is256BitVector()) {
16769     unsigned NumElems = VT.getVectorNumElements();
16770     MVT EltVT = VT.getVectorElementType();
16771     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16772
16773     // Extract the two vectors
16774     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16775     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16776
16777     // Recreate the shift amount vectors
16778     SDValue Amt1, Amt2;
16779     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16780       // Constant shift amount
16781       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16782       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16783       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16784
16785       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16786       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16787     } else {
16788       // Variable shift amount
16789       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16790       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16791     }
16792
16793     // Issue new vector shifts for the smaller types
16794     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16795     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16796
16797     // Concatenate the result back
16798     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16799   }
16800
16801   return SDValue();
16802 }
16803
16804 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16805   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16806   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16807   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16808   // has only one use.
16809   SDNode *N = Op.getNode();
16810   SDValue LHS = N->getOperand(0);
16811   SDValue RHS = N->getOperand(1);
16812   unsigned BaseOp = 0;
16813   unsigned Cond = 0;
16814   SDLoc DL(Op);
16815   switch (Op.getOpcode()) {
16816   default: llvm_unreachable("Unknown ovf instruction!");
16817   case ISD::SADDO:
16818     // A subtract of one will be selected as a INC. Note that INC doesn't
16819     // set CF, so we can't do this for UADDO.
16820     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16821       if (C->isOne()) {
16822         BaseOp = X86ISD::INC;
16823         Cond = X86::COND_O;
16824         break;
16825       }
16826     BaseOp = X86ISD::ADD;
16827     Cond = X86::COND_O;
16828     break;
16829   case ISD::UADDO:
16830     BaseOp = X86ISD::ADD;
16831     Cond = X86::COND_B;
16832     break;
16833   case ISD::SSUBO:
16834     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16835     // set CF, so we can't do this for USUBO.
16836     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16837       if (C->isOne()) {
16838         BaseOp = X86ISD::DEC;
16839         Cond = X86::COND_O;
16840         break;
16841       }
16842     BaseOp = X86ISD::SUB;
16843     Cond = X86::COND_O;
16844     break;
16845   case ISD::USUBO:
16846     BaseOp = X86ISD::SUB;
16847     Cond = X86::COND_B;
16848     break;
16849   case ISD::SMULO:
16850     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16851     Cond = X86::COND_O;
16852     break;
16853   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16854     if (N->getValueType(0) == MVT::i8) {
16855       BaseOp = X86ISD::UMUL8;
16856       Cond = X86::COND_O;
16857       break;
16858     }
16859     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16860                                  MVT::i32);
16861     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16862
16863     SDValue SetCC =
16864       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16865                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
16866                   SDValue(Sum.getNode(), 2));
16867
16868     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16869   }
16870   }
16871
16872   // Also sets EFLAGS.
16873   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16874   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16875
16876   SDValue SetCC =
16877     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16878                 DAG.getConstant(Cond, DL, MVT::i32),
16879                 SDValue(Sum.getNode(), 1));
16880
16881   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16882 }
16883
16884 /// Returns true if the operand type is exactly twice the native width, and
16885 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16886 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16887 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16888 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16889   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16890
16891   if (OpWidth == 64)
16892     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16893   else if (OpWidth == 128)
16894     return Subtarget->hasCmpxchg16b();
16895   else
16896     return false;
16897 }
16898
16899 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16900   return needsCmpXchgNb(SI->getValueOperand()->getType());
16901 }
16902
16903 // Note: this turns large loads into lock cmpxchg8b/16b.
16904 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16905 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16906   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16907   return needsCmpXchgNb(PTy->getElementType());
16908 }
16909
16910 TargetLoweringBase::AtomicRMWExpansionKind
16911 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16912   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16913   const Type *MemType = AI->getType();
16914
16915   // If the operand is too big, we must see if cmpxchg8/16b is available
16916   // and default to library calls otherwise.
16917   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16918     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16919                                    : AtomicRMWExpansionKind::None;
16920   }
16921
16922   AtomicRMWInst::BinOp Op = AI->getOperation();
16923   switch (Op) {
16924   default:
16925     llvm_unreachable("Unknown atomic operation");
16926   case AtomicRMWInst::Xchg:
16927   case AtomicRMWInst::Add:
16928   case AtomicRMWInst::Sub:
16929     // It's better to use xadd, xsub or xchg for these in all cases.
16930     return AtomicRMWExpansionKind::None;
16931   case AtomicRMWInst::Or:
16932   case AtomicRMWInst::And:
16933   case AtomicRMWInst::Xor:
16934     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16935     // prefix to a normal instruction for these operations.
16936     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16937                             : AtomicRMWExpansionKind::None;
16938   case AtomicRMWInst::Nand:
16939   case AtomicRMWInst::Max:
16940   case AtomicRMWInst::Min:
16941   case AtomicRMWInst::UMax:
16942   case AtomicRMWInst::UMin:
16943     // These always require a non-trivial set of data operations on x86. We must
16944     // use a cmpxchg loop.
16945     return AtomicRMWExpansionKind::CmpXChg;
16946   }
16947 }
16948
16949 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16950   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16951   // no-sse2). There isn't any reason to disable it if the target processor
16952   // supports it.
16953   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16954 }
16955
16956 LoadInst *
16957 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16958   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16959   const Type *MemType = AI->getType();
16960   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16961   // there is no benefit in turning such RMWs into loads, and it is actually
16962   // harmful as it introduces a mfence.
16963   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16964     return nullptr;
16965
16966   auto Builder = IRBuilder<>(AI);
16967   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16968   auto SynchScope = AI->getSynchScope();
16969   // We must restrict the ordering to avoid generating loads with Release or
16970   // ReleaseAcquire orderings.
16971   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16972   auto Ptr = AI->getPointerOperand();
16973
16974   // Before the load we need a fence. Here is an example lifted from
16975   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16976   // is required:
16977   // Thread 0:
16978   //   x.store(1, relaxed);
16979   //   r1 = y.fetch_add(0, release);
16980   // Thread 1:
16981   //   y.fetch_add(42, acquire);
16982   //   r2 = x.load(relaxed);
16983   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16984   // lowered to just a load without a fence. A mfence flushes the store buffer,
16985   // making the optimization clearly correct.
16986   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16987   // otherwise, we might be able to be more agressive on relaxed idempotent
16988   // rmw. In practice, they do not look useful, so we don't try to be
16989   // especially clever.
16990   if (SynchScope == SingleThread) {
16991     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16992     // the IR level, so we must wrap it in an intrinsic.
16993     return nullptr;
16994   } else if (hasMFENCE(*Subtarget)) {
16995     Function *MFence = llvm::Intrinsic::getDeclaration(M,
16996             Intrinsic::x86_sse2_mfence);
16997     Builder.CreateCall(MFence);
16998   } else {
16999     // FIXME: it might make sense to use a locked operation here but on a
17000     // different cache-line to prevent cache-line bouncing. In practice it
17001     // is probably a small win, and x86 processors without mfence are rare
17002     // enough that we do not bother.
17003     return nullptr;
17004   }
17005
17006   // Finally we can emit the atomic load.
17007   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17008           AI->getType()->getPrimitiveSizeInBits());
17009   Loaded->setAtomic(Order, SynchScope);
17010   AI->replaceAllUsesWith(Loaded);
17011   AI->eraseFromParent();
17012   return Loaded;
17013 }
17014
17015 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17016                                  SelectionDAG &DAG) {
17017   SDLoc dl(Op);
17018   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17019     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17020   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17021     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17022
17023   // The only fence that needs an instruction is a sequentially-consistent
17024   // cross-thread fence.
17025   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17026     if (hasMFENCE(*Subtarget))
17027       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17028
17029     SDValue Chain = Op.getOperand(0);
17030     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17031     SDValue Ops[] = {
17032       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17033       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17034       DAG.getRegister(0, MVT::i32),            // Index
17035       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17036       DAG.getRegister(0, MVT::i32),            // Segment.
17037       Zero,
17038       Chain
17039     };
17040     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17041     return SDValue(Res, 0);
17042   }
17043
17044   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17045   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17046 }
17047
17048 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17049                              SelectionDAG &DAG) {
17050   MVT T = Op.getSimpleValueType();
17051   SDLoc DL(Op);
17052   unsigned Reg = 0;
17053   unsigned size = 0;
17054   switch(T.SimpleTy) {
17055   default: llvm_unreachable("Invalid value type!");
17056   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17057   case MVT::i16: Reg = X86::AX;  size = 2; break;
17058   case MVT::i32: Reg = X86::EAX; size = 4; break;
17059   case MVT::i64:
17060     assert(Subtarget->is64Bit() && "Node not type legal!");
17061     Reg = X86::RAX; size = 8;
17062     break;
17063   }
17064   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17065                                   Op.getOperand(2), SDValue());
17066   SDValue Ops[] = { cpIn.getValue(0),
17067                     Op.getOperand(1),
17068                     Op.getOperand(3),
17069                     DAG.getTargetConstant(size, DL, MVT::i8),
17070                     cpIn.getValue(1) };
17071   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17072   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17073   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17074                                            Ops, T, MMO);
17075
17076   SDValue cpOut =
17077     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17078   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17079                                       MVT::i32, cpOut.getValue(2));
17080   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17081                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17082                                 EFLAGS);
17083
17084   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17085   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17086   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17087   return SDValue();
17088 }
17089
17090 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17091                             SelectionDAG &DAG) {
17092   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17093   MVT DstVT = Op.getSimpleValueType();
17094
17095   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17096     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17097     if (DstVT != MVT::f64)
17098       // This conversion needs to be expanded.
17099       return SDValue();
17100
17101     SDValue InVec = Op->getOperand(0);
17102     SDLoc dl(Op);
17103     unsigned NumElts = SrcVT.getVectorNumElements();
17104     EVT SVT = SrcVT.getVectorElementType();
17105
17106     // Widen the vector in input in the case of MVT::v2i32.
17107     // Example: from MVT::v2i32 to MVT::v4i32.
17108     SmallVector<SDValue, 16> Elts;
17109     for (unsigned i = 0, e = NumElts; i != e; ++i)
17110       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17111                                  DAG.getIntPtrConstant(i, dl)));
17112
17113     // Explicitly mark the extra elements as Undef.
17114     Elts.append(NumElts, DAG.getUNDEF(SVT));
17115
17116     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17117     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17118     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17119     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17120                        DAG.getIntPtrConstant(0, dl));
17121   }
17122
17123   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17124          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17125   assert((DstVT == MVT::i64 ||
17126           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17127          "Unexpected custom BITCAST");
17128   // i64 <=> MMX conversions are Legal.
17129   if (SrcVT==MVT::i64 && DstVT.isVector())
17130     return Op;
17131   if (DstVT==MVT::i64 && SrcVT.isVector())
17132     return Op;
17133   // MMX <=> MMX conversions are Legal.
17134   if (SrcVT.isVector() && DstVT.isVector())
17135     return Op;
17136   // All other conversions need to be expanded.
17137   return SDValue();
17138 }
17139
17140 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17141                           SelectionDAG &DAG) {
17142   SDNode *Node = Op.getNode();
17143   SDLoc dl(Node);
17144
17145   Op = Op.getOperand(0);
17146   EVT VT = Op.getValueType();
17147   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17148          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17149
17150   unsigned NumElts = VT.getVectorNumElements();
17151   EVT EltVT = VT.getVectorElementType();
17152   unsigned Len = EltVT.getSizeInBits();
17153
17154   // This is the vectorized version of the "best" algorithm from
17155   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17156   // with a minor tweak to use a series of adds + shifts instead of vector
17157   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17158   //
17159   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17160   //  v8i32 => Always profitable
17161   //
17162   // FIXME: There a couple of possible improvements:
17163   //
17164   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17165   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17166   //
17167   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17168          "CTPOP not implemented for this vector element type.");
17169
17170   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17171   // extra legalization.
17172   bool NeedsBitcast = EltVT == MVT::i32;
17173   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17174
17175   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17176                                   EltVT);
17177   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17178                                   EltVT);
17179   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17180                                   EltVT);
17181
17182   // v = v - ((v >> 1) & 0x55555555...)
17183   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17184   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17185   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17186   if (NeedsBitcast)
17187     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17188
17189   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17190   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17191   if (NeedsBitcast)
17192     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17193
17194   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17195   if (VT != And.getValueType())
17196     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17197   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17198
17199   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17200   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17201   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17202   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17203   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17204
17205   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17206   if (NeedsBitcast) {
17207     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17208     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17209     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17210   }
17211
17212   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17213   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17214   if (VT != AndRHS.getValueType()) {
17215     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17216     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17217   }
17218   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17219
17220   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17221   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17222   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17223   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17224   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17225
17226   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17227   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17228   if (NeedsBitcast) {
17229     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17230     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17231   }
17232   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17233   if (VT != And.getValueType())
17234     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17235
17236   // The algorithm mentioned above uses:
17237   //    v = (v * 0x01010101...) >> (Len - 8)
17238   //
17239   // Change it to use vector adds + vector shifts which yield faster results on
17240   // Haswell than using vector integer multiplication.
17241   //
17242   // For i32 elements:
17243   //    v = v + (v >> 8)
17244   //    v = v + (v >> 16)
17245   //
17246   // For i64 elements:
17247   //    v = v + (v >> 8)
17248   //    v = v + (v >> 16)
17249   //    v = v + (v >> 32)
17250   //
17251   Add = And;
17252   SmallVector<SDValue, 8> Csts;
17253   for (unsigned i = 8; i <= Len/2; i *= 2) {
17254     Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17255     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17256     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17257     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17258     Csts.clear();
17259   }
17260
17261   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17262   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17263                                   EltVT);
17264   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17265   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17266   if (NeedsBitcast) {
17267     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17268     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17269   }
17270   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17271   if (VT != And.getValueType())
17272     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17273
17274   return And;
17275 }
17276
17277 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17278   SDNode *Node = Op.getNode();
17279   SDLoc dl(Node);
17280   EVT T = Node->getValueType(0);
17281   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17282                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17283   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17284                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17285                        Node->getOperand(0),
17286                        Node->getOperand(1), negOp,
17287                        cast<AtomicSDNode>(Node)->getMemOperand(),
17288                        cast<AtomicSDNode>(Node)->getOrdering(),
17289                        cast<AtomicSDNode>(Node)->getSynchScope());
17290 }
17291
17292 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17293   SDNode *Node = Op.getNode();
17294   SDLoc dl(Node);
17295   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17296
17297   // Convert seq_cst store -> xchg
17298   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17299   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17300   //        (The only way to get a 16-byte store is cmpxchg16b)
17301   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17302   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17303       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17304     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17305                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17306                                  Node->getOperand(0),
17307                                  Node->getOperand(1), Node->getOperand(2),
17308                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17309                                  cast<AtomicSDNode>(Node)->getOrdering(),
17310                                  cast<AtomicSDNode>(Node)->getSynchScope());
17311     return Swap.getValue(1);
17312   }
17313   // Other atomic stores have a simple pattern.
17314   return Op;
17315 }
17316
17317 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17318   EVT VT = Op.getNode()->getSimpleValueType(0);
17319
17320   // Let legalize expand this if it isn't a legal type yet.
17321   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17322     return SDValue();
17323
17324   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17325
17326   unsigned Opc;
17327   bool ExtraOp = false;
17328   switch (Op.getOpcode()) {
17329   default: llvm_unreachable("Invalid code");
17330   case ISD::ADDC: Opc = X86ISD::ADD; break;
17331   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17332   case ISD::SUBC: Opc = X86ISD::SUB; break;
17333   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17334   }
17335
17336   if (!ExtraOp)
17337     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17338                        Op.getOperand(1));
17339   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17340                      Op.getOperand(1), Op.getOperand(2));
17341 }
17342
17343 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17344                             SelectionDAG &DAG) {
17345   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17346
17347   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17348   // which returns the values as { float, float } (in XMM0) or
17349   // { double, double } (which is returned in XMM0, XMM1).
17350   SDLoc dl(Op);
17351   SDValue Arg = Op.getOperand(0);
17352   EVT ArgVT = Arg.getValueType();
17353   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17354
17355   TargetLowering::ArgListTy Args;
17356   TargetLowering::ArgListEntry Entry;
17357
17358   Entry.Node = Arg;
17359   Entry.Ty = ArgTy;
17360   Entry.isSExt = false;
17361   Entry.isZExt = false;
17362   Args.push_back(Entry);
17363
17364   bool isF64 = ArgVT == MVT::f64;
17365   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17366   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17367   // the results are returned via SRet in memory.
17368   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17369   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17370   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17371
17372   Type *RetTy = isF64
17373     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17374     : (Type*)VectorType::get(ArgTy, 4);
17375
17376   TargetLowering::CallLoweringInfo CLI(DAG);
17377   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17378     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17379
17380   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17381
17382   if (isF64)
17383     // Returned in xmm0 and xmm1.
17384     return CallResult.first;
17385
17386   // Returned in bits 0:31 and 32:64 xmm0.
17387   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17388                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17389   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17390                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17391   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17392   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17393 }
17394
17395 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17396                              SelectionDAG &DAG) {
17397   assert(Subtarget->hasAVX512() &&
17398          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17399
17400   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17401   EVT VT = N->getValue().getValueType();
17402   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17403   SDLoc dl(Op);
17404
17405   // X86 scatter kills mask register, so its type should be added to
17406   // the list of return values
17407   if (N->getNumValues() == 1) {
17408     SDValue Index = N->getIndex();
17409     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17410         !Index.getValueType().is512BitVector())
17411       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17412
17413     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17414     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17415                       N->getOperand(3), Index };
17416
17417     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17418     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17419     return SDValue(NewScatter.getNode(), 0);
17420   }
17421   return Op;
17422 }
17423
17424 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17425                             SelectionDAG &DAG) {
17426   assert(Subtarget->hasAVX512() &&
17427          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17428
17429   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17430   EVT VT = Op.getValueType();
17431   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17432   SDLoc dl(Op);
17433
17434   SDValue Index = N->getIndex();
17435   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17436       !Index.getValueType().is512BitVector()) {
17437     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17438     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17439                       N->getOperand(3), Index };
17440     DAG.UpdateNodeOperands(N, Ops);
17441   }
17442   return Op;
17443 }
17444
17445 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17446                                                     SelectionDAG &DAG) const {
17447   // TODO: Eventually, the lowering of these nodes should be informed by or
17448   // deferred to the GC strategy for the function in which they appear. For
17449   // now, however, they must be lowered to something. Since they are logically
17450   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17451   // require special handling for these nodes), lower them as literal NOOPs for
17452   // the time being.
17453   SmallVector<SDValue, 2> Ops;
17454
17455   Ops.push_back(Op.getOperand(0));
17456   if (Op->getGluedNode())
17457     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17458
17459   SDLoc OpDL(Op);
17460   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17461   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17462
17463   return NOOP;
17464 }
17465
17466 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17467                                                   SelectionDAG &DAG) const {
17468   // TODO: Eventually, the lowering of these nodes should be informed by or
17469   // deferred to the GC strategy for the function in which they appear. For
17470   // now, however, they must be lowered to something. Since they are logically
17471   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17472   // require special handling for these nodes), lower them as literal NOOPs for
17473   // the time being.
17474   SmallVector<SDValue, 2> Ops;
17475
17476   Ops.push_back(Op.getOperand(0));
17477   if (Op->getGluedNode())
17478     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17479
17480   SDLoc OpDL(Op);
17481   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17482   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17483
17484   return NOOP;
17485 }
17486
17487 /// LowerOperation - Provide custom lowering hooks for some operations.
17488 ///
17489 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17490   switch (Op.getOpcode()) {
17491   default: llvm_unreachable("Should not custom lower this!");
17492   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17493   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17494     return LowerCMP_SWAP(Op, Subtarget, DAG);
17495   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17496   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17497   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17498   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17499   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17500   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17501   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17502   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17503   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17504   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17505   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17506   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17507   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17508   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17509   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17510   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17511   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17512   case ISD::SHL_PARTS:
17513   case ISD::SRA_PARTS:
17514   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17515   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17516   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17517   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17518   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17519   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17520   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17521   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17522   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17523   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17524   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17525   case ISD::FABS:
17526   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17527   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17528   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17529   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17530   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17531   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17532   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17533   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17534   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17535   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17536   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17537   case ISD::INTRINSIC_VOID:
17538   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17539   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17540   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17541   case ISD::FRAME_TO_ARGS_OFFSET:
17542                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17543   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17544   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17545   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17546   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17547   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17548   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17549   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17550   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17551   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17552   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17553   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17554   case ISD::UMUL_LOHI:
17555   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17556   case ISD::SRA:
17557   case ISD::SRL:
17558   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17559   case ISD::SADDO:
17560   case ISD::UADDO:
17561   case ISD::SSUBO:
17562   case ISD::USUBO:
17563   case ISD::SMULO:
17564   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17565   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17566   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17567   case ISD::ADDC:
17568   case ISD::ADDE:
17569   case ISD::SUBC:
17570   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17571   case ISD::ADD:                return LowerADD(Op, DAG);
17572   case ISD::SUB:                return LowerSUB(Op, DAG);
17573   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17574   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
17575   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
17576   case ISD::GC_TRANSITION_START:
17577                                 return LowerGC_TRANSITION_START(Op, DAG);
17578   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
17579   }
17580 }
17581
17582 /// ReplaceNodeResults - Replace a node with an illegal result type
17583 /// with a new node built out of custom code.
17584 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17585                                            SmallVectorImpl<SDValue>&Results,
17586                                            SelectionDAG &DAG) const {
17587   SDLoc dl(N);
17588   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17589   switch (N->getOpcode()) {
17590   default:
17591     llvm_unreachable("Do not know how to custom type legalize this operation!");
17592   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17593   case X86ISD::FMINC:
17594   case X86ISD::FMIN:
17595   case X86ISD::FMAXC:
17596   case X86ISD::FMAX: {
17597     EVT VT = N->getValueType(0);
17598     if (VT != MVT::v2f32)
17599       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17600     SDValue UNDEF = DAG.getUNDEF(VT);
17601     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17602                               N->getOperand(0), UNDEF);
17603     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17604                               N->getOperand(1), UNDEF);
17605     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17606     return;
17607   }
17608   case ISD::SIGN_EXTEND_INREG:
17609   case ISD::ADDC:
17610   case ISD::ADDE:
17611   case ISD::SUBC:
17612   case ISD::SUBE:
17613     // We don't want to expand or promote these.
17614     return;
17615   case ISD::SDIV:
17616   case ISD::UDIV:
17617   case ISD::SREM:
17618   case ISD::UREM:
17619   case ISD::SDIVREM:
17620   case ISD::UDIVREM: {
17621     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17622     Results.push_back(V);
17623     return;
17624   }
17625   case ISD::FP_TO_SINT:
17626   case ISD::FP_TO_UINT: {
17627     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17628
17629     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17630       return;
17631
17632     std::pair<SDValue,SDValue> Vals =
17633         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17634     SDValue FIST = Vals.first, StackSlot = Vals.second;
17635     if (FIST.getNode()) {
17636       EVT VT = N->getValueType(0);
17637       // Return a load from the stack slot.
17638       if (StackSlot.getNode())
17639         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17640                                       MachinePointerInfo(),
17641                                       false, false, false, 0));
17642       else
17643         Results.push_back(FIST);
17644     }
17645     return;
17646   }
17647   case ISD::UINT_TO_FP: {
17648     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17649     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17650         N->getValueType(0) != MVT::v2f32)
17651       return;
17652     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17653                                  N->getOperand(0));
17654     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17655                                      MVT::f64);
17656     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17657     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17658                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17659     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17660     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17661     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17662     return;
17663   }
17664   case ISD::FP_ROUND: {
17665     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17666         return;
17667     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17668     Results.push_back(V);
17669     return;
17670   }
17671   case ISD::INTRINSIC_W_CHAIN: {
17672     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17673     switch (IntNo) {
17674     default : llvm_unreachable("Do not know how to custom type "
17675                                "legalize this intrinsic operation!");
17676     case Intrinsic::x86_rdtsc:
17677       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17678                                      Results);
17679     case Intrinsic::x86_rdtscp:
17680       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17681                                      Results);
17682     case Intrinsic::x86_rdpmc:
17683       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17684     }
17685   }
17686   case ISD::READCYCLECOUNTER: {
17687     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17688                                    Results);
17689   }
17690   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17691     EVT T = N->getValueType(0);
17692     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17693     bool Regs64bit = T == MVT::i128;
17694     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17695     SDValue cpInL, cpInH;
17696     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17697                         DAG.getConstant(0, dl, HalfT));
17698     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17699                         DAG.getConstant(1, dl, HalfT));
17700     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17701                              Regs64bit ? X86::RAX : X86::EAX,
17702                              cpInL, SDValue());
17703     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17704                              Regs64bit ? X86::RDX : X86::EDX,
17705                              cpInH, cpInL.getValue(1));
17706     SDValue swapInL, swapInH;
17707     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17708                           DAG.getConstant(0, dl, HalfT));
17709     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17710                           DAG.getConstant(1, dl, HalfT));
17711     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17712                                Regs64bit ? X86::RBX : X86::EBX,
17713                                swapInL, cpInH.getValue(1));
17714     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17715                                Regs64bit ? X86::RCX : X86::ECX,
17716                                swapInH, swapInL.getValue(1));
17717     SDValue Ops[] = { swapInH.getValue(0),
17718                       N->getOperand(1),
17719                       swapInH.getValue(1) };
17720     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17721     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17722     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17723                                   X86ISD::LCMPXCHG8_DAG;
17724     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17725     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17726                                         Regs64bit ? X86::RAX : X86::EAX,
17727                                         HalfT, Result.getValue(1));
17728     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17729                                         Regs64bit ? X86::RDX : X86::EDX,
17730                                         HalfT, cpOutL.getValue(2));
17731     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17732
17733     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17734                                         MVT::i32, cpOutH.getValue(2));
17735     SDValue Success =
17736         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17737                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17738     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17739
17740     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17741     Results.push_back(Success);
17742     Results.push_back(EFLAGS.getValue(1));
17743     return;
17744   }
17745   case ISD::ATOMIC_SWAP:
17746   case ISD::ATOMIC_LOAD_ADD:
17747   case ISD::ATOMIC_LOAD_SUB:
17748   case ISD::ATOMIC_LOAD_AND:
17749   case ISD::ATOMIC_LOAD_OR:
17750   case ISD::ATOMIC_LOAD_XOR:
17751   case ISD::ATOMIC_LOAD_NAND:
17752   case ISD::ATOMIC_LOAD_MIN:
17753   case ISD::ATOMIC_LOAD_MAX:
17754   case ISD::ATOMIC_LOAD_UMIN:
17755   case ISD::ATOMIC_LOAD_UMAX:
17756   case ISD::ATOMIC_LOAD: {
17757     // Delegate to generic TypeLegalization. Situations we can really handle
17758     // should have already been dealt with by AtomicExpandPass.cpp.
17759     break;
17760   }
17761   case ISD::BITCAST: {
17762     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17763     EVT DstVT = N->getValueType(0);
17764     EVT SrcVT = N->getOperand(0)->getValueType(0);
17765
17766     if (SrcVT != MVT::f64 ||
17767         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17768       return;
17769
17770     unsigned NumElts = DstVT.getVectorNumElements();
17771     EVT SVT = DstVT.getVectorElementType();
17772     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17773     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17774                                    MVT::v2f64, N->getOperand(0));
17775     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17776
17777     if (ExperimentalVectorWideningLegalization) {
17778       // If we are legalizing vectors by widening, we already have the desired
17779       // legal vector type, just return it.
17780       Results.push_back(ToVecInt);
17781       return;
17782     }
17783
17784     SmallVector<SDValue, 8> Elts;
17785     for (unsigned i = 0, e = NumElts; i != e; ++i)
17786       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17787                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
17788
17789     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17790   }
17791   }
17792 }
17793
17794 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17795   switch ((X86ISD::NodeType)Opcode) {
17796   case X86ISD::FIRST_NUMBER:       break;
17797   case X86ISD::BSF:                return "X86ISD::BSF";
17798   case X86ISD::BSR:                return "X86ISD::BSR";
17799   case X86ISD::SHLD:               return "X86ISD::SHLD";
17800   case X86ISD::SHRD:               return "X86ISD::SHRD";
17801   case X86ISD::FAND:               return "X86ISD::FAND";
17802   case X86ISD::FANDN:              return "X86ISD::FANDN";
17803   case X86ISD::FOR:                return "X86ISD::FOR";
17804   case X86ISD::FXOR:               return "X86ISD::FXOR";
17805   case X86ISD::FSRL:               return "X86ISD::FSRL";
17806   case X86ISD::FILD:               return "X86ISD::FILD";
17807   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17808   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17809   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17810   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17811   case X86ISD::FLD:                return "X86ISD::FLD";
17812   case X86ISD::FST:                return "X86ISD::FST";
17813   case X86ISD::CALL:               return "X86ISD::CALL";
17814   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17815   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17816   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17817   case X86ISD::BT:                 return "X86ISD::BT";
17818   case X86ISD::CMP:                return "X86ISD::CMP";
17819   case X86ISD::COMI:               return "X86ISD::COMI";
17820   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17821   case X86ISD::CMPM:               return "X86ISD::CMPM";
17822   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17823   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
17824   case X86ISD::SETCC:              return "X86ISD::SETCC";
17825   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17826   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17827   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
17828   case X86ISD::CMOV:               return "X86ISD::CMOV";
17829   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17830   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17831   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17832   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17833   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17834   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17835   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17836   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
17837   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
17838   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
17839   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17840   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17841   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17842   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17843   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17844   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
17845   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17846   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17847   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17848   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17849   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17850   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
17851   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17852   case X86ISD::HADD:               return "X86ISD::HADD";
17853   case X86ISD::HSUB:               return "X86ISD::HSUB";
17854   case X86ISD::FHADD:              return "X86ISD::FHADD";
17855   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17856   case X86ISD::UMAX:               return "X86ISD::UMAX";
17857   case X86ISD::UMIN:               return "X86ISD::UMIN";
17858   case X86ISD::SMAX:               return "X86ISD::SMAX";
17859   case X86ISD::SMIN:               return "X86ISD::SMIN";
17860   case X86ISD::FMAX:               return "X86ISD::FMAX";
17861   case X86ISD::FMIN:               return "X86ISD::FMIN";
17862   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17863   case X86ISD::FMINC:              return "X86ISD::FMINC";
17864   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17865   case X86ISD::FRCP:               return "X86ISD::FRCP";
17866   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17867   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17868   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17869   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17870   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17871   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17872   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17873   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17874   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17875   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17876   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17877   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17878   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17879   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17880   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17881   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17882   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17883   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17884   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17885   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17886   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17887   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17888   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17889   case X86ISD::VSHL:               return "X86ISD::VSHL";
17890   case X86ISD::VSRL:               return "X86ISD::VSRL";
17891   case X86ISD::VSRA:               return "X86ISD::VSRA";
17892   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17893   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17894   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17895   case X86ISD::CMPP:               return "X86ISD::CMPP";
17896   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17897   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17898   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17899   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17900   case X86ISD::ADD:                return "X86ISD::ADD";
17901   case X86ISD::SUB:                return "X86ISD::SUB";
17902   case X86ISD::ADC:                return "X86ISD::ADC";
17903   case X86ISD::SBB:                return "X86ISD::SBB";
17904   case X86ISD::SMUL:               return "X86ISD::SMUL";
17905   case X86ISD::UMUL:               return "X86ISD::UMUL";
17906   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17907   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17908   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17909   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17910   case X86ISD::INC:                return "X86ISD::INC";
17911   case X86ISD::DEC:                return "X86ISD::DEC";
17912   case X86ISD::OR:                 return "X86ISD::OR";
17913   case X86ISD::XOR:                return "X86ISD::XOR";
17914   case X86ISD::AND:                return "X86ISD::AND";
17915   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17916   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17917   case X86ISD::PTEST:              return "X86ISD::PTEST";
17918   case X86ISD::TESTP:              return "X86ISD::TESTP";
17919   case X86ISD::TESTM:              return "X86ISD::TESTM";
17920   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17921   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17922   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17923   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17924   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17925   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17926   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17927   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17928   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17929   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17930   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17931   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17932   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17933   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17934   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17935   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17936   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17937   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17938   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17939   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17940   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17941   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17942   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17943   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17944   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
17945   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17946   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17947   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17948   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17949   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17950   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17951   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17952   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17953   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17954   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17955   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17956   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17957   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
17958   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
17959   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
17960   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17961   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17962   case X86ISD::SAHF:               return "X86ISD::SAHF";
17963   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17964   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17965   case X86ISD::FMADD:              return "X86ISD::FMADD";
17966   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17967   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17968   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17969   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17970   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17971   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
17972   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
17973   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
17974   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
17975   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
17976   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
17977   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
17978   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17979   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17980   case X86ISD::XTEST:              return "X86ISD::XTEST";
17981   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
17982   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
17983   case X86ISD::SELECT:             return "X86ISD::SELECT";
17984   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
17985   case X86ISD::RCP28:              return "X86ISD::RCP28";
17986   case X86ISD::EXP2:               return "X86ISD::EXP2";
17987   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
17988   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
17989   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
17990   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
17991   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
17992   case X86ISD::ADDS:               return "X86ISD::ADDS";
17993   case X86ISD::SUBS:               return "X86ISD::SUBS";
17994   }
17995   return nullptr;
17996 }
17997
17998 // isLegalAddressingMode - Return true if the addressing mode represented
17999 // by AM is legal for this target, for a load/store of the specified type.
18000 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18001                                               Type *Ty) const {
18002   // X86 supports extremely general addressing modes.
18003   CodeModel::Model M = getTargetMachine().getCodeModel();
18004   Reloc::Model R = getTargetMachine().getRelocationModel();
18005
18006   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18007   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18008     return false;
18009
18010   if (AM.BaseGV) {
18011     unsigned GVFlags =
18012       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18013
18014     // If a reference to this global requires an extra load, we can't fold it.
18015     if (isGlobalStubReference(GVFlags))
18016       return false;
18017
18018     // If BaseGV requires a register for the PIC base, we cannot also have a
18019     // BaseReg specified.
18020     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18021       return false;
18022
18023     // If lower 4G is not available, then we must use rip-relative addressing.
18024     if ((M != CodeModel::Small || R != Reloc::Static) &&
18025         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18026       return false;
18027   }
18028
18029   switch (AM.Scale) {
18030   case 0:
18031   case 1:
18032   case 2:
18033   case 4:
18034   case 8:
18035     // These scales always work.
18036     break;
18037   case 3:
18038   case 5:
18039   case 9:
18040     // These scales are formed with basereg+scalereg.  Only accept if there is
18041     // no basereg yet.
18042     if (AM.HasBaseReg)
18043       return false;
18044     break;
18045   default:  // Other stuff never works.
18046     return false;
18047   }
18048
18049   return true;
18050 }
18051
18052 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18053   unsigned Bits = Ty->getScalarSizeInBits();
18054
18055   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18056   // particularly cheaper than those without.
18057   if (Bits == 8)
18058     return false;
18059
18060   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18061   // variable shifts just as cheap as scalar ones.
18062   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18063     return false;
18064
18065   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18066   // fully general vector.
18067   return true;
18068 }
18069
18070 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18071   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18072     return false;
18073   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18074   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18075   return NumBits1 > NumBits2;
18076 }
18077
18078 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18079   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18080     return false;
18081
18082   if (!isTypeLegal(EVT::getEVT(Ty1)))
18083     return false;
18084
18085   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18086
18087   // Assuming the caller doesn't have a zeroext or signext return parameter,
18088   // truncation all the way down to i1 is valid.
18089   return true;
18090 }
18091
18092 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18093   return isInt<32>(Imm);
18094 }
18095
18096 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18097   // Can also use sub to handle negated immediates.
18098   return isInt<32>(Imm);
18099 }
18100
18101 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18102   if (!VT1.isInteger() || !VT2.isInteger())
18103     return false;
18104   unsigned NumBits1 = VT1.getSizeInBits();
18105   unsigned NumBits2 = VT2.getSizeInBits();
18106   return NumBits1 > NumBits2;
18107 }
18108
18109 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18110   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18111   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18112 }
18113
18114 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18115   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18116   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18117 }
18118
18119 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18120   EVT VT1 = Val.getValueType();
18121   if (isZExtFree(VT1, VT2))
18122     return true;
18123
18124   if (Val.getOpcode() != ISD::LOAD)
18125     return false;
18126
18127   if (!VT1.isSimple() || !VT1.isInteger() ||
18128       !VT2.isSimple() || !VT2.isInteger())
18129     return false;
18130
18131   switch (VT1.getSimpleVT().SimpleTy) {
18132   default: break;
18133   case MVT::i8:
18134   case MVT::i16:
18135   case MVT::i32:
18136     // X86 has 8, 16, and 32-bit zero-extending loads.
18137     return true;
18138   }
18139
18140   return false;
18141 }
18142
18143 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18144
18145 bool
18146 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18147   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18148     return false;
18149
18150   VT = VT.getScalarType();
18151
18152   if (!VT.isSimple())
18153     return false;
18154
18155   switch (VT.getSimpleVT().SimpleTy) {
18156   case MVT::f32:
18157   case MVT::f64:
18158     return true;
18159   default:
18160     break;
18161   }
18162
18163   return false;
18164 }
18165
18166 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18167   // i16 instructions are longer (0x66 prefix) and potentially slower.
18168   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18169 }
18170
18171 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18172 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18173 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18174 /// are assumed to be legal.
18175 bool
18176 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18177                                       EVT VT) const {
18178   if (!VT.isSimple())
18179     return false;
18180
18181   // Not for i1 vectors
18182   if (VT.getScalarType() == MVT::i1)
18183     return false;
18184
18185   // Very little shuffling can be done for 64-bit vectors right now.
18186   if (VT.getSizeInBits() == 64)
18187     return false;
18188
18189   // We only care that the types being shuffled are legal. The lowering can
18190   // handle any possible shuffle mask that results.
18191   return isTypeLegal(VT.getSimpleVT());
18192 }
18193
18194 bool
18195 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18196                                           EVT VT) const {
18197   // Just delegate to the generic legality, clear masks aren't special.
18198   return isShuffleMaskLegal(Mask, VT);
18199 }
18200
18201 //===----------------------------------------------------------------------===//
18202 //                           X86 Scheduler Hooks
18203 //===----------------------------------------------------------------------===//
18204
18205 /// Utility function to emit xbegin specifying the start of an RTM region.
18206 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18207                                      const TargetInstrInfo *TII) {
18208   DebugLoc DL = MI->getDebugLoc();
18209
18210   const BasicBlock *BB = MBB->getBasicBlock();
18211   MachineFunction::iterator I = MBB;
18212   ++I;
18213
18214   // For the v = xbegin(), we generate
18215   //
18216   // thisMBB:
18217   //  xbegin sinkMBB
18218   //
18219   // mainMBB:
18220   //  eax = -1
18221   //
18222   // sinkMBB:
18223   //  v = eax
18224
18225   MachineBasicBlock *thisMBB = MBB;
18226   MachineFunction *MF = MBB->getParent();
18227   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18228   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18229   MF->insert(I, mainMBB);
18230   MF->insert(I, sinkMBB);
18231
18232   // Transfer the remainder of BB and its successor edges to sinkMBB.
18233   sinkMBB->splice(sinkMBB->begin(), MBB,
18234                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18235   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18236
18237   // thisMBB:
18238   //  xbegin sinkMBB
18239   //  # fallthrough to mainMBB
18240   //  # abortion to sinkMBB
18241   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18242   thisMBB->addSuccessor(mainMBB);
18243   thisMBB->addSuccessor(sinkMBB);
18244
18245   // mainMBB:
18246   //  EAX = -1
18247   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18248   mainMBB->addSuccessor(sinkMBB);
18249
18250   // sinkMBB:
18251   // EAX is live into the sinkMBB
18252   sinkMBB->addLiveIn(X86::EAX);
18253   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18254           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18255     .addReg(X86::EAX);
18256
18257   MI->eraseFromParent();
18258   return sinkMBB;
18259 }
18260
18261 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18262 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18263 // in the .td file.
18264 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18265                                        const TargetInstrInfo *TII) {
18266   unsigned Opc;
18267   switch (MI->getOpcode()) {
18268   default: llvm_unreachable("illegal opcode!");
18269   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18270   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18271   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18272   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18273   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18274   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18275   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18276   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18277   }
18278
18279   DebugLoc dl = MI->getDebugLoc();
18280   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18281
18282   unsigned NumArgs = MI->getNumOperands();
18283   for (unsigned i = 1; i < NumArgs; ++i) {
18284     MachineOperand &Op = MI->getOperand(i);
18285     if (!(Op.isReg() && Op.isImplicit()))
18286       MIB.addOperand(Op);
18287   }
18288   if (MI->hasOneMemOperand())
18289     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18290
18291   BuildMI(*BB, MI, dl,
18292     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18293     .addReg(X86::XMM0);
18294
18295   MI->eraseFromParent();
18296   return BB;
18297 }
18298
18299 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18300 // defs in an instruction pattern
18301 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18302                                        const TargetInstrInfo *TII) {
18303   unsigned Opc;
18304   switch (MI->getOpcode()) {
18305   default: llvm_unreachable("illegal opcode!");
18306   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18307   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18308   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18309   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18310   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18311   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18312   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18313   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18314   }
18315
18316   DebugLoc dl = MI->getDebugLoc();
18317   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18318
18319   unsigned NumArgs = MI->getNumOperands(); // remove the results
18320   for (unsigned i = 1; i < NumArgs; ++i) {
18321     MachineOperand &Op = MI->getOperand(i);
18322     if (!(Op.isReg() && Op.isImplicit()))
18323       MIB.addOperand(Op);
18324   }
18325   if (MI->hasOneMemOperand())
18326     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18327
18328   BuildMI(*BB, MI, dl,
18329     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18330     .addReg(X86::ECX);
18331
18332   MI->eraseFromParent();
18333   return BB;
18334 }
18335
18336 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18337                                       const X86Subtarget *Subtarget) {
18338   DebugLoc dl = MI->getDebugLoc();
18339   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18340   // Address into RAX/EAX, other two args into ECX, EDX.
18341   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18342   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18343   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18344   for (int i = 0; i < X86::AddrNumOperands; ++i)
18345     MIB.addOperand(MI->getOperand(i));
18346
18347   unsigned ValOps = X86::AddrNumOperands;
18348   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18349     .addReg(MI->getOperand(ValOps).getReg());
18350   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18351     .addReg(MI->getOperand(ValOps+1).getReg());
18352
18353   // The instruction doesn't actually take any operands though.
18354   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18355
18356   MI->eraseFromParent(); // The pseudo is gone now.
18357   return BB;
18358 }
18359
18360 MachineBasicBlock *
18361 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18362                                                  MachineBasicBlock *MBB) const {
18363   // Emit va_arg instruction on X86-64.
18364
18365   // Operands to this pseudo-instruction:
18366   // 0  ) Output        : destination address (reg)
18367   // 1-5) Input         : va_list address (addr, i64mem)
18368   // 6  ) ArgSize       : Size (in bytes) of vararg type
18369   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18370   // 8  ) Align         : Alignment of type
18371   // 9  ) EFLAGS (implicit-def)
18372
18373   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18374   static_assert(X86::AddrNumOperands == 5,
18375                 "VAARG_64 assumes 5 address operands");
18376
18377   unsigned DestReg = MI->getOperand(0).getReg();
18378   MachineOperand &Base = MI->getOperand(1);
18379   MachineOperand &Scale = MI->getOperand(2);
18380   MachineOperand &Index = MI->getOperand(3);
18381   MachineOperand &Disp = MI->getOperand(4);
18382   MachineOperand &Segment = MI->getOperand(5);
18383   unsigned ArgSize = MI->getOperand(6).getImm();
18384   unsigned ArgMode = MI->getOperand(7).getImm();
18385   unsigned Align = MI->getOperand(8).getImm();
18386
18387   // Memory Reference
18388   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18389   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18390   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18391
18392   // Machine Information
18393   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18394   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18395   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18396   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18397   DebugLoc DL = MI->getDebugLoc();
18398
18399   // struct va_list {
18400   //   i32   gp_offset
18401   //   i32   fp_offset
18402   //   i64   overflow_area (address)
18403   //   i64   reg_save_area (address)
18404   // }
18405   // sizeof(va_list) = 24
18406   // alignment(va_list) = 8
18407
18408   unsigned TotalNumIntRegs = 6;
18409   unsigned TotalNumXMMRegs = 8;
18410   bool UseGPOffset = (ArgMode == 1);
18411   bool UseFPOffset = (ArgMode == 2);
18412   unsigned MaxOffset = TotalNumIntRegs * 8 +
18413                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18414
18415   /* Align ArgSize to a multiple of 8 */
18416   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18417   bool NeedsAlign = (Align > 8);
18418
18419   MachineBasicBlock *thisMBB = MBB;
18420   MachineBasicBlock *overflowMBB;
18421   MachineBasicBlock *offsetMBB;
18422   MachineBasicBlock *endMBB;
18423
18424   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18425   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18426   unsigned OffsetReg = 0;
18427
18428   if (!UseGPOffset && !UseFPOffset) {
18429     // If we only pull from the overflow region, we don't create a branch.
18430     // We don't need to alter control flow.
18431     OffsetDestReg = 0; // unused
18432     OverflowDestReg = DestReg;
18433
18434     offsetMBB = nullptr;
18435     overflowMBB = thisMBB;
18436     endMBB = thisMBB;
18437   } else {
18438     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18439     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18440     // If not, pull from overflow_area. (branch to overflowMBB)
18441     //
18442     //       thisMBB
18443     //         |     .
18444     //         |        .
18445     //     offsetMBB   overflowMBB
18446     //         |        .
18447     //         |     .
18448     //        endMBB
18449
18450     // Registers for the PHI in endMBB
18451     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18452     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18453
18454     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18455     MachineFunction *MF = MBB->getParent();
18456     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18457     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18458     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18459
18460     MachineFunction::iterator MBBIter = MBB;
18461     ++MBBIter;
18462
18463     // Insert the new basic blocks
18464     MF->insert(MBBIter, offsetMBB);
18465     MF->insert(MBBIter, overflowMBB);
18466     MF->insert(MBBIter, endMBB);
18467
18468     // Transfer the remainder of MBB and its successor edges to endMBB.
18469     endMBB->splice(endMBB->begin(), thisMBB,
18470                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18471     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18472
18473     // Make offsetMBB and overflowMBB successors of thisMBB
18474     thisMBB->addSuccessor(offsetMBB);
18475     thisMBB->addSuccessor(overflowMBB);
18476
18477     // endMBB is a successor of both offsetMBB and overflowMBB
18478     offsetMBB->addSuccessor(endMBB);
18479     overflowMBB->addSuccessor(endMBB);
18480
18481     // Load the offset value into a register
18482     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18483     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18484       .addOperand(Base)
18485       .addOperand(Scale)
18486       .addOperand(Index)
18487       .addDisp(Disp, UseFPOffset ? 4 : 0)
18488       .addOperand(Segment)
18489       .setMemRefs(MMOBegin, MMOEnd);
18490
18491     // Check if there is enough room left to pull this argument.
18492     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18493       .addReg(OffsetReg)
18494       .addImm(MaxOffset + 8 - ArgSizeA8);
18495
18496     // Branch to "overflowMBB" if offset >= max
18497     // Fall through to "offsetMBB" otherwise
18498     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18499       .addMBB(overflowMBB);
18500   }
18501
18502   // In offsetMBB, emit code to use the reg_save_area.
18503   if (offsetMBB) {
18504     assert(OffsetReg != 0);
18505
18506     // Read the reg_save_area address.
18507     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18508     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18509       .addOperand(Base)
18510       .addOperand(Scale)
18511       .addOperand(Index)
18512       .addDisp(Disp, 16)
18513       .addOperand(Segment)
18514       .setMemRefs(MMOBegin, MMOEnd);
18515
18516     // Zero-extend the offset
18517     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18518       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18519         .addImm(0)
18520         .addReg(OffsetReg)
18521         .addImm(X86::sub_32bit);
18522
18523     // Add the offset to the reg_save_area to get the final address.
18524     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18525       .addReg(OffsetReg64)
18526       .addReg(RegSaveReg);
18527
18528     // Compute the offset for the next argument
18529     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18530     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18531       .addReg(OffsetReg)
18532       .addImm(UseFPOffset ? 16 : 8);
18533
18534     // Store it back into the va_list.
18535     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18536       .addOperand(Base)
18537       .addOperand(Scale)
18538       .addOperand(Index)
18539       .addDisp(Disp, UseFPOffset ? 4 : 0)
18540       .addOperand(Segment)
18541       .addReg(NextOffsetReg)
18542       .setMemRefs(MMOBegin, MMOEnd);
18543
18544     // Jump to endMBB
18545     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18546       .addMBB(endMBB);
18547   }
18548
18549   //
18550   // Emit code to use overflow area
18551   //
18552
18553   // Load the overflow_area address into a register.
18554   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18555   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18556     .addOperand(Base)
18557     .addOperand(Scale)
18558     .addOperand(Index)
18559     .addDisp(Disp, 8)
18560     .addOperand(Segment)
18561     .setMemRefs(MMOBegin, MMOEnd);
18562
18563   // If we need to align it, do so. Otherwise, just copy the address
18564   // to OverflowDestReg.
18565   if (NeedsAlign) {
18566     // Align the overflow address
18567     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18568     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18569
18570     // aligned_addr = (addr + (align-1)) & ~(align-1)
18571     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18572       .addReg(OverflowAddrReg)
18573       .addImm(Align-1);
18574
18575     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18576       .addReg(TmpReg)
18577       .addImm(~(uint64_t)(Align-1));
18578   } else {
18579     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18580       .addReg(OverflowAddrReg);
18581   }
18582
18583   // Compute the next overflow address after this argument.
18584   // (the overflow address should be kept 8-byte aligned)
18585   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18586   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18587     .addReg(OverflowDestReg)
18588     .addImm(ArgSizeA8);
18589
18590   // Store the new overflow address.
18591   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18592     .addOperand(Base)
18593     .addOperand(Scale)
18594     .addOperand(Index)
18595     .addDisp(Disp, 8)
18596     .addOperand(Segment)
18597     .addReg(NextAddrReg)
18598     .setMemRefs(MMOBegin, MMOEnd);
18599
18600   // If we branched, emit the PHI to the front of endMBB.
18601   if (offsetMBB) {
18602     BuildMI(*endMBB, endMBB->begin(), DL,
18603             TII->get(X86::PHI), DestReg)
18604       .addReg(OffsetDestReg).addMBB(offsetMBB)
18605       .addReg(OverflowDestReg).addMBB(overflowMBB);
18606   }
18607
18608   // Erase the pseudo instruction
18609   MI->eraseFromParent();
18610
18611   return endMBB;
18612 }
18613
18614 MachineBasicBlock *
18615 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18616                                                  MachineInstr *MI,
18617                                                  MachineBasicBlock *MBB) const {
18618   // Emit code to save XMM registers to the stack. The ABI says that the
18619   // number of registers to save is given in %al, so it's theoretically
18620   // possible to do an indirect jump trick to avoid saving all of them,
18621   // however this code takes a simpler approach and just executes all
18622   // of the stores if %al is non-zero. It's less code, and it's probably
18623   // easier on the hardware branch predictor, and stores aren't all that
18624   // expensive anyway.
18625
18626   // Create the new basic blocks. One block contains all the XMM stores,
18627   // and one block is the final destination regardless of whether any
18628   // stores were performed.
18629   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18630   MachineFunction *F = MBB->getParent();
18631   MachineFunction::iterator MBBIter = MBB;
18632   ++MBBIter;
18633   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18634   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18635   F->insert(MBBIter, XMMSaveMBB);
18636   F->insert(MBBIter, EndMBB);
18637
18638   // Transfer the remainder of MBB and its successor edges to EndMBB.
18639   EndMBB->splice(EndMBB->begin(), MBB,
18640                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18641   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18642
18643   // The original block will now fall through to the XMM save block.
18644   MBB->addSuccessor(XMMSaveMBB);
18645   // The XMMSaveMBB will fall through to the end block.
18646   XMMSaveMBB->addSuccessor(EndMBB);
18647
18648   // Now add the instructions.
18649   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18650   DebugLoc DL = MI->getDebugLoc();
18651
18652   unsigned CountReg = MI->getOperand(0).getReg();
18653   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18654   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18655
18656   if (!Subtarget->isTargetWin64()) {
18657     // If %al is 0, branch around the XMM save block.
18658     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18659     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18660     MBB->addSuccessor(EndMBB);
18661   }
18662
18663   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18664   // that was just emitted, but clearly shouldn't be "saved".
18665   assert((MI->getNumOperands() <= 3 ||
18666           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18667           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18668          && "Expected last argument to be EFLAGS");
18669   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18670   // In the XMM save block, save all the XMM argument registers.
18671   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18672     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18673     MachineMemOperand *MMO =
18674       F->getMachineMemOperand(
18675           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18676         MachineMemOperand::MOStore,
18677         /*Size=*/16, /*Align=*/16);
18678     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18679       .addFrameIndex(RegSaveFrameIndex)
18680       .addImm(/*Scale=*/1)
18681       .addReg(/*IndexReg=*/0)
18682       .addImm(/*Disp=*/Offset)
18683       .addReg(/*Segment=*/0)
18684       .addReg(MI->getOperand(i).getReg())
18685       .addMemOperand(MMO);
18686   }
18687
18688   MI->eraseFromParent();   // The pseudo instruction is gone now.
18689
18690   return EndMBB;
18691 }
18692
18693 // The EFLAGS operand of SelectItr might be missing a kill marker
18694 // because there were multiple uses of EFLAGS, and ISel didn't know
18695 // which to mark. Figure out whether SelectItr should have had a
18696 // kill marker, and set it if it should. Returns the correct kill
18697 // marker value.
18698 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18699                                      MachineBasicBlock* BB,
18700                                      const TargetRegisterInfo* TRI) {
18701   // Scan forward through BB for a use/def of EFLAGS.
18702   MachineBasicBlock::iterator miI(std::next(SelectItr));
18703   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18704     const MachineInstr& mi = *miI;
18705     if (mi.readsRegister(X86::EFLAGS))
18706       return false;
18707     if (mi.definesRegister(X86::EFLAGS))
18708       break; // Should have kill-flag - update below.
18709   }
18710
18711   // If we hit the end of the block, check whether EFLAGS is live into a
18712   // successor.
18713   if (miI == BB->end()) {
18714     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18715                                           sEnd = BB->succ_end();
18716          sItr != sEnd; ++sItr) {
18717       MachineBasicBlock* succ = *sItr;
18718       if (succ->isLiveIn(X86::EFLAGS))
18719         return false;
18720     }
18721   }
18722
18723   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18724   // out. SelectMI should have a kill flag on EFLAGS.
18725   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18726   return true;
18727 }
18728
18729 MachineBasicBlock *
18730 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18731                                      MachineBasicBlock *BB) const {
18732   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18733   DebugLoc DL = MI->getDebugLoc();
18734
18735   // To "insert" a SELECT_CC instruction, we actually have to insert the
18736   // diamond control-flow pattern.  The incoming instruction knows the
18737   // destination vreg to set, the condition code register to branch on, the
18738   // true/false values to select between, and a branch opcode to use.
18739   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18740   MachineFunction::iterator It = BB;
18741   ++It;
18742
18743   //  thisMBB:
18744   //  ...
18745   //   TrueVal = ...
18746   //   cmpTY ccX, r1, r2
18747   //   bCC copy1MBB
18748   //   fallthrough --> copy0MBB
18749   MachineBasicBlock *thisMBB = BB;
18750   MachineFunction *F = BB->getParent();
18751
18752   // We also lower double CMOVs:
18753   //   (CMOV (CMOV F, T, cc1), T, cc2)
18754   // to two successives branches.  For that, we look for another CMOV as the
18755   // following instruction.
18756   //
18757   // Without this, we would add a PHI between the two jumps, which ends up
18758   // creating a few copies all around. For instance, for
18759   //
18760   //    (sitofp (zext (fcmp une)))
18761   //
18762   // we would generate:
18763   //
18764   //         ucomiss %xmm1, %xmm0
18765   //         movss  <1.0f>, %xmm0
18766   //         movaps  %xmm0, %xmm1
18767   //         jne     .LBB5_2
18768   //         xorps   %xmm1, %xmm1
18769   // .LBB5_2:
18770   //         jp      .LBB5_4
18771   //         movaps  %xmm1, %xmm0
18772   // .LBB5_4:
18773   //         retq
18774   //
18775   // because this custom-inserter would have generated:
18776   //
18777   //   A
18778   //   | \
18779   //   |  B
18780   //   | /
18781   //   C
18782   //   | \
18783   //   |  D
18784   //   | /
18785   //   E
18786   //
18787   // A: X = ...; Y = ...
18788   // B: empty
18789   // C: Z = PHI [X, A], [Y, B]
18790   // D: empty
18791   // E: PHI [X, C], [Z, D]
18792   //
18793   // If we lower both CMOVs in a single step, we can instead generate:
18794   //
18795   //   A
18796   //   | \
18797   //   |  C
18798   //   | /|
18799   //   |/ |
18800   //   |  |
18801   //   |  D
18802   //   | /
18803   //   E
18804   //
18805   // A: X = ...; Y = ...
18806   // D: empty
18807   // E: PHI [X, A], [X, C], [Y, D]
18808   //
18809   // Which, in our sitofp/fcmp example, gives us something like:
18810   //
18811   //         ucomiss %xmm1, %xmm0
18812   //         movss  <1.0f>, %xmm0
18813   //         jne     .LBB5_4
18814   //         jp      .LBB5_4
18815   //         xorps   %xmm0, %xmm0
18816   // .LBB5_4:
18817   //         retq
18818   //
18819   MachineInstr *NextCMOV = nullptr;
18820   MachineBasicBlock::iterator NextMIIt =
18821       std::next(MachineBasicBlock::iterator(MI));
18822   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18823       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18824       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18825     NextCMOV = &*NextMIIt;
18826
18827   MachineBasicBlock *jcc1MBB = nullptr;
18828
18829   // If we have a double CMOV, we lower it to two successive branches to
18830   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18831   if (NextCMOV) {
18832     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18833     F->insert(It, jcc1MBB);
18834     jcc1MBB->addLiveIn(X86::EFLAGS);
18835   }
18836
18837   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18838   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18839   F->insert(It, copy0MBB);
18840   F->insert(It, sinkMBB);
18841
18842   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18843   // live into the sink and copy blocks.
18844   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18845
18846   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18847   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18848       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18849     copy0MBB->addLiveIn(X86::EFLAGS);
18850     sinkMBB->addLiveIn(X86::EFLAGS);
18851   }
18852
18853   // Transfer the remainder of BB and its successor edges to sinkMBB.
18854   sinkMBB->splice(sinkMBB->begin(), BB,
18855                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18856   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18857
18858   // Add the true and fallthrough blocks as its successors.
18859   if (NextCMOV) {
18860     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18861     BB->addSuccessor(jcc1MBB);
18862
18863     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18864     // jump to the sinkMBB.
18865     jcc1MBB->addSuccessor(copy0MBB);
18866     jcc1MBB->addSuccessor(sinkMBB);
18867   } else {
18868     BB->addSuccessor(copy0MBB);
18869   }
18870
18871   // The true block target of the first (or only) branch is always sinkMBB.
18872   BB->addSuccessor(sinkMBB);
18873
18874   // Create the conditional branch instruction.
18875   unsigned Opc =
18876     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18877   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18878
18879   if (NextCMOV) {
18880     unsigned Opc2 = X86::GetCondBranchFromCond(
18881         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18882     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18883   }
18884
18885   //  copy0MBB:
18886   //   %FalseValue = ...
18887   //   # fallthrough to sinkMBB
18888   copy0MBB->addSuccessor(sinkMBB);
18889
18890   //  sinkMBB:
18891   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18892   //  ...
18893   MachineInstrBuilder MIB =
18894       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18895               MI->getOperand(0).getReg())
18896           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18897           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18898
18899   // If we have a double CMOV, the second Jcc provides the same incoming
18900   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18901   if (NextCMOV) {
18902     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18903     // Copy the PHI result to the register defined by the second CMOV.
18904     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18905             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18906         .addReg(MI->getOperand(0).getReg());
18907     NextCMOV->eraseFromParent();
18908   }
18909
18910   MI->eraseFromParent();   // The pseudo instruction is gone now.
18911   return sinkMBB;
18912 }
18913
18914 MachineBasicBlock *
18915 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18916                                         MachineBasicBlock *BB) const {
18917   MachineFunction *MF = BB->getParent();
18918   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18919   DebugLoc DL = MI->getDebugLoc();
18920   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18921
18922   assert(MF->shouldSplitStack());
18923
18924   const bool Is64Bit = Subtarget->is64Bit();
18925   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18926
18927   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18928   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18929
18930   // BB:
18931   //  ... [Till the alloca]
18932   // If stacklet is not large enough, jump to mallocMBB
18933   //
18934   // bumpMBB:
18935   //  Allocate by subtracting from RSP
18936   //  Jump to continueMBB
18937   //
18938   // mallocMBB:
18939   //  Allocate by call to runtime
18940   //
18941   // continueMBB:
18942   //  ...
18943   //  [rest of original BB]
18944   //
18945
18946   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18947   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18948   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18949
18950   MachineRegisterInfo &MRI = MF->getRegInfo();
18951   const TargetRegisterClass *AddrRegClass =
18952     getRegClassFor(getPointerTy());
18953
18954   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18955     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18956     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18957     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18958     sizeVReg = MI->getOperand(1).getReg(),
18959     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18960
18961   MachineFunction::iterator MBBIter = BB;
18962   ++MBBIter;
18963
18964   MF->insert(MBBIter, bumpMBB);
18965   MF->insert(MBBIter, mallocMBB);
18966   MF->insert(MBBIter, continueMBB);
18967
18968   continueMBB->splice(continueMBB->begin(), BB,
18969                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18970   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18971
18972   // Add code to the main basic block to check if the stack limit has been hit,
18973   // and if so, jump to mallocMBB otherwise to bumpMBB.
18974   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18975   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18976     .addReg(tmpSPVReg).addReg(sizeVReg);
18977   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18978     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18979     .addReg(SPLimitVReg);
18980   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18981
18982   // bumpMBB simply decreases the stack pointer, since we know the current
18983   // stacklet has enough space.
18984   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18985     .addReg(SPLimitVReg);
18986   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18987     .addReg(SPLimitVReg);
18988   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18989
18990   // Calls into a routine in libgcc to allocate more space from the heap.
18991   const uint32_t *RegMask =
18992       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
18993   if (IsLP64) {
18994     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18995       .addReg(sizeVReg);
18996     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18997       .addExternalSymbol("__morestack_allocate_stack_space")
18998       .addRegMask(RegMask)
18999       .addReg(X86::RDI, RegState::Implicit)
19000       .addReg(X86::RAX, RegState::ImplicitDefine);
19001   } else if (Is64Bit) {
19002     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19003       .addReg(sizeVReg);
19004     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19005       .addExternalSymbol("__morestack_allocate_stack_space")
19006       .addRegMask(RegMask)
19007       .addReg(X86::EDI, RegState::Implicit)
19008       .addReg(X86::EAX, RegState::ImplicitDefine);
19009   } else {
19010     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19011       .addImm(12);
19012     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19013     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19014       .addExternalSymbol("__morestack_allocate_stack_space")
19015       .addRegMask(RegMask)
19016       .addReg(X86::EAX, RegState::ImplicitDefine);
19017   }
19018
19019   if (!Is64Bit)
19020     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19021       .addImm(16);
19022
19023   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19024     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19025   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19026
19027   // Set up the CFG correctly.
19028   BB->addSuccessor(bumpMBB);
19029   BB->addSuccessor(mallocMBB);
19030   mallocMBB->addSuccessor(continueMBB);
19031   bumpMBB->addSuccessor(continueMBB);
19032
19033   // Take care of the PHI nodes.
19034   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19035           MI->getOperand(0).getReg())
19036     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19037     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19038
19039   // Delete the original pseudo instruction.
19040   MI->eraseFromParent();
19041
19042   // And we're done.
19043   return continueMBB;
19044 }
19045
19046 MachineBasicBlock *
19047 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19048                                         MachineBasicBlock *BB) const {
19049   DebugLoc DL = MI->getDebugLoc();
19050
19051   assert(!Subtarget->isTargetMachO());
19052
19053   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19054
19055   MI->eraseFromParent();   // The pseudo instruction is gone now.
19056   return BB;
19057 }
19058
19059 MachineBasicBlock *
19060 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19061                                       MachineBasicBlock *BB) const {
19062   // This is pretty easy.  We're taking the value that we received from
19063   // our load from the relocation, sticking it in either RDI (x86-64)
19064   // or EAX and doing an indirect call.  The return value will then
19065   // be in the normal return register.
19066   MachineFunction *F = BB->getParent();
19067   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19068   DebugLoc DL = MI->getDebugLoc();
19069
19070   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19071   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19072
19073   // Get a register mask for the lowered call.
19074   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19075   // proper register mask.
19076   const uint32_t *RegMask =
19077       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19078   if (Subtarget->is64Bit()) {
19079     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19080                                       TII->get(X86::MOV64rm), X86::RDI)
19081     .addReg(X86::RIP)
19082     .addImm(0).addReg(0)
19083     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19084                       MI->getOperand(3).getTargetFlags())
19085     .addReg(0);
19086     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19087     addDirectMem(MIB, X86::RDI);
19088     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19089   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19090     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19091                                       TII->get(X86::MOV32rm), X86::EAX)
19092     .addReg(0)
19093     .addImm(0).addReg(0)
19094     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19095                       MI->getOperand(3).getTargetFlags())
19096     .addReg(0);
19097     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19098     addDirectMem(MIB, X86::EAX);
19099     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19100   } else {
19101     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19102                                       TII->get(X86::MOV32rm), X86::EAX)
19103     .addReg(TII->getGlobalBaseReg(F))
19104     .addImm(0).addReg(0)
19105     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19106                       MI->getOperand(3).getTargetFlags())
19107     .addReg(0);
19108     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19109     addDirectMem(MIB, X86::EAX);
19110     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19111   }
19112
19113   MI->eraseFromParent(); // The pseudo instruction is gone now.
19114   return BB;
19115 }
19116
19117 MachineBasicBlock *
19118 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19119                                     MachineBasicBlock *MBB) const {
19120   DebugLoc DL = MI->getDebugLoc();
19121   MachineFunction *MF = MBB->getParent();
19122   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19123   MachineRegisterInfo &MRI = MF->getRegInfo();
19124
19125   const BasicBlock *BB = MBB->getBasicBlock();
19126   MachineFunction::iterator I = MBB;
19127   ++I;
19128
19129   // Memory Reference
19130   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19131   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19132
19133   unsigned DstReg;
19134   unsigned MemOpndSlot = 0;
19135
19136   unsigned CurOp = 0;
19137
19138   DstReg = MI->getOperand(CurOp++).getReg();
19139   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19140   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19141   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19142   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19143
19144   MemOpndSlot = CurOp;
19145
19146   MVT PVT = getPointerTy();
19147   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19148          "Invalid Pointer Size!");
19149
19150   // For v = setjmp(buf), we generate
19151   //
19152   // thisMBB:
19153   //  buf[LabelOffset] = restoreMBB
19154   //  SjLjSetup restoreMBB
19155   //
19156   // mainMBB:
19157   //  v_main = 0
19158   //
19159   // sinkMBB:
19160   //  v = phi(main, restore)
19161   //
19162   // restoreMBB:
19163   //  if base pointer being used, load it from frame
19164   //  v_restore = 1
19165
19166   MachineBasicBlock *thisMBB = MBB;
19167   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19168   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19169   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19170   MF->insert(I, mainMBB);
19171   MF->insert(I, sinkMBB);
19172   MF->push_back(restoreMBB);
19173
19174   MachineInstrBuilder MIB;
19175
19176   // Transfer the remainder of BB and its successor edges to sinkMBB.
19177   sinkMBB->splice(sinkMBB->begin(), MBB,
19178                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19179   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19180
19181   // thisMBB:
19182   unsigned PtrStoreOpc = 0;
19183   unsigned LabelReg = 0;
19184   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19185   Reloc::Model RM = MF->getTarget().getRelocationModel();
19186   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19187                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19188
19189   // Prepare IP either in reg or imm.
19190   if (!UseImmLabel) {
19191     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19192     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19193     LabelReg = MRI.createVirtualRegister(PtrRC);
19194     if (Subtarget->is64Bit()) {
19195       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19196               .addReg(X86::RIP)
19197               .addImm(0)
19198               .addReg(0)
19199               .addMBB(restoreMBB)
19200               .addReg(0);
19201     } else {
19202       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19203       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19204               .addReg(XII->getGlobalBaseReg(MF))
19205               .addImm(0)
19206               .addReg(0)
19207               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19208               .addReg(0);
19209     }
19210   } else
19211     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19212   // Store IP
19213   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19214   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19215     if (i == X86::AddrDisp)
19216       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19217     else
19218       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19219   }
19220   if (!UseImmLabel)
19221     MIB.addReg(LabelReg);
19222   else
19223     MIB.addMBB(restoreMBB);
19224   MIB.setMemRefs(MMOBegin, MMOEnd);
19225   // Setup
19226   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19227           .addMBB(restoreMBB);
19228
19229   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19230   MIB.addRegMask(RegInfo->getNoPreservedMask());
19231   thisMBB->addSuccessor(mainMBB);
19232   thisMBB->addSuccessor(restoreMBB);
19233
19234   // mainMBB:
19235   //  EAX = 0
19236   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19237   mainMBB->addSuccessor(sinkMBB);
19238
19239   // sinkMBB:
19240   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19241           TII->get(X86::PHI), DstReg)
19242     .addReg(mainDstReg).addMBB(mainMBB)
19243     .addReg(restoreDstReg).addMBB(restoreMBB);
19244
19245   // restoreMBB:
19246   if (RegInfo->hasBasePointer(*MF)) {
19247     const bool Uses64BitFramePtr =
19248         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19249     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19250     X86FI->setRestoreBasePointer(MF);
19251     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19252     unsigned BasePtr = RegInfo->getBaseRegister();
19253     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19254     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19255                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19256       .setMIFlag(MachineInstr::FrameSetup);
19257   }
19258   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19259   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19260   restoreMBB->addSuccessor(sinkMBB);
19261
19262   MI->eraseFromParent();
19263   return sinkMBB;
19264 }
19265
19266 MachineBasicBlock *
19267 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19268                                      MachineBasicBlock *MBB) const {
19269   DebugLoc DL = MI->getDebugLoc();
19270   MachineFunction *MF = MBB->getParent();
19271   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19272   MachineRegisterInfo &MRI = MF->getRegInfo();
19273
19274   // Memory Reference
19275   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19276   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19277
19278   MVT PVT = getPointerTy();
19279   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19280          "Invalid Pointer Size!");
19281
19282   const TargetRegisterClass *RC =
19283     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19284   unsigned Tmp = MRI.createVirtualRegister(RC);
19285   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19286   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19287   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19288   unsigned SP = RegInfo->getStackRegister();
19289
19290   MachineInstrBuilder MIB;
19291
19292   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19293   const int64_t SPOffset = 2 * PVT.getStoreSize();
19294
19295   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19296   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19297
19298   // Reload FP
19299   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19300   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19301     MIB.addOperand(MI->getOperand(i));
19302   MIB.setMemRefs(MMOBegin, MMOEnd);
19303   // Reload IP
19304   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19305   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19306     if (i == X86::AddrDisp)
19307       MIB.addDisp(MI->getOperand(i), LabelOffset);
19308     else
19309       MIB.addOperand(MI->getOperand(i));
19310   }
19311   MIB.setMemRefs(MMOBegin, MMOEnd);
19312   // Reload SP
19313   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19314   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19315     if (i == X86::AddrDisp)
19316       MIB.addDisp(MI->getOperand(i), SPOffset);
19317     else
19318       MIB.addOperand(MI->getOperand(i));
19319   }
19320   MIB.setMemRefs(MMOBegin, MMOEnd);
19321   // Jump
19322   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19323
19324   MI->eraseFromParent();
19325   return MBB;
19326 }
19327
19328 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19329 // accumulator loops. Writing back to the accumulator allows the coalescer
19330 // to remove extra copies in the loop.
19331 MachineBasicBlock *
19332 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19333                                  MachineBasicBlock *MBB) const {
19334   MachineOperand &AddendOp = MI->getOperand(3);
19335
19336   // Bail out early if the addend isn't a register - we can't switch these.
19337   if (!AddendOp.isReg())
19338     return MBB;
19339
19340   MachineFunction &MF = *MBB->getParent();
19341   MachineRegisterInfo &MRI = MF.getRegInfo();
19342
19343   // Check whether the addend is defined by a PHI:
19344   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19345   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19346   if (!AddendDef.isPHI())
19347     return MBB;
19348
19349   // Look for the following pattern:
19350   // loop:
19351   //   %addend = phi [%entry, 0], [%loop, %result]
19352   //   ...
19353   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19354
19355   // Replace with:
19356   //   loop:
19357   //   %addend = phi [%entry, 0], [%loop, %result]
19358   //   ...
19359   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19360
19361   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19362     assert(AddendDef.getOperand(i).isReg());
19363     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19364     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19365     if (&PHISrcInst == MI) {
19366       // Found a matching instruction.
19367       unsigned NewFMAOpc = 0;
19368       switch (MI->getOpcode()) {
19369         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19370         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19371         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19372         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19373         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19374         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19375         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19376         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19377         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19378         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19379         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19380         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19381         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19382         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19383         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19384         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19385         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19386         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19387         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19388         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19389
19390         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19391         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19392         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19393         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19394         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19395         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19396         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19397         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19398         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19399         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19400         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19401         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19402         default: llvm_unreachable("Unrecognized FMA variant.");
19403       }
19404
19405       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19406       MachineInstrBuilder MIB =
19407         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19408         .addOperand(MI->getOperand(0))
19409         .addOperand(MI->getOperand(3))
19410         .addOperand(MI->getOperand(2))
19411         .addOperand(MI->getOperand(1));
19412       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19413       MI->eraseFromParent();
19414     }
19415   }
19416
19417   return MBB;
19418 }
19419
19420 MachineBasicBlock *
19421 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19422                                                MachineBasicBlock *BB) const {
19423   switch (MI->getOpcode()) {
19424   default: llvm_unreachable("Unexpected instr type to insert");
19425   case X86::TAILJMPd64:
19426   case X86::TAILJMPr64:
19427   case X86::TAILJMPm64:
19428   case X86::TAILJMPd64_REX:
19429   case X86::TAILJMPr64_REX:
19430   case X86::TAILJMPm64_REX:
19431     llvm_unreachable("TAILJMP64 would not be touched here.");
19432   case X86::TCRETURNdi64:
19433   case X86::TCRETURNri64:
19434   case X86::TCRETURNmi64:
19435     return BB;
19436   case X86::WIN_ALLOCA:
19437     return EmitLoweredWinAlloca(MI, BB);
19438   case X86::SEG_ALLOCA_32:
19439   case X86::SEG_ALLOCA_64:
19440     return EmitLoweredSegAlloca(MI, BB);
19441   case X86::TLSCall_32:
19442   case X86::TLSCall_64:
19443     return EmitLoweredTLSCall(MI, BB);
19444   case X86::CMOV_GR8:
19445   case X86::CMOV_FR32:
19446   case X86::CMOV_FR64:
19447   case X86::CMOV_V4F32:
19448   case X86::CMOV_V2F64:
19449   case X86::CMOV_V2I64:
19450   case X86::CMOV_V8F32:
19451   case X86::CMOV_V4F64:
19452   case X86::CMOV_V4I64:
19453   case X86::CMOV_V16F32:
19454   case X86::CMOV_V8F64:
19455   case X86::CMOV_V8I64:
19456   case X86::CMOV_GR16:
19457   case X86::CMOV_GR32:
19458   case X86::CMOV_RFP32:
19459   case X86::CMOV_RFP64:
19460   case X86::CMOV_RFP80:
19461     return EmitLoweredSelect(MI, BB);
19462
19463   case X86::FP32_TO_INT16_IN_MEM:
19464   case X86::FP32_TO_INT32_IN_MEM:
19465   case X86::FP32_TO_INT64_IN_MEM:
19466   case X86::FP64_TO_INT16_IN_MEM:
19467   case X86::FP64_TO_INT32_IN_MEM:
19468   case X86::FP64_TO_INT64_IN_MEM:
19469   case X86::FP80_TO_INT16_IN_MEM:
19470   case X86::FP80_TO_INT32_IN_MEM:
19471   case X86::FP80_TO_INT64_IN_MEM: {
19472     MachineFunction *F = BB->getParent();
19473     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19474     DebugLoc DL = MI->getDebugLoc();
19475
19476     // Change the floating point control register to use "round towards zero"
19477     // mode when truncating to an integer value.
19478     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19479     addFrameReference(BuildMI(*BB, MI, DL,
19480                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19481
19482     // Load the old value of the high byte of the control word...
19483     unsigned OldCW =
19484       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19485     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19486                       CWFrameIdx);
19487
19488     // Set the high part to be round to zero...
19489     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19490       .addImm(0xC7F);
19491
19492     // Reload the modified control word now...
19493     addFrameReference(BuildMI(*BB, MI, DL,
19494                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19495
19496     // Restore the memory image of control word to original value
19497     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19498       .addReg(OldCW);
19499
19500     // Get the X86 opcode to use.
19501     unsigned Opc;
19502     switch (MI->getOpcode()) {
19503     default: llvm_unreachable("illegal opcode!");
19504     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19505     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19506     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19507     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19508     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19509     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19510     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19511     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19512     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19513     }
19514
19515     X86AddressMode AM;
19516     MachineOperand &Op = MI->getOperand(0);
19517     if (Op.isReg()) {
19518       AM.BaseType = X86AddressMode::RegBase;
19519       AM.Base.Reg = Op.getReg();
19520     } else {
19521       AM.BaseType = X86AddressMode::FrameIndexBase;
19522       AM.Base.FrameIndex = Op.getIndex();
19523     }
19524     Op = MI->getOperand(1);
19525     if (Op.isImm())
19526       AM.Scale = Op.getImm();
19527     Op = MI->getOperand(2);
19528     if (Op.isImm())
19529       AM.IndexReg = Op.getImm();
19530     Op = MI->getOperand(3);
19531     if (Op.isGlobal()) {
19532       AM.GV = Op.getGlobal();
19533     } else {
19534       AM.Disp = Op.getImm();
19535     }
19536     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19537                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19538
19539     // Reload the original control word now.
19540     addFrameReference(BuildMI(*BB, MI, DL,
19541                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19542
19543     MI->eraseFromParent();   // The pseudo instruction is gone now.
19544     return BB;
19545   }
19546     // String/text processing lowering.
19547   case X86::PCMPISTRM128REG:
19548   case X86::VPCMPISTRM128REG:
19549   case X86::PCMPISTRM128MEM:
19550   case X86::VPCMPISTRM128MEM:
19551   case X86::PCMPESTRM128REG:
19552   case X86::VPCMPESTRM128REG:
19553   case X86::PCMPESTRM128MEM:
19554   case X86::VPCMPESTRM128MEM:
19555     assert(Subtarget->hasSSE42() &&
19556            "Target must have SSE4.2 or AVX features enabled");
19557     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19558
19559   // String/text processing lowering.
19560   case X86::PCMPISTRIREG:
19561   case X86::VPCMPISTRIREG:
19562   case X86::PCMPISTRIMEM:
19563   case X86::VPCMPISTRIMEM:
19564   case X86::PCMPESTRIREG:
19565   case X86::VPCMPESTRIREG:
19566   case X86::PCMPESTRIMEM:
19567   case X86::VPCMPESTRIMEM:
19568     assert(Subtarget->hasSSE42() &&
19569            "Target must have SSE4.2 or AVX features enabled");
19570     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19571
19572   // Thread synchronization.
19573   case X86::MONITOR:
19574     return EmitMonitor(MI, BB, Subtarget);
19575
19576   // xbegin
19577   case X86::XBEGIN:
19578     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19579
19580   case X86::VASTART_SAVE_XMM_REGS:
19581     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19582
19583   case X86::VAARG_64:
19584     return EmitVAARG64WithCustomInserter(MI, BB);
19585
19586   case X86::EH_SjLj_SetJmp32:
19587   case X86::EH_SjLj_SetJmp64:
19588     return emitEHSjLjSetJmp(MI, BB);
19589
19590   case X86::EH_SjLj_LongJmp32:
19591   case X86::EH_SjLj_LongJmp64:
19592     return emitEHSjLjLongJmp(MI, BB);
19593
19594   case TargetOpcode::STATEPOINT:
19595     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19596     // this point in the process.  We diverge later.
19597     return emitPatchPoint(MI, BB);
19598
19599   case TargetOpcode::STACKMAP:
19600   case TargetOpcode::PATCHPOINT:
19601     return emitPatchPoint(MI, BB);
19602
19603   case X86::VFMADDPDr213r:
19604   case X86::VFMADDPSr213r:
19605   case X86::VFMADDSDr213r:
19606   case X86::VFMADDSSr213r:
19607   case X86::VFMSUBPDr213r:
19608   case X86::VFMSUBPSr213r:
19609   case X86::VFMSUBSDr213r:
19610   case X86::VFMSUBSSr213r:
19611   case X86::VFNMADDPDr213r:
19612   case X86::VFNMADDPSr213r:
19613   case X86::VFNMADDSDr213r:
19614   case X86::VFNMADDSSr213r:
19615   case X86::VFNMSUBPDr213r:
19616   case X86::VFNMSUBPSr213r:
19617   case X86::VFNMSUBSDr213r:
19618   case X86::VFNMSUBSSr213r:
19619   case X86::VFMADDSUBPDr213r:
19620   case X86::VFMADDSUBPSr213r:
19621   case X86::VFMSUBADDPDr213r:
19622   case X86::VFMSUBADDPSr213r:
19623   case X86::VFMADDPDr213rY:
19624   case X86::VFMADDPSr213rY:
19625   case X86::VFMSUBPDr213rY:
19626   case X86::VFMSUBPSr213rY:
19627   case X86::VFNMADDPDr213rY:
19628   case X86::VFNMADDPSr213rY:
19629   case X86::VFNMSUBPDr213rY:
19630   case X86::VFNMSUBPSr213rY:
19631   case X86::VFMADDSUBPDr213rY:
19632   case X86::VFMADDSUBPSr213rY:
19633   case X86::VFMSUBADDPDr213rY:
19634   case X86::VFMSUBADDPSr213rY:
19635     return emitFMA3Instr(MI, BB);
19636   }
19637 }
19638
19639 //===----------------------------------------------------------------------===//
19640 //                           X86 Optimization Hooks
19641 //===----------------------------------------------------------------------===//
19642
19643 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19644                                                       APInt &KnownZero,
19645                                                       APInt &KnownOne,
19646                                                       const SelectionDAG &DAG,
19647                                                       unsigned Depth) const {
19648   unsigned BitWidth = KnownZero.getBitWidth();
19649   unsigned Opc = Op.getOpcode();
19650   assert((Opc >= ISD::BUILTIN_OP_END ||
19651           Opc == ISD::INTRINSIC_WO_CHAIN ||
19652           Opc == ISD::INTRINSIC_W_CHAIN ||
19653           Opc == ISD::INTRINSIC_VOID) &&
19654          "Should use MaskedValueIsZero if you don't know whether Op"
19655          " is a target node!");
19656
19657   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19658   switch (Opc) {
19659   default: break;
19660   case X86ISD::ADD:
19661   case X86ISD::SUB:
19662   case X86ISD::ADC:
19663   case X86ISD::SBB:
19664   case X86ISD::SMUL:
19665   case X86ISD::UMUL:
19666   case X86ISD::INC:
19667   case X86ISD::DEC:
19668   case X86ISD::OR:
19669   case X86ISD::XOR:
19670   case X86ISD::AND:
19671     // These nodes' second result is a boolean.
19672     if (Op.getResNo() == 0)
19673       break;
19674     // Fallthrough
19675   case X86ISD::SETCC:
19676     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19677     break;
19678   case ISD::INTRINSIC_WO_CHAIN: {
19679     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19680     unsigned NumLoBits = 0;
19681     switch (IntId) {
19682     default: break;
19683     case Intrinsic::x86_sse_movmsk_ps:
19684     case Intrinsic::x86_avx_movmsk_ps_256:
19685     case Intrinsic::x86_sse2_movmsk_pd:
19686     case Intrinsic::x86_avx_movmsk_pd_256:
19687     case Intrinsic::x86_mmx_pmovmskb:
19688     case Intrinsic::x86_sse2_pmovmskb_128:
19689     case Intrinsic::x86_avx2_pmovmskb: {
19690       // High bits of movmskp{s|d}, pmovmskb are known zero.
19691       switch (IntId) {
19692         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19693         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19694         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19695         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19696         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19697         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19698         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19699         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19700       }
19701       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19702       break;
19703     }
19704     }
19705     break;
19706   }
19707   }
19708 }
19709
19710 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19711   SDValue Op,
19712   const SelectionDAG &,
19713   unsigned Depth) const {
19714   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19715   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19716     return Op.getValueType().getScalarType().getSizeInBits();
19717
19718   // Fallback case.
19719   return 1;
19720 }
19721
19722 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19723 /// node is a GlobalAddress + offset.
19724 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19725                                        const GlobalValue* &GA,
19726                                        int64_t &Offset) const {
19727   if (N->getOpcode() == X86ISD::Wrapper) {
19728     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19729       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19730       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19731       return true;
19732     }
19733   }
19734   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19735 }
19736
19737 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19738 /// same as extracting the high 128-bit part of 256-bit vector and then
19739 /// inserting the result into the low part of a new 256-bit vector
19740 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19741   EVT VT = SVOp->getValueType(0);
19742   unsigned NumElems = VT.getVectorNumElements();
19743
19744   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19745   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19746     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19747         SVOp->getMaskElt(j) >= 0)
19748       return false;
19749
19750   return true;
19751 }
19752
19753 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19754 /// same as extracting the low 128-bit part of 256-bit vector and then
19755 /// inserting the result into the high part of a new 256-bit vector
19756 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19757   EVT VT = SVOp->getValueType(0);
19758   unsigned NumElems = VT.getVectorNumElements();
19759
19760   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19761   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19762     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19763         SVOp->getMaskElt(j) >= 0)
19764       return false;
19765
19766   return true;
19767 }
19768
19769 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19770 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19771                                         TargetLowering::DAGCombinerInfo &DCI,
19772                                         const X86Subtarget* Subtarget) {
19773   SDLoc dl(N);
19774   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19775   SDValue V1 = SVOp->getOperand(0);
19776   SDValue V2 = SVOp->getOperand(1);
19777   EVT VT = SVOp->getValueType(0);
19778   unsigned NumElems = VT.getVectorNumElements();
19779
19780   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19781       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19782     //
19783     //                   0,0,0,...
19784     //                      |
19785     //    V      UNDEF    BUILD_VECTOR    UNDEF
19786     //     \      /           \           /
19787     //  CONCAT_VECTOR         CONCAT_VECTOR
19788     //         \                  /
19789     //          \                /
19790     //          RESULT: V + zero extended
19791     //
19792     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19793         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19794         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19795       return SDValue();
19796
19797     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19798       return SDValue();
19799
19800     // To match the shuffle mask, the first half of the mask should
19801     // be exactly the first vector, and all the rest a splat with the
19802     // first element of the second one.
19803     for (unsigned i = 0; i != NumElems/2; ++i)
19804       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19805           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19806         return SDValue();
19807
19808     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19809     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19810       if (Ld->hasNUsesOfValue(1, 0)) {
19811         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19812         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19813         SDValue ResNode =
19814           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19815                                   Ld->getMemoryVT(),
19816                                   Ld->getPointerInfo(),
19817                                   Ld->getAlignment(),
19818                                   false/*isVolatile*/, true/*ReadMem*/,
19819                                   false/*WriteMem*/);
19820
19821         // Make sure the newly-created LOAD is in the same position as Ld in
19822         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19823         // and update uses of Ld's output chain to use the TokenFactor.
19824         if (Ld->hasAnyUseOfValue(1)) {
19825           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19826                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19827           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19828           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19829                                  SDValue(ResNode.getNode(), 1));
19830         }
19831
19832         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19833       }
19834     }
19835
19836     // Emit a zeroed vector and insert the desired subvector on its
19837     // first half.
19838     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19839     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19840     return DCI.CombineTo(N, InsV);
19841   }
19842
19843   //===--------------------------------------------------------------------===//
19844   // Combine some shuffles into subvector extracts and inserts:
19845   //
19846
19847   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19848   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19849     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19850     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19851     return DCI.CombineTo(N, InsV);
19852   }
19853
19854   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19855   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19856     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19857     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19858     return DCI.CombineTo(N, InsV);
19859   }
19860
19861   return SDValue();
19862 }
19863
19864 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19865 /// possible.
19866 ///
19867 /// This is the leaf of the recursive combinine below. When we have found some
19868 /// chain of single-use x86 shuffle instructions and accumulated the combined
19869 /// shuffle mask represented by them, this will try to pattern match that mask
19870 /// into either a single instruction if there is a special purpose instruction
19871 /// for this operation, or into a PSHUFB instruction which is a fully general
19872 /// instruction but should only be used to replace chains over a certain depth.
19873 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19874                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19875                                    TargetLowering::DAGCombinerInfo &DCI,
19876                                    const X86Subtarget *Subtarget) {
19877   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19878
19879   // Find the operand that enters the chain. Note that multiple uses are OK
19880   // here, we're not going to remove the operand we find.
19881   SDValue Input = Op.getOperand(0);
19882   while (Input.getOpcode() == ISD::BITCAST)
19883     Input = Input.getOperand(0);
19884
19885   MVT VT = Input.getSimpleValueType();
19886   MVT RootVT = Root.getSimpleValueType();
19887   SDLoc DL(Root);
19888
19889   // Just remove no-op shuffle masks.
19890   if (Mask.size() == 1) {
19891     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19892                   /*AddTo*/ true);
19893     return true;
19894   }
19895
19896   // Use the float domain if the operand type is a floating point type.
19897   bool FloatDomain = VT.isFloatingPoint();
19898
19899   // For floating point shuffles, we don't have free copies in the shuffle
19900   // instructions or the ability to load as part of the instruction, so
19901   // canonicalize their shuffles to UNPCK or MOV variants.
19902   //
19903   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19904   // vectors because it can have a load folded into it that UNPCK cannot. This
19905   // doesn't preclude something switching to the shorter encoding post-RA.
19906   //
19907   // FIXME: Should teach these routines about AVX vector widths.
19908   if (FloatDomain && VT.getSizeInBits() == 128) {
19909     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19910       bool Lo = Mask.equals({0, 0});
19911       unsigned Shuffle;
19912       MVT ShuffleVT;
19913       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19914       // is no slower than UNPCKLPD but has the option to fold the input operand
19915       // into even an unaligned memory load.
19916       if (Lo && Subtarget->hasSSE3()) {
19917         Shuffle = X86ISD::MOVDDUP;
19918         ShuffleVT = MVT::v2f64;
19919       } else {
19920         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19921         // than the UNPCK variants.
19922         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19923         ShuffleVT = MVT::v4f32;
19924       }
19925       if (Depth == 1 && Root->getOpcode() == Shuffle)
19926         return false; // Nothing to do!
19927       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19928       DCI.AddToWorklist(Op.getNode());
19929       if (Shuffle == X86ISD::MOVDDUP)
19930         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19931       else
19932         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19933       DCI.AddToWorklist(Op.getNode());
19934       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19935                     /*AddTo*/ true);
19936       return true;
19937     }
19938     if (Subtarget->hasSSE3() &&
19939         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19940       bool Lo = Mask.equals({0, 0, 2, 2});
19941       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19942       MVT ShuffleVT = MVT::v4f32;
19943       if (Depth == 1 && Root->getOpcode() == Shuffle)
19944         return false; // Nothing to do!
19945       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19946       DCI.AddToWorklist(Op.getNode());
19947       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19948       DCI.AddToWorklist(Op.getNode());
19949       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19950                     /*AddTo*/ true);
19951       return true;
19952     }
19953     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19954       bool Lo = Mask.equals({0, 0, 1, 1});
19955       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19956       MVT ShuffleVT = MVT::v4f32;
19957       if (Depth == 1 && Root->getOpcode() == Shuffle)
19958         return false; // Nothing to do!
19959       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19960       DCI.AddToWorklist(Op.getNode());
19961       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19962       DCI.AddToWorklist(Op.getNode());
19963       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19964                     /*AddTo*/ true);
19965       return true;
19966     }
19967   }
19968
19969   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19970   // variants as none of these have single-instruction variants that are
19971   // superior to the UNPCK formulation.
19972   if (!FloatDomain && VT.getSizeInBits() == 128 &&
19973       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19974        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19975        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19976        Mask.equals(
19977            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19978     bool Lo = Mask[0] == 0;
19979     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19980     if (Depth == 1 && Root->getOpcode() == Shuffle)
19981       return false; // Nothing to do!
19982     MVT ShuffleVT;
19983     switch (Mask.size()) {
19984     case 8:
19985       ShuffleVT = MVT::v8i16;
19986       break;
19987     case 16:
19988       ShuffleVT = MVT::v16i8;
19989       break;
19990     default:
19991       llvm_unreachable("Impossible mask size!");
19992     };
19993     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19994     DCI.AddToWorklist(Op.getNode());
19995     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19996     DCI.AddToWorklist(Op.getNode());
19997     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19998                   /*AddTo*/ true);
19999     return true;
20000   }
20001
20002   // Don't try to re-form single instruction chains under any circumstances now
20003   // that we've done encoding canonicalization for them.
20004   if (Depth < 2)
20005     return false;
20006
20007   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20008   // can replace them with a single PSHUFB instruction profitably. Intel's
20009   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20010   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20011   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20012     SmallVector<SDValue, 16> PSHUFBMask;
20013     int NumBytes = VT.getSizeInBits() / 8;
20014     int Ratio = NumBytes / Mask.size();
20015     for (int i = 0; i < NumBytes; ++i) {
20016       if (Mask[i / Ratio] == SM_SentinelUndef) {
20017         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20018         continue;
20019       }
20020       int M = Mask[i / Ratio] != SM_SentinelZero
20021                   ? Ratio * Mask[i / Ratio] + i % Ratio
20022                   : 255;
20023       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20024     }
20025     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20026     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20027     DCI.AddToWorklist(Op.getNode());
20028     SDValue PSHUFBMaskOp =
20029         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20030     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20031     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20032     DCI.AddToWorklist(Op.getNode());
20033     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20034                   /*AddTo*/ true);
20035     return true;
20036   }
20037
20038   // Failed to find any combines.
20039   return false;
20040 }
20041
20042 /// \brief Fully generic combining of x86 shuffle instructions.
20043 ///
20044 /// This should be the last combine run over the x86 shuffle instructions. Once
20045 /// they have been fully optimized, this will recursively consider all chains
20046 /// of single-use shuffle instructions, build a generic model of the cumulative
20047 /// shuffle operation, and check for simpler instructions which implement this
20048 /// operation. We use this primarily for two purposes:
20049 ///
20050 /// 1) Collapse generic shuffles to specialized single instructions when
20051 ///    equivalent. In most cases, this is just an encoding size win, but
20052 ///    sometimes we will collapse multiple generic shuffles into a single
20053 ///    special-purpose shuffle.
20054 /// 2) Look for sequences of shuffle instructions with 3 or more total
20055 ///    instructions, and replace them with the slightly more expensive SSSE3
20056 ///    PSHUFB instruction if available. We do this as the last combining step
20057 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20058 ///    a suitable short sequence of other instructions. The PHUFB will either
20059 ///    use a register or have to read from memory and so is slightly (but only
20060 ///    slightly) more expensive than the other shuffle instructions.
20061 ///
20062 /// Because this is inherently a quadratic operation (for each shuffle in
20063 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20064 /// This should never be an issue in practice as the shuffle lowering doesn't
20065 /// produce sequences of more than 8 instructions.
20066 ///
20067 /// FIXME: We will currently miss some cases where the redundant shuffling
20068 /// would simplify under the threshold for PSHUFB formation because of
20069 /// combine-ordering. To fix this, we should do the redundant instruction
20070 /// combining in this recursive walk.
20071 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20072                                           ArrayRef<int> RootMask,
20073                                           int Depth, bool HasPSHUFB,
20074                                           SelectionDAG &DAG,
20075                                           TargetLowering::DAGCombinerInfo &DCI,
20076                                           const X86Subtarget *Subtarget) {
20077   // Bound the depth of our recursive combine because this is ultimately
20078   // quadratic in nature.
20079   if (Depth > 8)
20080     return false;
20081
20082   // Directly rip through bitcasts to find the underlying operand.
20083   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20084     Op = Op.getOperand(0);
20085
20086   MVT VT = Op.getSimpleValueType();
20087   if (!VT.isVector())
20088     return false; // Bail if we hit a non-vector.
20089
20090   assert(Root.getSimpleValueType().isVector() &&
20091          "Shuffles operate on vector types!");
20092   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20093          "Can only combine shuffles of the same vector register size.");
20094
20095   if (!isTargetShuffle(Op.getOpcode()))
20096     return false;
20097   SmallVector<int, 16> OpMask;
20098   bool IsUnary;
20099   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20100   // We only can combine unary shuffles which we can decode the mask for.
20101   if (!HaveMask || !IsUnary)
20102     return false;
20103
20104   assert(VT.getVectorNumElements() == OpMask.size() &&
20105          "Different mask size from vector size!");
20106   assert(((RootMask.size() > OpMask.size() &&
20107            RootMask.size() % OpMask.size() == 0) ||
20108           (OpMask.size() > RootMask.size() &&
20109            OpMask.size() % RootMask.size() == 0) ||
20110           OpMask.size() == RootMask.size()) &&
20111          "The smaller number of elements must divide the larger.");
20112   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20113   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20114   assert(((RootRatio == 1 && OpRatio == 1) ||
20115           (RootRatio == 1) != (OpRatio == 1)) &&
20116          "Must not have a ratio for both incoming and op masks!");
20117
20118   SmallVector<int, 16> Mask;
20119   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20120
20121   // Merge this shuffle operation's mask into our accumulated mask. Note that
20122   // this shuffle's mask will be the first applied to the input, followed by the
20123   // root mask to get us all the way to the root value arrangement. The reason
20124   // for this order is that we are recursing up the operation chain.
20125   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20126     int RootIdx = i / RootRatio;
20127     if (RootMask[RootIdx] < 0) {
20128       // This is a zero or undef lane, we're done.
20129       Mask.push_back(RootMask[RootIdx]);
20130       continue;
20131     }
20132
20133     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20134     int OpIdx = RootMaskedIdx / OpRatio;
20135     if (OpMask[OpIdx] < 0) {
20136       // The incoming lanes are zero or undef, it doesn't matter which ones we
20137       // are using.
20138       Mask.push_back(OpMask[OpIdx]);
20139       continue;
20140     }
20141
20142     // Ok, we have non-zero lanes, map them through.
20143     Mask.push_back(OpMask[OpIdx] * OpRatio +
20144                    RootMaskedIdx % OpRatio);
20145   }
20146
20147   // See if we can recurse into the operand to combine more things.
20148   switch (Op.getOpcode()) {
20149     case X86ISD::PSHUFB:
20150       HasPSHUFB = true;
20151     case X86ISD::PSHUFD:
20152     case X86ISD::PSHUFHW:
20153     case X86ISD::PSHUFLW:
20154       if (Op.getOperand(0).hasOneUse() &&
20155           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20156                                         HasPSHUFB, DAG, DCI, Subtarget))
20157         return true;
20158       break;
20159
20160     case X86ISD::UNPCKL:
20161     case X86ISD::UNPCKH:
20162       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20163       // We can't check for single use, we have to check that this shuffle is the only user.
20164       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20165           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20166                                         HasPSHUFB, DAG, DCI, Subtarget))
20167           return true;
20168       break;
20169   }
20170
20171   // Minor canonicalization of the accumulated shuffle mask to make it easier
20172   // to match below. All this does is detect masks with squential pairs of
20173   // elements, and shrink them to the half-width mask. It does this in a loop
20174   // so it will reduce the size of the mask to the minimal width mask which
20175   // performs an equivalent shuffle.
20176   SmallVector<int, 16> WidenedMask;
20177   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20178     Mask = std::move(WidenedMask);
20179     WidenedMask.clear();
20180   }
20181
20182   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20183                                 Subtarget);
20184 }
20185
20186 /// \brief Get the PSHUF-style mask from PSHUF node.
20187 ///
20188 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20189 /// PSHUF-style masks that can be reused with such instructions.
20190 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20191   MVT VT = N.getSimpleValueType();
20192   SmallVector<int, 4> Mask;
20193   bool IsUnary;
20194   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20195   (void)HaveMask;
20196   assert(HaveMask);
20197
20198   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20199   // matter. Check that the upper masks are repeats and remove them.
20200   if (VT.getSizeInBits() > 128) {
20201     int LaneElts = 128 / VT.getScalarSizeInBits();
20202 #ifndef NDEBUG
20203     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20204       for (int j = 0; j < LaneElts; ++j)
20205         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20206                "Mask doesn't repeat in high 128-bit lanes!");
20207 #endif
20208     Mask.resize(LaneElts);
20209   }
20210
20211   switch (N.getOpcode()) {
20212   case X86ISD::PSHUFD:
20213     return Mask;
20214   case X86ISD::PSHUFLW:
20215     Mask.resize(4);
20216     return Mask;
20217   case X86ISD::PSHUFHW:
20218     Mask.erase(Mask.begin(), Mask.begin() + 4);
20219     for (int &M : Mask)
20220       M -= 4;
20221     return Mask;
20222   default:
20223     llvm_unreachable("No valid shuffle instruction found!");
20224   }
20225 }
20226
20227 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20228 ///
20229 /// We walk up the chain and look for a combinable shuffle, skipping over
20230 /// shuffles that we could hoist this shuffle's transformation past without
20231 /// altering anything.
20232 static SDValue
20233 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20234                              SelectionDAG &DAG,
20235                              TargetLowering::DAGCombinerInfo &DCI) {
20236   assert(N.getOpcode() == X86ISD::PSHUFD &&
20237          "Called with something other than an x86 128-bit half shuffle!");
20238   SDLoc DL(N);
20239
20240   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20241   // of the shuffles in the chain so that we can form a fresh chain to replace
20242   // this one.
20243   SmallVector<SDValue, 8> Chain;
20244   SDValue V = N.getOperand(0);
20245   for (; V.hasOneUse(); V = V.getOperand(0)) {
20246     switch (V.getOpcode()) {
20247     default:
20248       return SDValue(); // Nothing combined!
20249
20250     case ISD::BITCAST:
20251       // Skip bitcasts as we always know the type for the target specific
20252       // instructions.
20253       continue;
20254
20255     case X86ISD::PSHUFD:
20256       // Found another dword shuffle.
20257       break;
20258
20259     case X86ISD::PSHUFLW:
20260       // Check that the low words (being shuffled) are the identity in the
20261       // dword shuffle, and the high words are self-contained.
20262       if (Mask[0] != 0 || Mask[1] != 1 ||
20263           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20264         return SDValue();
20265
20266       Chain.push_back(V);
20267       continue;
20268
20269     case X86ISD::PSHUFHW:
20270       // Check that the high words (being shuffled) are the identity in the
20271       // dword shuffle, and the low words are self-contained.
20272       if (Mask[2] != 2 || Mask[3] != 3 ||
20273           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20274         return SDValue();
20275
20276       Chain.push_back(V);
20277       continue;
20278
20279     case X86ISD::UNPCKL:
20280     case X86ISD::UNPCKH:
20281       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20282       // shuffle into a preceding word shuffle.
20283       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20284           V.getSimpleValueType().getScalarType() != MVT::i16)
20285         return SDValue();
20286
20287       // Search for a half-shuffle which we can combine with.
20288       unsigned CombineOp =
20289           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20290       if (V.getOperand(0) != V.getOperand(1) ||
20291           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20292         return SDValue();
20293       Chain.push_back(V);
20294       V = V.getOperand(0);
20295       do {
20296         switch (V.getOpcode()) {
20297         default:
20298           return SDValue(); // Nothing to combine.
20299
20300         case X86ISD::PSHUFLW:
20301         case X86ISD::PSHUFHW:
20302           if (V.getOpcode() == CombineOp)
20303             break;
20304
20305           Chain.push_back(V);
20306
20307           // Fallthrough!
20308         case ISD::BITCAST:
20309           V = V.getOperand(0);
20310           continue;
20311         }
20312         break;
20313       } while (V.hasOneUse());
20314       break;
20315     }
20316     // Break out of the loop if we break out of the switch.
20317     break;
20318   }
20319
20320   if (!V.hasOneUse())
20321     // We fell out of the loop without finding a viable combining instruction.
20322     return SDValue();
20323
20324   // Merge this node's mask and our incoming mask.
20325   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20326   for (int &M : Mask)
20327     M = VMask[M];
20328   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20329                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20330
20331   // Rebuild the chain around this new shuffle.
20332   while (!Chain.empty()) {
20333     SDValue W = Chain.pop_back_val();
20334
20335     if (V.getValueType() != W.getOperand(0).getValueType())
20336       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20337
20338     switch (W.getOpcode()) {
20339     default:
20340       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20341
20342     case X86ISD::UNPCKL:
20343     case X86ISD::UNPCKH:
20344       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20345       break;
20346
20347     case X86ISD::PSHUFD:
20348     case X86ISD::PSHUFLW:
20349     case X86ISD::PSHUFHW:
20350       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20351       break;
20352     }
20353   }
20354   if (V.getValueType() != N.getValueType())
20355     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20356
20357   // Return the new chain to replace N.
20358   return V;
20359 }
20360
20361 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20362 ///
20363 /// We walk up the chain, skipping shuffles of the other half and looking
20364 /// through shuffles which switch halves trying to find a shuffle of the same
20365 /// pair of dwords.
20366 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20367                                         SelectionDAG &DAG,
20368                                         TargetLowering::DAGCombinerInfo &DCI) {
20369   assert(
20370       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20371       "Called with something other than an x86 128-bit half shuffle!");
20372   SDLoc DL(N);
20373   unsigned CombineOpcode = N.getOpcode();
20374
20375   // Walk up a single-use chain looking for a combinable shuffle.
20376   SDValue V = N.getOperand(0);
20377   for (; V.hasOneUse(); V = V.getOperand(0)) {
20378     switch (V.getOpcode()) {
20379     default:
20380       return false; // Nothing combined!
20381
20382     case ISD::BITCAST:
20383       // Skip bitcasts as we always know the type for the target specific
20384       // instructions.
20385       continue;
20386
20387     case X86ISD::PSHUFLW:
20388     case X86ISD::PSHUFHW:
20389       if (V.getOpcode() == CombineOpcode)
20390         break;
20391
20392       // Other-half shuffles are no-ops.
20393       continue;
20394     }
20395     // Break out of the loop if we break out of the switch.
20396     break;
20397   }
20398
20399   if (!V.hasOneUse())
20400     // We fell out of the loop without finding a viable combining instruction.
20401     return false;
20402
20403   // Combine away the bottom node as its shuffle will be accumulated into
20404   // a preceding shuffle.
20405   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20406
20407   // Record the old value.
20408   SDValue Old = V;
20409
20410   // Merge this node's mask and our incoming mask (adjusted to account for all
20411   // the pshufd instructions encountered).
20412   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20413   for (int &M : Mask)
20414     M = VMask[M];
20415   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20416                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20417
20418   // Check that the shuffles didn't cancel each other out. If not, we need to
20419   // combine to the new one.
20420   if (Old != V)
20421     // Replace the combinable shuffle with the combined one, updating all users
20422     // so that we re-evaluate the chain here.
20423     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20424
20425   return true;
20426 }
20427
20428 /// \brief Try to combine x86 target specific shuffles.
20429 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20430                                            TargetLowering::DAGCombinerInfo &DCI,
20431                                            const X86Subtarget *Subtarget) {
20432   SDLoc DL(N);
20433   MVT VT = N.getSimpleValueType();
20434   SmallVector<int, 4> Mask;
20435
20436   switch (N.getOpcode()) {
20437   case X86ISD::PSHUFD:
20438   case X86ISD::PSHUFLW:
20439   case X86ISD::PSHUFHW:
20440     Mask = getPSHUFShuffleMask(N);
20441     assert(Mask.size() == 4);
20442     break;
20443   default:
20444     return SDValue();
20445   }
20446
20447   // Nuke no-op shuffles that show up after combining.
20448   if (isNoopShuffleMask(Mask))
20449     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20450
20451   // Look for simplifications involving one or two shuffle instructions.
20452   SDValue V = N.getOperand(0);
20453   switch (N.getOpcode()) {
20454   default:
20455     break;
20456   case X86ISD::PSHUFLW:
20457   case X86ISD::PSHUFHW:
20458     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20459
20460     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20461       return SDValue(); // We combined away this shuffle, so we're done.
20462
20463     // See if this reduces to a PSHUFD which is no more expensive and can
20464     // combine with more operations. Note that it has to at least flip the
20465     // dwords as otherwise it would have been removed as a no-op.
20466     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20467       int DMask[] = {0, 1, 2, 3};
20468       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20469       DMask[DOffset + 0] = DOffset + 1;
20470       DMask[DOffset + 1] = DOffset + 0;
20471       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20472       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20473       DCI.AddToWorklist(V.getNode());
20474       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20475                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20476       DCI.AddToWorklist(V.getNode());
20477       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20478     }
20479
20480     // Look for shuffle patterns which can be implemented as a single unpack.
20481     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20482     // only works when we have a PSHUFD followed by two half-shuffles.
20483     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20484         (V.getOpcode() == X86ISD::PSHUFLW ||
20485          V.getOpcode() == X86ISD::PSHUFHW) &&
20486         V.getOpcode() != N.getOpcode() &&
20487         V.hasOneUse()) {
20488       SDValue D = V.getOperand(0);
20489       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20490         D = D.getOperand(0);
20491       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20492         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20493         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20494         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20495         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20496         int WordMask[8];
20497         for (int i = 0; i < 4; ++i) {
20498           WordMask[i + NOffset] = Mask[i] + NOffset;
20499           WordMask[i + VOffset] = VMask[i] + VOffset;
20500         }
20501         // Map the word mask through the DWord mask.
20502         int MappedMask[8];
20503         for (int i = 0; i < 8; ++i)
20504           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20505         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20506             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20507           // We can replace all three shuffles with an unpack.
20508           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20509           DCI.AddToWorklist(V.getNode());
20510           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20511                                                 : X86ISD::UNPCKH,
20512                              DL, VT, V, V);
20513         }
20514       }
20515     }
20516
20517     break;
20518
20519   case X86ISD::PSHUFD:
20520     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20521       return NewN;
20522
20523     break;
20524   }
20525
20526   return SDValue();
20527 }
20528
20529 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20530 ///
20531 /// We combine this directly on the abstract vector shuffle nodes so it is
20532 /// easier to generically match. We also insert dummy vector shuffle nodes for
20533 /// the operands which explicitly discard the lanes which are unused by this
20534 /// operation to try to flow through the rest of the combiner the fact that
20535 /// they're unused.
20536 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20537   SDLoc DL(N);
20538   EVT VT = N->getValueType(0);
20539
20540   // We only handle target-independent shuffles.
20541   // FIXME: It would be easy and harmless to use the target shuffle mask
20542   // extraction tool to support more.
20543   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20544     return SDValue();
20545
20546   auto *SVN = cast<ShuffleVectorSDNode>(N);
20547   ArrayRef<int> Mask = SVN->getMask();
20548   SDValue V1 = N->getOperand(0);
20549   SDValue V2 = N->getOperand(1);
20550
20551   // We require the first shuffle operand to be the SUB node, and the second to
20552   // be the ADD node.
20553   // FIXME: We should support the commuted patterns.
20554   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20555     return SDValue();
20556
20557   // If there are other uses of these operations we can't fold them.
20558   if (!V1->hasOneUse() || !V2->hasOneUse())
20559     return SDValue();
20560
20561   // Ensure that both operations have the same operands. Note that we can
20562   // commute the FADD operands.
20563   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20564   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20565       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20566     return SDValue();
20567
20568   // We're looking for blends between FADD and FSUB nodes. We insist on these
20569   // nodes being lined up in a specific expected pattern.
20570   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20571         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20572         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20573     return SDValue();
20574
20575   // Only specific types are legal at this point, assert so we notice if and
20576   // when these change.
20577   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20578           VT == MVT::v4f64) &&
20579          "Unknown vector type encountered!");
20580
20581   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20582 }
20583
20584 /// PerformShuffleCombine - Performs several different shuffle combines.
20585 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20586                                      TargetLowering::DAGCombinerInfo &DCI,
20587                                      const X86Subtarget *Subtarget) {
20588   SDLoc dl(N);
20589   SDValue N0 = N->getOperand(0);
20590   SDValue N1 = N->getOperand(1);
20591   EVT VT = N->getValueType(0);
20592
20593   // Don't create instructions with illegal types after legalize types has run.
20594   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20595   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20596     return SDValue();
20597
20598   // If we have legalized the vector types, look for blends of FADD and FSUB
20599   // nodes that we can fuse into an ADDSUB node.
20600   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20601     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20602       return AddSub;
20603
20604   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20605   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20606       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20607     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20608
20609   // During Type Legalization, when promoting illegal vector types,
20610   // the backend might introduce new shuffle dag nodes and bitcasts.
20611   //
20612   // This code performs the following transformation:
20613   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20614   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20615   //
20616   // We do this only if both the bitcast and the BINOP dag nodes have
20617   // one use. Also, perform this transformation only if the new binary
20618   // operation is legal. This is to avoid introducing dag nodes that
20619   // potentially need to be further expanded (or custom lowered) into a
20620   // less optimal sequence of dag nodes.
20621   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20622       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20623       N0.getOpcode() == ISD::BITCAST) {
20624     SDValue BC0 = N0.getOperand(0);
20625     EVT SVT = BC0.getValueType();
20626     unsigned Opcode = BC0.getOpcode();
20627     unsigned NumElts = VT.getVectorNumElements();
20628
20629     if (BC0.hasOneUse() && SVT.isVector() &&
20630         SVT.getVectorNumElements() * 2 == NumElts &&
20631         TLI.isOperationLegal(Opcode, VT)) {
20632       bool CanFold = false;
20633       switch (Opcode) {
20634       default : break;
20635       case ISD::ADD :
20636       case ISD::FADD :
20637       case ISD::SUB :
20638       case ISD::FSUB :
20639       case ISD::MUL :
20640       case ISD::FMUL :
20641         CanFold = true;
20642       }
20643
20644       unsigned SVTNumElts = SVT.getVectorNumElements();
20645       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20646       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20647         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20648       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20649         CanFold = SVOp->getMaskElt(i) < 0;
20650
20651       if (CanFold) {
20652         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20653         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20654         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20655         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20656       }
20657     }
20658   }
20659
20660   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20661   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20662   // consecutive, non-overlapping, and in the right order.
20663   SmallVector<SDValue, 16> Elts;
20664   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20665     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20666
20667   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20668   if (LD.getNode())
20669     return LD;
20670
20671   if (isTargetShuffle(N->getOpcode())) {
20672     SDValue Shuffle =
20673         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20674     if (Shuffle.getNode())
20675       return Shuffle;
20676
20677     // Try recursively combining arbitrary sequences of x86 shuffle
20678     // instructions into higher-order shuffles. We do this after combining
20679     // specific PSHUF instruction sequences into their minimal form so that we
20680     // can evaluate how many specialized shuffle instructions are involved in
20681     // a particular chain.
20682     SmallVector<int, 1> NonceMask; // Just a placeholder.
20683     NonceMask.push_back(0);
20684     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20685                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20686                                       DCI, Subtarget))
20687       return SDValue(); // This routine will use CombineTo to replace N.
20688   }
20689
20690   return SDValue();
20691 }
20692
20693 /// PerformTruncateCombine - Converts truncate operation to
20694 /// a sequence of vector shuffle operations.
20695 /// It is possible when we truncate 256-bit vector to 128-bit vector
20696 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20697                                       TargetLowering::DAGCombinerInfo &DCI,
20698                                       const X86Subtarget *Subtarget)  {
20699   return SDValue();
20700 }
20701
20702 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20703 /// specific shuffle of a load can be folded into a single element load.
20704 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20705 /// shuffles have been custom lowered so we need to handle those here.
20706 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20707                                          TargetLowering::DAGCombinerInfo &DCI) {
20708   if (DCI.isBeforeLegalizeOps())
20709     return SDValue();
20710
20711   SDValue InVec = N->getOperand(0);
20712   SDValue EltNo = N->getOperand(1);
20713
20714   if (!isa<ConstantSDNode>(EltNo))
20715     return SDValue();
20716
20717   EVT OriginalVT = InVec.getValueType();
20718
20719   if (InVec.getOpcode() == ISD::BITCAST) {
20720     // Don't duplicate a load with other uses.
20721     if (!InVec.hasOneUse())
20722       return SDValue();
20723     EVT BCVT = InVec.getOperand(0).getValueType();
20724     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20725       return SDValue();
20726     InVec = InVec.getOperand(0);
20727   }
20728
20729   EVT CurrentVT = InVec.getValueType();
20730
20731   if (!isTargetShuffle(InVec.getOpcode()))
20732     return SDValue();
20733
20734   // Don't duplicate a load with other uses.
20735   if (!InVec.hasOneUse())
20736     return SDValue();
20737
20738   SmallVector<int, 16> ShuffleMask;
20739   bool UnaryShuffle;
20740   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20741                             ShuffleMask, UnaryShuffle))
20742     return SDValue();
20743
20744   // Select the input vector, guarding against out of range extract vector.
20745   unsigned NumElems = CurrentVT.getVectorNumElements();
20746   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20747   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20748   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20749                                          : InVec.getOperand(1);
20750
20751   // If inputs to shuffle are the same for both ops, then allow 2 uses
20752   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20753                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20754
20755   if (LdNode.getOpcode() == ISD::BITCAST) {
20756     // Don't duplicate a load with other uses.
20757     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20758       return SDValue();
20759
20760     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20761     LdNode = LdNode.getOperand(0);
20762   }
20763
20764   if (!ISD::isNormalLoad(LdNode.getNode()))
20765     return SDValue();
20766
20767   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20768
20769   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20770     return SDValue();
20771
20772   EVT EltVT = N->getValueType(0);
20773   // If there's a bitcast before the shuffle, check if the load type and
20774   // alignment is valid.
20775   unsigned Align = LN0->getAlignment();
20776   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20777   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20778       EltVT.getTypeForEVT(*DAG.getContext()));
20779
20780   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20781     return SDValue();
20782
20783   // All checks match so transform back to vector_shuffle so that DAG combiner
20784   // can finish the job
20785   SDLoc dl(N);
20786
20787   // Create shuffle node taking into account the case that its a unary shuffle
20788   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20789                                    : InVec.getOperand(1);
20790   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20791                                  InVec.getOperand(0), Shuffle,
20792                                  &ShuffleMask[0]);
20793   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20794   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20795                      EltNo);
20796 }
20797
20798 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20799 /// special and don't usually play with other vector types, it's better to
20800 /// handle them early to be sure we emit efficient code by avoiding
20801 /// store-load conversions.
20802 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20803   if (N->getValueType(0) != MVT::x86mmx ||
20804       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20805       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20806     return SDValue();
20807
20808   SDValue V = N->getOperand(0);
20809   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20810   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20811     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20812                        N->getValueType(0), V.getOperand(0));
20813
20814   return SDValue();
20815 }
20816
20817 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20818 /// generation and convert it from being a bunch of shuffles and extracts
20819 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20820 /// storing the value and loading scalars back, while for x64 we should
20821 /// use 64-bit extracts and shifts.
20822 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20823                                          TargetLowering::DAGCombinerInfo &DCI) {
20824   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20825   if (NewOp.getNode())
20826     return NewOp;
20827
20828   SDValue InputVector = N->getOperand(0);
20829
20830   // Detect mmx to i32 conversion through a v2i32 elt extract.
20831   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20832       N->getValueType(0) == MVT::i32 &&
20833       InputVector.getValueType() == MVT::v2i32) {
20834
20835     // The bitcast source is a direct mmx result.
20836     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20837     if (MMXSrc.getValueType() == MVT::x86mmx)
20838       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20839                          N->getValueType(0),
20840                          InputVector.getNode()->getOperand(0));
20841
20842     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20843     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20844     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20845         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20846         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20847         MMXSrcOp.getValueType() == MVT::v1i64 &&
20848         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20849       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20850                          N->getValueType(0),
20851                          MMXSrcOp.getOperand(0));
20852   }
20853
20854   // Only operate on vectors of 4 elements, where the alternative shuffling
20855   // gets to be more expensive.
20856   if (InputVector.getValueType() != MVT::v4i32)
20857     return SDValue();
20858
20859   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20860   // single use which is a sign-extend or zero-extend, and all elements are
20861   // used.
20862   SmallVector<SDNode *, 4> Uses;
20863   unsigned ExtractedElements = 0;
20864   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20865        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20866     if (UI.getUse().getResNo() != InputVector.getResNo())
20867       return SDValue();
20868
20869     SDNode *Extract = *UI;
20870     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20871       return SDValue();
20872
20873     if (Extract->getValueType(0) != MVT::i32)
20874       return SDValue();
20875     if (!Extract->hasOneUse())
20876       return SDValue();
20877     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20878         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20879       return SDValue();
20880     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20881       return SDValue();
20882
20883     // Record which element was extracted.
20884     ExtractedElements |=
20885       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20886
20887     Uses.push_back(Extract);
20888   }
20889
20890   // If not all the elements were used, this may not be worthwhile.
20891   if (ExtractedElements != 15)
20892     return SDValue();
20893
20894   // Ok, we've now decided to do the transformation.
20895   // If 64-bit shifts are legal, use the extract-shift sequence,
20896   // otherwise bounce the vector off the cache.
20897   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20898   SDValue Vals[4];
20899   SDLoc dl(InputVector);
20900
20901   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20902     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20903     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20904     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20905       DAG.getConstant(0, dl, VecIdxTy));
20906     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20907       DAG.getConstant(1, dl, VecIdxTy));
20908
20909     SDValue ShAmt = DAG.getConstant(32, dl,
20910       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20911     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20912     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20913       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20914     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20915     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20916       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20917   } else {
20918     // Store the value to a temporary stack slot.
20919     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20920     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20921       MachinePointerInfo(), false, false, 0);
20922
20923     EVT ElementType = InputVector.getValueType().getVectorElementType();
20924     unsigned EltSize = ElementType.getSizeInBits() / 8;
20925
20926     // Replace each use (extract) with a load of the appropriate element.
20927     for (unsigned i = 0; i < 4; ++i) {
20928       uint64_t Offset = EltSize * i;
20929       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
20930
20931       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20932                                        StackPtr, OffsetVal);
20933
20934       // Load the scalar.
20935       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20936                             ScalarAddr, MachinePointerInfo(),
20937                             false, false, false, 0);
20938
20939     }
20940   }
20941
20942   // Replace the extracts
20943   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20944     UE = Uses.end(); UI != UE; ++UI) {
20945     SDNode *Extract = *UI;
20946
20947     SDValue Idx = Extract->getOperand(1);
20948     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20949     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20950   }
20951
20952   // The replacement was made in place; don't return anything.
20953   return SDValue();
20954 }
20955
20956 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20957 static std::pair<unsigned, bool>
20958 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20959                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20960   if (!VT.isVector())
20961     return std::make_pair(0, false);
20962
20963   bool NeedSplit = false;
20964   switch (VT.getSimpleVT().SimpleTy) {
20965   default: return std::make_pair(0, false);
20966   case MVT::v4i64:
20967   case MVT::v2i64:
20968     if (!Subtarget->hasVLX())
20969       return std::make_pair(0, false);
20970     break;
20971   case MVT::v64i8:
20972   case MVT::v32i16:
20973     if (!Subtarget->hasBWI())
20974       return std::make_pair(0, false);
20975     break;
20976   case MVT::v16i32:
20977   case MVT::v8i64:
20978     if (!Subtarget->hasAVX512())
20979       return std::make_pair(0, false);
20980     break;
20981   case MVT::v32i8:
20982   case MVT::v16i16:
20983   case MVT::v8i32:
20984     if (!Subtarget->hasAVX2())
20985       NeedSplit = true;
20986     if (!Subtarget->hasAVX())
20987       return std::make_pair(0, false);
20988     break;
20989   case MVT::v16i8:
20990   case MVT::v8i16:
20991   case MVT::v4i32:
20992     if (!Subtarget->hasSSE2())
20993       return std::make_pair(0, false);
20994   }
20995
20996   // SSE2 has only a small subset of the operations.
20997   bool hasUnsigned = Subtarget->hasSSE41() ||
20998                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20999   bool hasSigned = Subtarget->hasSSE41() ||
21000                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21001
21002   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21003
21004   unsigned Opc = 0;
21005   // Check for x CC y ? x : y.
21006   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21007       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21008     switch (CC) {
21009     default: break;
21010     case ISD::SETULT:
21011     case ISD::SETULE:
21012       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21013     case ISD::SETUGT:
21014     case ISD::SETUGE:
21015       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21016     case ISD::SETLT:
21017     case ISD::SETLE:
21018       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21019     case ISD::SETGT:
21020     case ISD::SETGE:
21021       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21022     }
21023   // Check for x CC y ? y : x -- a min/max with reversed arms.
21024   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21025              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21026     switch (CC) {
21027     default: break;
21028     case ISD::SETULT:
21029     case ISD::SETULE:
21030       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21031     case ISD::SETUGT:
21032     case ISD::SETUGE:
21033       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21034     case ISD::SETLT:
21035     case ISD::SETLE:
21036       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21037     case ISD::SETGT:
21038     case ISD::SETGE:
21039       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21040     }
21041   }
21042
21043   return std::make_pair(Opc, NeedSplit);
21044 }
21045
21046 static SDValue
21047 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21048                                       const X86Subtarget *Subtarget) {
21049   SDLoc dl(N);
21050   SDValue Cond = N->getOperand(0);
21051   SDValue LHS = N->getOperand(1);
21052   SDValue RHS = N->getOperand(2);
21053
21054   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21055     SDValue CondSrc = Cond->getOperand(0);
21056     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21057       Cond = CondSrc->getOperand(0);
21058   }
21059
21060   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21061     return SDValue();
21062
21063   // A vselect where all conditions and data are constants can be optimized into
21064   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21065   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21066       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21067     return SDValue();
21068
21069   unsigned MaskValue = 0;
21070   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21071     return SDValue();
21072
21073   MVT VT = N->getSimpleValueType(0);
21074   unsigned NumElems = VT.getVectorNumElements();
21075   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21076   for (unsigned i = 0; i < NumElems; ++i) {
21077     // Be sure we emit undef where we can.
21078     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21079       ShuffleMask[i] = -1;
21080     else
21081       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21082   }
21083
21084   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21085   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21086     return SDValue();
21087   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21088 }
21089
21090 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21091 /// nodes.
21092 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21093                                     TargetLowering::DAGCombinerInfo &DCI,
21094                                     const X86Subtarget *Subtarget) {
21095   SDLoc DL(N);
21096   SDValue Cond = N->getOperand(0);
21097   // Get the LHS/RHS of the select.
21098   SDValue LHS = N->getOperand(1);
21099   SDValue RHS = N->getOperand(2);
21100   EVT VT = LHS.getValueType();
21101   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21102
21103   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21104   // instructions match the semantics of the common C idiom x<y?x:y but not
21105   // x<=y?x:y, because of how they handle negative zero (which can be
21106   // ignored in unsafe-math mode).
21107   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21108   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21109       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21110       (Subtarget->hasSSE2() ||
21111        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21112     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21113
21114     unsigned Opcode = 0;
21115     // Check for x CC y ? x : y.
21116     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21117         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21118       switch (CC) {
21119       default: break;
21120       case ISD::SETULT:
21121         // Converting this to a min would handle NaNs incorrectly, and swapping
21122         // the operands would cause it to handle comparisons between positive
21123         // and negative zero incorrectly.
21124         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21125           if (!DAG.getTarget().Options.UnsafeFPMath &&
21126               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21127             break;
21128           std::swap(LHS, RHS);
21129         }
21130         Opcode = X86ISD::FMIN;
21131         break;
21132       case ISD::SETOLE:
21133         // Converting this to a min would handle comparisons between positive
21134         // and negative zero incorrectly.
21135         if (!DAG.getTarget().Options.UnsafeFPMath &&
21136             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21137           break;
21138         Opcode = X86ISD::FMIN;
21139         break;
21140       case ISD::SETULE:
21141         // Converting this to a min would handle both negative zeros and NaNs
21142         // incorrectly, but we can swap the operands to fix both.
21143         std::swap(LHS, RHS);
21144       case ISD::SETOLT:
21145       case ISD::SETLT:
21146       case ISD::SETLE:
21147         Opcode = X86ISD::FMIN;
21148         break;
21149
21150       case ISD::SETOGE:
21151         // Converting this to a max would handle comparisons between positive
21152         // and negative zero incorrectly.
21153         if (!DAG.getTarget().Options.UnsafeFPMath &&
21154             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21155           break;
21156         Opcode = X86ISD::FMAX;
21157         break;
21158       case ISD::SETUGT:
21159         // Converting this to a max would handle NaNs incorrectly, and swapping
21160         // the operands would cause it to handle comparisons between positive
21161         // and negative zero incorrectly.
21162         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21163           if (!DAG.getTarget().Options.UnsafeFPMath &&
21164               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21165             break;
21166           std::swap(LHS, RHS);
21167         }
21168         Opcode = X86ISD::FMAX;
21169         break;
21170       case ISD::SETUGE:
21171         // Converting this to a max would handle both negative zeros and NaNs
21172         // incorrectly, but we can swap the operands to fix both.
21173         std::swap(LHS, RHS);
21174       case ISD::SETOGT:
21175       case ISD::SETGT:
21176       case ISD::SETGE:
21177         Opcode = X86ISD::FMAX;
21178         break;
21179       }
21180     // Check for x CC y ? y : x -- a min/max with reversed arms.
21181     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21182                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21183       switch (CC) {
21184       default: break;
21185       case ISD::SETOGE:
21186         // Converting this to a min would handle comparisons between positive
21187         // and negative zero incorrectly, and swapping the operands would
21188         // cause it to handle NaNs incorrectly.
21189         if (!DAG.getTarget().Options.UnsafeFPMath &&
21190             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21191           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21192             break;
21193           std::swap(LHS, RHS);
21194         }
21195         Opcode = X86ISD::FMIN;
21196         break;
21197       case ISD::SETUGT:
21198         // Converting this to a min would handle NaNs incorrectly.
21199         if (!DAG.getTarget().Options.UnsafeFPMath &&
21200             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21201           break;
21202         Opcode = X86ISD::FMIN;
21203         break;
21204       case ISD::SETUGE:
21205         // Converting this to a min would handle both negative zeros and NaNs
21206         // incorrectly, but we can swap the operands to fix both.
21207         std::swap(LHS, RHS);
21208       case ISD::SETOGT:
21209       case ISD::SETGT:
21210       case ISD::SETGE:
21211         Opcode = X86ISD::FMIN;
21212         break;
21213
21214       case ISD::SETULT:
21215         // Converting this to a max would handle NaNs incorrectly.
21216         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21217           break;
21218         Opcode = X86ISD::FMAX;
21219         break;
21220       case ISD::SETOLE:
21221         // Converting this to a max would handle comparisons between positive
21222         // and negative zero incorrectly, and swapping the operands would
21223         // cause it to handle NaNs incorrectly.
21224         if (!DAG.getTarget().Options.UnsafeFPMath &&
21225             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21226           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21227             break;
21228           std::swap(LHS, RHS);
21229         }
21230         Opcode = X86ISD::FMAX;
21231         break;
21232       case ISD::SETULE:
21233         // Converting this to a max would handle both negative zeros and NaNs
21234         // incorrectly, but we can swap the operands to fix both.
21235         std::swap(LHS, RHS);
21236       case ISD::SETOLT:
21237       case ISD::SETLT:
21238       case ISD::SETLE:
21239         Opcode = X86ISD::FMAX;
21240         break;
21241       }
21242     }
21243
21244     if (Opcode)
21245       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21246   }
21247
21248   EVT CondVT = Cond.getValueType();
21249   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21250       CondVT.getVectorElementType() == MVT::i1) {
21251     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21252     // lowering on KNL. In this case we convert it to
21253     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21254     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21255     // Since SKX these selects have a proper lowering.
21256     EVT OpVT = LHS.getValueType();
21257     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21258         (OpVT.getVectorElementType() == MVT::i8 ||
21259          OpVT.getVectorElementType() == MVT::i16) &&
21260         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21261       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21262       DCI.AddToWorklist(Cond.getNode());
21263       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21264     }
21265   }
21266   // If this is a select between two integer constants, try to do some
21267   // optimizations.
21268   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21269     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21270       // Don't do this for crazy integer types.
21271       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21272         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21273         // so that TrueC (the true value) is larger than FalseC.
21274         bool NeedsCondInvert = false;
21275
21276         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21277             // Efficiently invertible.
21278             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21279              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21280               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21281           NeedsCondInvert = true;
21282           std::swap(TrueC, FalseC);
21283         }
21284
21285         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21286         if (FalseC->getAPIntValue() == 0 &&
21287             TrueC->getAPIntValue().isPowerOf2()) {
21288           if (NeedsCondInvert) // Invert the condition if needed.
21289             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21290                                DAG.getConstant(1, DL, Cond.getValueType()));
21291
21292           // Zero extend the condition if needed.
21293           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21294
21295           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21296           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21297                              DAG.getConstant(ShAmt, DL, MVT::i8));
21298         }
21299
21300         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21301         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21302           if (NeedsCondInvert) // Invert the condition if needed.
21303             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21304                                DAG.getConstant(1, DL, Cond.getValueType()));
21305
21306           // Zero extend the condition if needed.
21307           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21308                              FalseC->getValueType(0), Cond);
21309           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21310                              SDValue(FalseC, 0));
21311         }
21312
21313         // Optimize cases that will turn into an LEA instruction.  This requires
21314         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21315         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21316           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21317           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21318
21319           bool isFastMultiplier = false;
21320           if (Diff < 10) {
21321             switch ((unsigned char)Diff) {
21322               default: break;
21323               case 1:  // result = add base, cond
21324               case 2:  // result = lea base(    , cond*2)
21325               case 3:  // result = lea base(cond, cond*2)
21326               case 4:  // result = lea base(    , cond*4)
21327               case 5:  // result = lea base(cond, cond*4)
21328               case 8:  // result = lea base(    , cond*8)
21329               case 9:  // result = lea base(cond, cond*8)
21330                 isFastMultiplier = true;
21331                 break;
21332             }
21333           }
21334
21335           if (isFastMultiplier) {
21336             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21337             if (NeedsCondInvert) // Invert the condition if needed.
21338               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21339                                  DAG.getConstant(1, DL, Cond.getValueType()));
21340
21341             // Zero extend the condition if needed.
21342             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21343                                Cond);
21344             // Scale the condition by the difference.
21345             if (Diff != 1)
21346               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21347                                  DAG.getConstant(Diff, DL,
21348                                                  Cond.getValueType()));
21349
21350             // Add the base if non-zero.
21351             if (FalseC->getAPIntValue() != 0)
21352               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21353                                  SDValue(FalseC, 0));
21354             return Cond;
21355           }
21356         }
21357       }
21358   }
21359
21360   // Canonicalize max and min:
21361   // (x > y) ? x : y -> (x >= y) ? x : y
21362   // (x < y) ? x : y -> (x <= y) ? x : y
21363   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21364   // the need for an extra compare
21365   // against zero. e.g.
21366   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21367   // subl   %esi, %edi
21368   // testl  %edi, %edi
21369   // movl   $0, %eax
21370   // cmovgl %edi, %eax
21371   // =>
21372   // xorl   %eax, %eax
21373   // subl   %esi, $edi
21374   // cmovsl %eax, %edi
21375   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21376       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21377       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21378     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21379     switch (CC) {
21380     default: break;
21381     case ISD::SETLT:
21382     case ISD::SETGT: {
21383       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21384       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21385                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21386       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21387     }
21388     }
21389   }
21390
21391   // Early exit check
21392   if (!TLI.isTypeLegal(VT))
21393     return SDValue();
21394
21395   // Match VSELECTs into subs with unsigned saturation.
21396   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21397       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21398       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21399        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21400     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21401
21402     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21403     // left side invert the predicate to simplify logic below.
21404     SDValue Other;
21405     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21406       Other = RHS;
21407       CC = ISD::getSetCCInverse(CC, true);
21408     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21409       Other = LHS;
21410     }
21411
21412     if (Other.getNode() && Other->getNumOperands() == 2 &&
21413         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21414       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21415       SDValue CondRHS = Cond->getOperand(1);
21416
21417       // Look for a general sub with unsigned saturation first.
21418       // x >= y ? x-y : 0 --> subus x, y
21419       // x >  y ? x-y : 0 --> subus x, y
21420       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21421           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21422         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21423
21424       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21425         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21426           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21427             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21428               // If the RHS is a constant we have to reverse the const
21429               // canonicalization.
21430               // x > C-1 ? x+-C : 0 --> subus x, C
21431               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21432                   CondRHSConst->getAPIntValue() ==
21433                       (-OpRHSConst->getAPIntValue() - 1))
21434                 return DAG.getNode(
21435                     X86ISD::SUBUS, DL, VT, OpLHS,
21436                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21437
21438           // Another special case: If C was a sign bit, the sub has been
21439           // canonicalized into a xor.
21440           // FIXME: Would it be better to use computeKnownBits to determine
21441           //        whether it's safe to decanonicalize the xor?
21442           // x s< 0 ? x^C : 0 --> subus x, C
21443           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21444               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21445               OpRHSConst->getAPIntValue().isSignBit())
21446             // Note that we have to rebuild the RHS constant here to ensure we
21447             // don't rely on particular values of undef lanes.
21448             return DAG.getNode(
21449                 X86ISD::SUBUS, DL, VT, OpLHS,
21450                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21451         }
21452     }
21453   }
21454
21455   // Try to match a min/max vector operation.
21456   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21457     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21458     unsigned Opc = ret.first;
21459     bool NeedSplit = ret.second;
21460
21461     if (Opc && NeedSplit) {
21462       unsigned NumElems = VT.getVectorNumElements();
21463       // Extract the LHS vectors
21464       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21465       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21466
21467       // Extract the RHS vectors
21468       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21469       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21470
21471       // Create min/max for each subvector
21472       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21473       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21474
21475       // Merge the result
21476       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21477     } else if (Opc)
21478       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21479   }
21480
21481   // Simplify vector selection if condition value type matches vselect
21482   // operand type
21483   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21484     assert(Cond.getValueType().isVector() &&
21485            "vector select expects a vector selector!");
21486
21487     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21488     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21489
21490     // Try invert the condition if true value is not all 1s and false value
21491     // is not all 0s.
21492     if (!TValIsAllOnes && !FValIsAllZeros &&
21493         // Check if the selector will be produced by CMPP*/PCMP*
21494         Cond.getOpcode() == ISD::SETCC &&
21495         // Check if SETCC has already been promoted
21496         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21497       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21498       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21499
21500       if (TValIsAllZeros || FValIsAllOnes) {
21501         SDValue CC = Cond.getOperand(2);
21502         ISD::CondCode NewCC =
21503           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21504                                Cond.getOperand(0).getValueType().isInteger());
21505         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21506         std::swap(LHS, RHS);
21507         TValIsAllOnes = FValIsAllOnes;
21508         FValIsAllZeros = TValIsAllZeros;
21509       }
21510     }
21511
21512     if (TValIsAllOnes || FValIsAllZeros) {
21513       SDValue Ret;
21514
21515       if (TValIsAllOnes && FValIsAllZeros)
21516         Ret = Cond;
21517       else if (TValIsAllOnes)
21518         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21519                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21520       else if (FValIsAllZeros)
21521         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21522                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21523
21524       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21525     }
21526   }
21527
21528   // We should generate an X86ISD::BLENDI from a vselect if its argument
21529   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21530   // constants. This specific pattern gets generated when we split a
21531   // selector for a 512 bit vector in a machine without AVX512 (but with
21532   // 256-bit vectors), during legalization:
21533   //
21534   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21535   //
21536   // Iff we find this pattern and the build_vectors are built from
21537   // constants, we translate the vselect into a shuffle_vector that we
21538   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21539   if ((N->getOpcode() == ISD::VSELECT ||
21540        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21541       !DCI.isBeforeLegalize()) {
21542     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21543     if (Shuffle.getNode())
21544       return Shuffle;
21545   }
21546
21547   // If this is a *dynamic* select (non-constant condition) and we can match
21548   // this node with one of the variable blend instructions, restructure the
21549   // condition so that the blends can use the high bit of each element and use
21550   // SimplifyDemandedBits to simplify the condition operand.
21551   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21552       !DCI.isBeforeLegalize() &&
21553       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21554     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21555
21556     // Don't optimize vector selects that map to mask-registers.
21557     if (BitWidth == 1)
21558       return SDValue();
21559
21560     // We can only handle the cases where VSELECT is directly legal on the
21561     // subtarget. We custom lower VSELECT nodes with constant conditions and
21562     // this makes it hard to see whether a dynamic VSELECT will correctly
21563     // lower, so we both check the operation's status and explicitly handle the
21564     // cases where a *dynamic* blend will fail even though a constant-condition
21565     // blend could be custom lowered.
21566     // FIXME: We should find a better way to handle this class of problems.
21567     // Potentially, we should combine constant-condition vselect nodes
21568     // pre-legalization into shuffles and not mark as many types as custom
21569     // lowered.
21570     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21571       return SDValue();
21572     // FIXME: We don't support i16-element blends currently. We could and
21573     // should support them by making *all* the bits in the condition be set
21574     // rather than just the high bit and using an i8-element blend.
21575     if (VT.getScalarType() == MVT::i16)
21576       return SDValue();
21577     // Dynamic blending was only available from SSE4.1 onward.
21578     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21579       return SDValue();
21580     // Byte blends are only available in AVX2
21581     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21582         !Subtarget->hasAVX2())
21583       return SDValue();
21584
21585     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21586     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21587
21588     APInt KnownZero, KnownOne;
21589     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21590                                           DCI.isBeforeLegalizeOps());
21591     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21592         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21593                                  TLO)) {
21594       // If we changed the computation somewhere in the DAG, this change
21595       // will affect all users of Cond.
21596       // Make sure it is fine and update all the nodes so that we do not
21597       // use the generic VSELECT anymore. Otherwise, we may perform
21598       // wrong optimizations as we messed up with the actual expectation
21599       // for the vector boolean values.
21600       if (Cond != TLO.Old) {
21601         // Check all uses of that condition operand to check whether it will be
21602         // consumed by non-BLEND instructions, which may depend on all bits are
21603         // set properly.
21604         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21605              I != E; ++I)
21606           if (I->getOpcode() != ISD::VSELECT)
21607             // TODO: Add other opcodes eventually lowered into BLEND.
21608             return SDValue();
21609
21610         // Update all the users of the condition, before committing the change,
21611         // so that the VSELECT optimizations that expect the correct vector
21612         // boolean value will not be triggered.
21613         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21614              I != E; ++I)
21615           DAG.ReplaceAllUsesOfValueWith(
21616               SDValue(*I, 0),
21617               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21618                           Cond, I->getOperand(1), I->getOperand(2)));
21619         DCI.CommitTargetLoweringOpt(TLO);
21620         return SDValue();
21621       }
21622       // At this point, only Cond is changed. Change the condition
21623       // just for N to keep the opportunity to optimize all other
21624       // users their own way.
21625       DAG.ReplaceAllUsesOfValueWith(
21626           SDValue(N, 0),
21627           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21628                       TLO.New, N->getOperand(1), N->getOperand(2)));
21629       return SDValue();
21630     }
21631   }
21632
21633   return SDValue();
21634 }
21635
21636 // Check whether a boolean test is testing a boolean value generated by
21637 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21638 // code.
21639 //
21640 // Simplify the following patterns:
21641 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21642 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21643 // to (Op EFLAGS Cond)
21644 //
21645 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21646 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21647 // to (Op EFLAGS !Cond)
21648 //
21649 // where Op could be BRCOND or CMOV.
21650 //
21651 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21652   // Quit if not CMP and SUB with its value result used.
21653   if (Cmp.getOpcode() != X86ISD::CMP &&
21654       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21655       return SDValue();
21656
21657   // Quit if not used as a boolean value.
21658   if (CC != X86::COND_E && CC != X86::COND_NE)
21659     return SDValue();
21660
21661   // Check CMP operands. One of them should be 0 or 1 and the other should be
21662   // an SetCC or extended from it.
21663   SDValue Op1 = Cmp.getOperand(0);
21664   SDValue Op2 = Cmp.getOperand(1);
21665
21666   SDValue SetCC;
21667   const ConstantSDNode* C = nullptr;
21668   bool needOppositeCond = (CC == X86::COND_E);
21669   bool checkAgainstTrue = false; // Is it a comparison against 1?
21670
21671   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21672     SetCC = Op2;
21673   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21674     SetCC = Op1;
21675   else // Quit if all operands are not constants.
21676     return SDValue();
21677
21678   if (C->getZExtValue() == 1) {
21679     needOppositeCond = !needOppositeCond;
21680     checkAgainstTrue = true;
21681   } else if (C->getZExtValue() != 0)
21682     // Quit if the constant is neither 0 or 1.
21683     return SDValue();
21684
21685   bool truncatedToBoolWithAnd = false;
21686   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21687   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21688          SetCC.getOpcode() == ISD::TRUNCATE ||
21689          SetCC.getOpcode() == ISD::AND) {
21690     if (SetCC.getOpcode() == ISD::AND) {
21691       int OpIdx = -1;
21692       ConstantSDNode *CS;
21693       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21694           CS->getZExtValue() == 1)
21695         OpIdx = 1;
21696       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21697           CS->getZExtValue() == 1)
21698         OpIdx = 0;
21699       if (OpIdx == -1)
21700         break;
21701       SetCC = SetCC.getOperand(OpIdx);
21702       truncatedToBoolWithAnd = true;
21703     } else
21704       SetCC = SetCC.getOperand(0);
21705   }
21706
21707   switch (SetCC.getOpcode()) {
21708   case X86ISD::SETCC_CARRY:
21709     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21710     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21711     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21712     // truncated to i1 using 'and'.
21713     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21714       break;
21715     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21716            "Invalid use of SETCC_CARRY!");
21717     // FALL THROUGH
21718   case X86ISD::SETCC:
21719     // Set the condition code or opposite one if necessary.
21720     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21721     if (needOppositeCond)
21722       CC = X86::GetOppositeBranchCondition(CC);
21723     return SetCC.getOperand(1);
21724   case X86ISD::CMOV: {
21725     // Check whether false/true value has canonical one, i.e. 0 or 1.
21726     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21727     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21728     // Quit if true value is not a constant.
21729     if (!TVal)
21730       return SDValue();
21731     // Quit if false value is not a constant.
21732     if (!FVal) {
21733       SDValue Op = SetCC.getOperand(0);
21734       // Skip 'zext' or 'trunc' node.
21735       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21736           Op.getOpcode() == ISD::TRUNCATE)
21737         Op = Op.getOperand(0);
21738       // A special case for rdrand/rdseed, where 0 is set if false cond is
21739       // found.
21740       if ((Op.getOpcode() != X86ISD::RDRAND &&
21741            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21742         return SDValue();
21743     }
21744     // Quit if false value is not the constant 0 or 1.
21745     bool FValIsFalse = true;
21746     if (FVal && FVal->getZExtValue() != 0) {
21747       if (FVal->getZExtValue() != 1)
21748         return SDValue();
21749       // If FVal is 1, opposite cond is needed.
21750       needOppositeCond = !needOppositeCond;
21751       FValIsFalse = false;
21752     }
21753     // Quit if TVal is not the constant opposite of FVal.
21754     if (FValIsFalse && TVal->getZExtValue() != 1)
21755       return SDValue();
21756     if (!FValIsFalse && TVal->getZExtValue() != 0)
21757       return SDValue();
21758     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21759     if (needOppositeCond)
21760       CC = X86::GetOppositeBranchCondition(CC);
21761     return SetCC.getOperand(3);
21762   }
21763   }
21764
21765   return SDValue();
21766 }
21767
21768 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21769 /// Match:
21770 ///   (X86or (X86setcc) (X86setcc))
21771 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21772 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21773                                            X86::CondCode &CC1, SDValue &Flags,
21774                                            bool &isAnd) {
21775   if (Cond->getOpcode() == X86ISD::CMP) {
21776     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21777     if (!CondOp1C || !CondOp1C->isNullValue())
21778       return false;
21779
21780     Cond = Cond->getOperand(0);
21781   }
21782
21783   isAnd = false;
21784
21785   SDValue SetCC0, SetCC1;
21786   switch (Cond->getOpcode()) {
21787   default: return false;
21788   case ISD::AND:
21789   case X86ISD::AND:
21790     isAnd = true;
21791     // fallthru
21792   case ISD::OR:
21793   case X86ISD::OR:
21794     SetCC0 = Cond->getOperand(0);
21795     SetCC1 = Cond->getOperand(1);
21796     break;
21797   };
21798
21799   // Make sure we have SETCC nodes, using the same flags value.
21800   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21801       SetCC1.getOpcode() != X86ISD::SETCC ||
21802       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21803     return false;
21804
21805   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21806   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21807   Flags = SetCC0->getOperand(1);
21808   return true;
21809 }
21810
21811 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21812 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21813                                   TargetLowering::DAGCombinerInfo &DCI,
21814                                   const X86Subtarget *Subtarget) {
21815   SDLoc DL(N);
21816
21817   // If the flag operand isn't dead, don't touch this CMOV.
21818   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21819     return SDValue();
21820
21821   SDValue FalseOp = N->getOperand(0);
21822   SDValue TrueOp = N->getOperand(1);
21823   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21824   SDValue Cond = N->getOperand(3);
21825
21826   if (CC == X86::COND_E || CC == X86::COND_NE) {
21827     switch (Cond.getOpcode()) {
21828     default: break;
21829     case X86ISD::BSR:
21830     case X86ISD::BSF:
21831       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21832       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21833         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21834     }
21835   }
21836
21837   SDValue Flags;
21838
21839   Flags = checkBoolTestSetCCCombine(Cond, CC);
21840   if (Flags.getNode() &&
21841       // Extra check as FCMOV only supports a subset of X86 cond.
21842       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21843     SDValue Ops[] = { FalseOp, TrueOp,
21844                       DAG.getConstant(CC, DL, MVT::i8), Flags };
21845     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21846   }
21847
21848   // If this is a select between two integer constants, try to do some
21849   // optimizations.  Note that the operands are ordered the opposite of SELECT
21850   // operands.
21851   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21852     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21853       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21854       // larger than FalseC (the false value).
21855       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21856         CC = X86::GetOppositeBranchCondition(CC);
21857         std::swap(TrueC, FalseC);
21858         std::swap(TrueOp, FalseOp);
21859       }
21860
21861       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21862       // This is efficient for any integer data type (including i8/i16) and
21863       // shift amount.
21864       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21865         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21866                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21867
21868         // Zero extend the condition if needed.
21869         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21870
21871         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21872         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21873                            DAG.getConstant(ShAmt, DL, MVT::i8));
21874         if (N->getNumValues() == 2)  // Dead flag value?
21875           return DCI.CombineTo(N, Cond, SDValue());
21876         return Cond;
21877       }
21878
21879       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21880       // for any integer data type, including i8/i16.
21881       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21882         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21883                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21884
21885         // Zero extend the condition if needed.
21886         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21887                            FalseC->getValueType(0), Cond);
21888         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21889                            SDValue(FalseC, 0));
21890
21891         if (N->getNumValues() == 2)  // Dead flag value?
21892           return DCI.CombineTo(N, Cond, SDValue());
21893         return Cond;
21894       }
21895
21896       // Optimize cases that will turn into an LEA instruction.  This requires
21897       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21898       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21899         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21900         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21901
21902         bool isFastMultiplier = false;
21903         if (Diff < 10) {
21904           switch ((unsigned char)Diff) {
21905           default: break;
21906           case 1:  // result = add base, cond
21907           case 2:  // result = lea base(    , cond*2)
21908           case 3:  // result = lea base(cond, cond*2)
21909           case 4:  // result = lea base(    , cond*4)
21910           case 5:  // result = lea base(cond, cond*4)
21911           case 8:  // result = lea base(    , cond*8)
21912           case 9:  // result = lea base(cond, cond*8)
21913             isFastMultiplier = true;
21914             break;
21915           }
21916         }
21917
21918         if (isFastMultiplier) {
21919           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21920           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21921                              DAG.getConstant(CC, DL, MVT::i8), Cond);
21922           // Zero extend the condition if needed.
21923           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21924                              Cond);
21925           // Scale the condition by the difference.
21926           if (Diff != 1)
21927             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21928                                DAG.getConstant(Diff, DL, Cond.getValueType()));
21929
21930           // Add the base if non-zero.
21931           if (FalseC->getAPIntValue() != 0)
21932             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21933                                SDValue(FalseC, 0));
21934           if (N->getNumValues() == 2)  // Dead flag value?
21935             return DCI.CombineTo(N, Cond, SDValue());
21936           return Cond;
21937         }
21938       }
21939     }
21940   }
21941
21942   // Handle these cases:
21943   //   (select (x != c), e, c) -> select (x != c), e, x),
21944   //   (select (x == c), c, e) -> select (x == c), x, e)
21945   // where the c is an integer constant, and the "select" is the combination
21946   // of CMOV and CMP.
21947   //
21948   // The rationale for this change is that the conditional-move from a constant
21949   // needs two instructions, however, conditional-move from a register needs
21950   // only one instruction.
21951   //
21952   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21953   //  some instruction-combining opportunities. This opt needs to be
21954   //  postponed as late as possible.
21955   //
21956   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21957     // the DCI.xxxx conditions are provided to postpone the optimization as
21958     // late as possible.
21959
21960     ConstantSDNode *CmpAgainst = nullptr;
21961     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21962         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21963         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21964
21965       if (CC == X86::COND_NE &&
21966           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21967         CC = X86::GetOppositeBranchCondition(CC);
21968         std::swap(TrueOp, FalseOp);
21969       }
21970
21971       if (CC == X86::COND_E &&
21972           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21973         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21974                           DAG.getConstant(CC, DL, MVT::i8), Cond };
21975         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21976       }
21977     }
21978   }
21979
21980   // Fold and/or of setcc's to double CMOV:
21981   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21982   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21983   //
21984   // This combine lets us generate:
21985   //   cmovcc1 (jcc1 if we don't have CMOV)
21986   //   cmovcc2 (same)
21987   // instead of:
21988   //   setcc1
21989   //   setcc2
21990   //   and/or
21991   //   cmovne (jne if we don't have CMOV)
21992   // When we can't use the CMOV instruction, it might increase branch
21993   // mispredicts.
21994   // When we can use CMOV, or when there is no mispredict, this improves
21995   // throughput and reduces register pressure.
21996   //
21997   if (CC == X86::COND_NE) {
21998     SDValue Flags;
21999     X86::CondCode CC0, CC1;
22000     bool isAndSetCC;
22001     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22002       if (isAndSetCC) {
22003         std::swap(FalseOp, TrueOp);
22004         CC0 = X86::GetOppositeBranchCondition(CC0);
22005         CC1 = X86::GetOppositeBranchCondition(CC1);
22006       }
22007
22008       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22009         Flags};
22010       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22011       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22012       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22013       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22014       return CMOV;
22015     }
22016   }
22017
22018   return SDValue();
22019 }
22020
22021 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22022                                                 const X86Subtarget *Subtarget) {
22023   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22024   switch (IntNo) {
22025   default: return SDValue();
22026   // SSE/AVX/AVX2 blend intrinsics.
22027   case Intrinsic::x86_avx2_pblendvb:
22028     // Don't try to simplify this intrinsic if we don't have AVX2.
22029     if (!Subtarget->hasAVX2())
22030       return SDValue();
22031     // FALL-THROUGH
22032   case Intrinsic::x86_avx_blendv_pd_256:
22033   case Intrinsic::x86_avx_blendv_ps_256:
22034     // Don't try to simplify this intrinsic if we don't have AVX.
22035     if (!Subtarget->hasAVX())
22036       return SDValue();
22037     // FALL-THROUGH
22038   case Intrinsic::x86_sse41_blendvps:
22039   case Intrinsic::x86_sse41_blendvpd:
22040   case Intrinsic::x86_sse41_pblendvb: {
22041     SDValue Op0 = N->getOperand(1);
22042     SDValue Op1 = N->getOperand(2);
22043     SDValue Mask = N->getOperand(3);
22044
22045     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22046     if (!Subtarget->hasSSE41())
22047       return SDValue();
22048
22049     // fold (blend A, A, Mask) -> A
22050     if (Op0 == Op1)
22051       return Op0;
22052     // fold (blend A, B, allZeros) -> A
22053     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22054       return Op0;
22055     // fold (blend A, B, allOnes) -> B
22056     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22057       return Op1;
22058
22059     // Simplify the case where the mask is a constant i32 value.
22060     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22061       if (C->isNullValue())
22062         return Op0;
22063       if (C->isAllOnesValue())
22064         return Op1;
22065     }
22066
22067     return SDValue();
22068   }
22069
22070   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22071   case Intrinsic::x86_sse2_psrai_w:
22072   case Intrinsic::x86_sse2_psrai_d:
22073   case Intrinsic::x86_avx2_psrai_w:
22074   case Intrinsic::x86_avx2_psrai_d:
22075   case Intrinsic::x86_sse2_psra_w:
22076   case Intrinsic::x86_sse2_psra_d:
22077   case Intrinsic::x86_avx2_psra_w:
22078   case Intrinsic::x86_avx2_psra_d: {
22079     SDValue Op0 = N->getOperand(1);
22080     SDValue Op1 = N->getOperand(2);
22081     EVT VT = Op0.getValueType();
22082     assert(VT.isVector() && "Expected a vector type!");
22083
22084     if (isa<BuildVectorSDNode>(Op1))
22085       Op1 = Op1.getOperand(0);
22086
22087     if (!isa<ConstantSDNode>(Op1))
22088       return SDValue();
22089
22090     EVT SVT = VT.getVectorElementType();
22091     unsigned SVTBits = SVT.getSizeInBits();
22092
22093     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22094     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22095     uint64_t ShAmt = C.getZExtValue();
22096
22097     // Don't try to convert this shift into a ISD::SRA if the shift
22098     // count is bigger than or equal to the element size.
22099     if (ShAmt >= SVTBits)
22100       return SDValue();
22101
22102     // Trivial case: if the shift count is zero, then fold this
22103     // into the first operand.
22104     if (ShAmt == 0)
22105       return Op0;
22106
22107     // Replace this packed shift intrinsic with a target independent
22108     // shift dag node.
22109     SDLoc DL(N);
22110     SDValue Splat = DAG.getConstant(C, DL, VT);
22111     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22112   }
22113   }
22114 }
22115
22116 /// PerformMulCombine - Optimize a single multiply with constant into two
22117 /// in order to implement it with two cheaper instructions, e.g.
22118 /// LEA + SHL, LEA + LEA.
22119 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22120                                  TargetLowering::DAGCombinerInfo &DCI) {
22121   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22122     return SDValue();
22123
22124   EVT VT = N->getValueType(0);
22125   if (VT != MVT::i64 && VT != MVT::i32)
22126     return SDValue();
22127
22128   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22129   if (!C)
22130     return SDValue();
22131   uint64_t MulAmt = C->getZExtValue();
22132   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22133     return SDValue();
22134
22135   uint64_t MulAmt1 = 0;
22136   uint64_t MulAmt2 = 0;
22137   if ((MulAmt % 9) == 0) {
22138     MulAmt1 = 9;
22139     MulAmt2 = MulAmt / 9;
22140   } else if ((MulAmt % 5) == 0) {
22141     MulAmt1 = 5;
22142     MulAmt2 = MulAmt / 5;
22143   } else if ((MulAmt % 3) == 0) {
22144     MulAmt1 = 3;
22145     MulAmt2 = MulAmt / 3;
22146   }
22147   if (MulAmt2 &&
22148       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22149     SDLoc DL(N);
22150
22151     if (isPowerOf2_64(MulAmt2) &&
22152         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22153       // If second multiplifer is pow2, issue it first. We want the multiply by
22154       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22155       // is an add.
22156       std::swap(MulAmt1, MulAmt2);
22157
22158     SDValue NewMul;
22159     if (isPowerOf2_64(MulAmt1))
22160       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22161                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22162     else
22163       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22164                            DAG.getConstant(MulAmt1, DL, VT));
22165
22166     if (isPowerOf2_64(MulAmt2))
22167       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22168                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22169     else
22170       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22171                            DAG.getConstant(MulAmt2, DL, VT));
22172
22173     // Do not add new nodes to DAG combiner worklist.
22174     DCI.CombineTo(N, NewMul, false);
22175   }
22176   return SDValue();
22177 }
22178
22179 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22180   SDValue N0 = N->getOperand(0);
22181   SDValue N1 = N->getOperand(1);
22182   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22183   EVT VT = N0.getValueType();
22184
22185   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22186   // since the result of setcc_c is all zero's or all ones.
22187   if (VT.isInteger() && !VT.isVector() &&
22188       N1C && N0.getOpcode() == ISD::AND &&
22189       N0.getOperand(1).getOpcode() == ISD::Constant) {
22190     SDValue N00 = N0.getOperand(0);
22191     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22192         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22193           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22194          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22195       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22196       APInt ShAmt = N1C->getAPIntValue();
22197       Mask = Mask.shl(ShAmt);
22198       if (Mask != 0) {
22199         SDLoc DL(N);
22200         return DAG.getNode(ISD::AND, DL, VT,
22201                            N00, DAG.getConstant(Mask, DL, VT));
22202       }
22203     }
22204   }
22205
22206   // Hardware support for vector shifts is sparse which makes us scalarize the
22207   // vector operations in many cases. Also, on sandybridge ADD is faster than
22208   // shl.
22209   // (shl V, 1) -> add V,V
22210   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22211     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22212       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22213       // We shift all of the values by one. In many cases we do not have
22214       // hardware support for this operation. This is better expressed as an ADD
22215       // of two values.
22216       if (N1SplatC->getZExtValue() == 1)
22217         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22218     }
22219
22220   return SDValue();
22221 }
22222
22223 /// \brief Returns a vector of 0s if the node in input is a vector logical
22224 /// shift by a constant amount which is known to be bigger than or equal
22225 /// to the vector element size in bits.
22226 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22227                                       const X86Subtarget *Subtarget) {
22228   EVT VT = N->getValueType(0);
22229
22230   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22231       (!Subtarget->hasInt256() ||
22232        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22233     return SDValue();
22234
22235   SDValue Amt = N->getOperand(1);
22236   SDLoc DL(N);
22237   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22238     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22239       APInt ShiftAmt = AmtSplat->getAPIntValue();
22240       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22241
22242       // SSE2/AVX2 logical shifts always return a vector of 0s
22243       // if the shift amount is bigger than or equal to
22244       // the element size. The constant shift amount will be
22245       // encoded as a 8-bit immediate.
22246       if (ShiftAmt.trunc(8).uge(MaxAmount))
22247         return getZeroVector(VT, Subtarget, DAG, DL);
22248     }
22249
22250   return SDValue();
22251 }
22252
22253 /// PerformShiftCombine - Combine shifts.
22254 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22255                                    TargetLowering::DAGCombinerInfo &DCI,
22256                                    const X86Subtarget *Subtarget) {
22257   if (N->getOpcode() == ISD::SHL) {
22258     SDValue V = PerformSHLCombine(N, DAG);
22259     if (V.getNode()) return V;
22260   }
22261
22262   if (N->getOpcode() != ISD::SRA) {
22263     // Try to fold this logical shift into a zero vector.
22264     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22265     if (V.getNode()) return V;
22266   }
22267
22268   return SDValue();
22269 }
22270
22271 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22272 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22273 // and friends.  Likewise for OR -> CMPNEQSS.
22274 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22275                             TargetLowering::DAGCombinerInfo &DCI,
22276                             const X86Subtarget *Subtarget) {
22277   unsigned opcode;
22278
22279   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22280   // we're requiring SSE2 for both.
22281   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22282     SDValue N0 = N->getOperand(0);
22283     SDValue N1 = N->getOperand(1);
22284     SDValue CMP0 = N0->getOperand(1);
22285     SDValue CMP1 = N1->getOperand(1);
22286     SDLoc DL(N);
22287
22288     // The SETCCs should both refer to the same CMP.
22289     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22290       return SDValue();
22291
22292     SDValue CMP00 = CMP0->getOperand(0);
22293     SDValue CMP01 = CMP0->getOperand(1);
22294     EVT     VT    = CMP00.getValueType();
22295
22296     if (VT == MVT::f32 || VT == MVT::f64) {
22297       bool ExpectingFlags = false;
22298       // Check for any users that want flags:
22299       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22300            !ExpectingFlags && UI != UE; ++UI)
22301         switch (UI->getOpcode()) {
22302         default:
22303         case ISD::BR_CC:
22304         case ISD::BRCOND:
22305         case ISD::SELECT:
22306           ExpectingFlags = true;
22307           break;
22308         case ISD::CopyToReg:
22309         case ISD::SIGN_EXTEND:
22310         case ISD::ZERO_EXTEND:
22311         case ISD::ANY_EXTEND:
22312           break;
22313         }
22314
22315       if (!ExpectingFlags) {
22316         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22317         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22318
22319         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22320           X86::CondCode tmp = cc0;
22321           cc0 = cc1;
22322           cc1 = tmp;
22323         }
22324
22325         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22326             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22327           // FIXME: need symbolic constants for these magic numbers.
22328           // See X86ATTInstPrinter.cpp:printSSECC().
22329           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22330           if (Subtarget->hasAVX512()) {
22331             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22332                                          CMP01,
22333                                          DAG.getConstant(x86cc, DL, MVT::i8));
22334             if (N->getValueType(0) != MVT::i1)
22335               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22336                                  FSetCC);
22337             return FSetCC;
22338           }
22339           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22340                                               CMP00.getValueType(), CMP00, CMP01,
22341                                               DAG.getConstant(x86cc, DL,
22342                                                               MVT::i8));
22343
22344           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22345           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22346
22347           if (is64BitFP && !Subtarget->is64Bit()) {
22348             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22349             // 64-bit integer, since that's not a legal type. Since
22350             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22351             // bits, but can do this little dance to extract the lowest 32 bits
22352             // and work with those going forward.
22353             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22354                                            OnesOrZeroesF);
22355             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22356                                            Vector64);
22357             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22358                                         Vector32, DAG.getIntPtrConstant(0, DL));
22359             IntVT = MVT::i32;
22360           }
22361
22362           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22363                                               OnesOrZeroesF);
22364           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22365                                       DAG.getConstant(1, DL, IntVT));
22366           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22367                                               ANDed);
22368           return OneBitOfTruth;
22369         }
22370       }
22371     }
22372   }
22373   return SDValue();
22374 }
22375
22376 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22377 /// so it can be folded inside ANDNP.
22378 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22379   EVT VT = N->getValueType(0);
22380
22381   // Match direct AllOnes for 128 and 256-bit vectors
22382   if (ISD::isBuildVectorAllOnes(N))
22383     return true;
22384
22385   // Look through a bit convert.
22386   if (N->getOpcode() == ISD::BITCAST)
22387     N = N->getOperand(0).getNode();
22388
22389   // Sometimes the operand may come from a insert_subvector building a 256-bit
22390   // allones vector
22391   if (VT.is256BitVector() &&
22392       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22393     SDValue V1 = N->getOperand(0);
22394     SDValue V2 = N->getOperand(1);
22395
22396     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22397         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22398         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22399         ISD::isBuildVectorAllOnes(V2.getNode()))
22400       return true;
22401   }
22402
22403   return false;
22404 }
22405
22406 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22407 // register. In most cases we actually compare or select YMM-sized registers
22408 // and mixing the two types creates horrible code. This method optimizes
22409 // some of the transition sequences.
22410 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22411                                  TargetLowering::DAGCombinerInfo &DCI,
22412                                  const X86Subtarget *Subtarget) {
22413   EVT VT = N->getValueType(0);
22414   if (!VT.is256BitVector())
22415     return SDValue();
22416
22417   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22418           N->getOpcode() == ISD::ZERO_EXTEND ||
22419           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22420
22421   SDValue Narrow = N->getOperand(0);
22422   EVT NarrowVT = Narrow->getValueType(0);
22423   if (!NarrowVT.is128BitVector())
22424     return SDValue();
22425
22426   if (Narrow->getOpcode() != ISD::XOR &&
22427       Narrow->getOpcode() != ISD::AND &&
22428       Narrow->getOpcode() != ISD::OR)
22429     return SDValue();
22430
22431   SDValue N0  = Narrow->getOperand(0);
22432   SDValue N1  = Narrow->getOperand(1);
22433   SDLoc DL(Narrow);
22434
22435   // The Left side has to be a trunc.
22436   if (N0.getOpcode() != ISD::TRUNCATE)
22437     return SDValue();
22438
22439   // The type of the truncated inputs.
22440   EVT WideVT = N0->getOperand(0)->getValueType(0);
22441   if (WideVT != VT)
22442     return SDValue();
22443
22444   // The right side has to be a 'trunc' or a constant vector.
22445   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22446   ConstantSDNode *RHSConstSplat = nullptr;
22447   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22448     RHSConstSplat = RHSBV->getConstantSplatNode();
22449   if (!RHSTrunc && !RHSConstSplat)
22450     return SDValue();
22451
22452   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22453
22454   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22455     return SDValue();
22456
22457   // Set N0 and N1 to hold the inputs to the new wide operation.
22458   N0 = N0->getOperand(0);
22459   if (RHSConstSplat) {
22460     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22461                      SDValue(RHSConstSplat, 0));
22462     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22463     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22464   } else if (RHSTrunc) {
22465     N1 = N1->getOperand(0);
22466   }
22467
22468   // Generate the wide operation.
22469   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22470   unsigned Opcode = N->getOpcode();
22471   switch (Opcode) {
22472   case ISD::ANY_EXTEND:
22473     return Op;
22474   case ISD::ZERO_EXTEND: {
22475     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22476     APInt Mask = APInt::getAllOnesValue(InBits);
22477     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22478     return DAG.getNode(ISD::AND, DL, VT,
22479                        Op, DAG.getConstant(Mask, DL, VT));
22480   }
22481   case ISD::SIGN_EXTEND:
22482     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22483                        Op, DAG.getValueType(NarrowVT));
22484   default:
22485     llvm_unreachable("Unexpected opcode");
22486   }
22487 }
22488
22489 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22490                                  TargetLowering::DAGCombinerInfo &DCI,
22491                                  const X86Subtarget *Subtarget) {
22492   SDValue N0 = N->getOperand(0);
22493   SDValue N1 = N->getOperand(1);
22494   SDLoc DL(N);
22495
22496   // A vector zext_in_reg may be represented as a shuffle,
22497   // feeding into a bitcast (this represents anyext) feeding into
22498   // an and with a mask.
22499   // We'd like to try to combine that into a shuffle with zero
22500   // plus a bitcast, removing the and.
22501   if (N0.getOpcode() != ISD::BITCAST ||
22502       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22503     return SDValue();
22504
22505   // The other side of the AND should be a splat of 2^C, where C
22506   // is the number of bits in the source type.
22507   if (N1.getOpcode() == ISD::BITCAST)
22508     N1 = N1.getOperand(0);
22509   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22510     return SDValue();
22511   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22512
22513   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22514   EVT SrcType = Shuffle->getValueType(0);
22515
22516   // We expect a single-source shuffle
22517   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22518     return SDValue();
22519
22520   unsigned SrcSize = SrcType.getScalarSizeInBits();
22521
22522   APInt SplatValue, SplatUndef;
22523   unsigned SplatBitSize;
22524   bool HasAnyUndefs;
22525   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22526                                 SplatBitSize, HasAnyUndefs))
22527     return SDValue();
22528
22529   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22530   // Make sure the splat matches the mask we expect
22531   if (SplatBitSize > ResSize ||
22532       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22533     return SDValue();
22534
22535   // Make sure the input and output size make sense
22536   if (SrcSize >= ResSize || ResSize % SrcSize)
22537     return SDValue();
22538
22539   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22540   // The number of u's between each two values depends on the ratio between
22541   // the source and dest type.
22542   unsigned ZextRatio = ResSize / SrcSize;
22543   bool IsZext = true;
22544   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22545     if (i % ZextRatio) {
22546       if (Shuffle->getMaskElt(i) > 0) {
22547         // Expected undef
22548         IsZext = false;
22549         break;
22550       }
22551     } else {
22552       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22553         // Expected element number
22554         IsZext = false;
22555         break;
22556       }
22557     }
22558   }
22559
22560   if (!IsZext)
22561     return SDValue();
22562
22563   // Ok, perform the transformation - replace the shuffle with
22564   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22565   // (instead of undef) where the k elements come from the zero vector.
22566   SmallVector<int, 8> Mask;
22567   unsigned NumElems = SrcType.getVectorNumElements();
22568   for (unsigned i = 0; i < NumElems; ++i)
22569     if (i % ZextRatio)
22570       Mask.push_back(NumElems);
22571     else
22572       Mask.push_back(i / ZextRatio);
22573
22574   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22575     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22576   return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22577 }
22578
22579 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22580                                  TargetLowering::DAGCombinerInfo &DCI,
22581                                  const X86Subtarget *Subtarget) {
22582   if (DCI.isBeforeLegalizeOps())
22583     return SDValue();
22584
22585   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22586     return Zext;
22587
22588   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22589     return R;
22590
22591   EVT VT = N->getValueType(0);
22592   SDValue N0 = N->getOperand(0);
22593   SDValue N1 = N->getOperand(1);
22594   SDLoc DL(N);
22595
22596   // Create BEXTR instructions
22597   // BEXTR is ((X >> imm) & (2**size-1))
22598   if (VT == MVT::i32 || VT == MVT::i64) {
22599     // Check for BEXTR.
22600     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22601         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22602       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22603       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22604       if (MaskNode && ShiftNode) {
22605         uint64_t Mask = MaskNode->getZExtValue();
22606         uint64_t Shift = ShiftNode->getZExtValue();
22607         if (isMask_64(Mask)) {
22608           uint64_t MaskSize = countPopulation(Mask);
22609           if (Shift + MaskSize <= VT.getSizeInBits())
22610             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22611                                DAG.getConstant(Shift | (MaskSize << 8), DL,
22612                                                VT));
22613         }
22614       }
22615     } // BEXTR
22616
22617     return SDValue();
22618   }
22619
22620   // Want to form ANDNP nodes:
22621   // 1) In the hopes of then easily combining them with OR and AND nodes
22622   //    to form PBLEND/PSIGN.
22623   // 2) To match ANDN packed intrinsics
22624   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22625     return SDValue();
22626
22627   // Check LHS for vnot
22628   if (N0.getOpcode() == ISD::XOR &&
22629       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22630       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22631     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22632
22633   // Check RHS for vnot
22634   if (N1.getOpcode() == ISD::XOR &&
22635       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22636       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22637     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22638
22639   return SDValue();
22640 }
22641
22642 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22643                                 TargetLowering::DAGCombinerInfo &DCI,
22644                                 const X86Subtarget *Subtarget) {
22645   if (DCI.isBeforeLegalizeOps())
22646     return SDValue();
22647
22648   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22649   if (R.getNode())
22650     return R;
22651
22652   SDValue N0 = N->getOperand(0);
22653   SDValue N1 = N->getOperand(1);
22654   EVT VT = N->getValueType(0);
22655
22656   // look for psign/blend
22657   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22658     if (!Subtarget->hasSSSE3() ||
22659         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22660       return SDValue();
22661
22662     // Canonicalize pandn to RHS
22663     if (N0.getOpcode() == X86ISD::ANDNP)
22664       std::swap(N0, N1);
22665     // or (and (m, y), (pandn m, x))
22666     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22667       SDValue Mask = N1.getOperand(0);
22668       SDValue X    = N1.getOperand(1);
22669       SDValue Y;
22670       if (N0.getOperand(0) == Mask)
22671         Y = N0.getOperand(1);
22672       if (N0.getOperand(1) == Mask)
22673         Y = N0.getOperand(0);
22674
22675       // Check to see if the mask appeared in both the AND and ANDNP and
22676       if (!Y.getNode())
22677         return SDValue();
22678
22679       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22680       // Look through mask bitcast.
22681       if (Mask.getOpcode() == ISD::BITCAST)
22682         Mask = Mask.getOperand(0);
22683       if (X.getOpcode() == ISD::BITCAST)
22684         X = X.getOperand(0);
22685       if (Y.getOpcode() == ISD::BITCAST)
22686         Y = Y.getOperand(0);
22687
22688       EVT MaskVT = Mask.getValueType();
22689
22690       // Validate that the Mask operand is a vector sra node.
22691       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22692       // there is no psrai.b
22693       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22694       unsigned SraAmt = ~0;
22695       if (Mask.getOpcode() == ISD::SRA) {
22696         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22697           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22698             SraAmt = AmtConst->getZExtValue();
22699       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22700         SDValue SraC = Mask.getOperand(1);
22701         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22702       }
22703       if ((SraAmt + 1) != EltBits)
22704         return SDValue();
22705
22706       SDLoc DL(N);
22707
22708       // Now we know we at least have a plendvb with the mask val.  See if
22709       // we can form a psignb/w/d.
22710       // psign = x.type == y.type == mask.type && y = sub(0, x);
22711       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22712           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22713           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22714         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22715                "Unsupported VT for PSIGN");
22716         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22717         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22718       }
22719       // PBLENDVB only available on SSE 4.1
22720       if (!Subtarget->hasSSE41())
22721         return SDValue();
22722
22723       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22724
22725       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22726       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22727       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22728       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22729       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22730     }
22731   }
22732
22733   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22734     return SDValue();
22735
22736   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22737   MachineFunction &MF = DAG.getMachineFunction();
22738   bool OptForSize =
22739       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22740
22741   // SHLD/SHRD instructions have lower register pressure, but on some
22742   // platforms they have higher latency than the equivalent
22743   // series of shifts/or that would otherwise be generated.
22744   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22745   // have higher latencies and we are not optimizing for size.
22746   if (!OptForSize && Subtarget->isSHLDSlow())
22747     return SDValue();
22748
22749   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22750     std::swap(N0, N1);
22751   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22752     return SDValue();
22753   if (!N0.hasOneUse() || !N1.hasOneUse())
22754     return SDValue();
22755
22756   SDValue ShAmt0 = N0.getOperand(1);
22757   if (ShAmt0.getValueType() != MVT::i8)
22758     return SDValue();
22759   SDValue ShAmt1 = N1.getOperand(1);
22760   if (ShAmt1.getValueType() != MVT::i8)
22761     return SDValue();
22762   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22763     ShAmt0 = ShAmt0.getOperand(0);
22764   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22765     ShAmt1 = ShAmt1.getOperand(0);
22766
22767   SDLoc DL(N);
22768   unsigned Opc = X86ISD::SHLD;
22769   SDValue Op0 = N0.getOperand(0);
22770   SDValue Op1 = N1.getOperand(0);
22771   if (ShAmt0.getOpcode() == ISD::SUB) {
22772     Opc = X86ISD::SHRD;
22773     std::swap(Op0, Op1);
22774     std::swap(ShAmt0, ShAmt1);
22775   }
22776
22777   unsigned Bits = VT.getSizeInBits();
22778   if (ShAmt1.getOpcode() == ISD::SUB) {
22779     SDValue Sum = ShAmt1.getOperand(0);
22780     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22781       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22782       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22783         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22784       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22785         return DAG.getNode(Opc, DL, VT,
22786                            Op0, Op1,
22787                            DAG.getNode(ISD::TRUNCATE, DL,
22788                                        MVT::i8, ShAmt0));
22789     }
22790   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22791     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22792     if (ShAmt0C &&
22793         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22794       return DAG.getNode(Opc, DL, VT,
22795                          N0.getOperand(0), N1.getOperand(0),
22796                          DAG.getNode(ISD::TRUNCATE, DL,
22797                                        MVT::i8, ShAmt0));
22798   }
22799
22800   return SDValue();
22801 }
22802
22803 // Generate NEG and CMOV for integer abs.
22804 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22805   EVT VT = N->getValueType(0);
22806
22807   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22808   // 8-bit integer abs to NEG and CMOV.
22809   if (VT.isInteger() && VT.getSizeInBits() == 8)
22810     return SDValue();
22811
22812   SDValue N0 = N->getOperand(0);
22813   SDValue N1 = N->getOperand(1);
22814   SDLoc DL(N);
22815
22816   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22817   // and change it to SUB and CMOV.
22818   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22819       N0.getOpcode() == ISD::ADD &&
22820       N0.getOperand(1) == N1 &&
22821       N1.getOpcode() == ISD::SRA &&
22822       N1.getOperand(0) == N0.getOperand(0))
22823     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22824       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22825         // Generate SUB & CMOV.
22826         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22827                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
22828
22829         SDValue Ops[] = { N0.getOperand(0), Neg,
22830                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22831                           SDValue(Neg.getNode(), 1) };
22832         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22833       }
22834   return SDValue();
22835 }
22836
22837 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22838 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22839                                  TargetLowering::DAGCombinerInfo &DCI,
22840                                  const X86Subtarget *Subtarget) {
22841   if (DCI.isBeforeLegalizeOps())
22842     return SDValue();
22843
22844   if (Subtarget->hasCMov()) {
22845     SDValue RV = performIntegerAbsCombine(N, DAG);
22846     if (RV.getNode())
22847       return RV;
22848   }
22849
22850   return SDValue();
22851 }
22852
22853 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22854 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22855                                   TargetLowering::DAGCombinerInfo &DCI,
22856                                   const X86Subtarget *Subtarget) {
22857   LoadSDNode *Ld = cast<LoadSDNode>(N);
22858   EVT RegVT = Ld->getValueType(0);
22859   EVT MemVT = Ld->getMemoryVT();
22860   SDLoc dl(Ld);
22861   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22862
22863   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22864   // into two 16-byte operations.
22865   ISD::LoadExtType Ext = Ld->getExtensionType();
22866   unsigned Alignment = Ld->getAlignment();
22867   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22868   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22869       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22870     unsigned NumElems = RegVT.getVectorNumElements();
22871     if (NumElems < 2)
22872       return SDValue();
22873
22874     SDValue Ptr = Ld->getBasePtr();
22875     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
22876
22877     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22878                                   NumElems/2);
22879     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22880                                 Ld->getPointerInfo(), Ld->isVolatile(),
22881                                 Ld->isNonTemporal(), Ld->isInvariant(),
22882                                 Alignment);
22883     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22884     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22885                                 Ld->getPointerInfo(), Ld->isVolatile(),
22886                                 Ld->isNonTemporal(), Ld->isInvariant(),
22887                                 std::min(16U, Alignment));
22888     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22889                              Load1.getValue(1),
22890                              Load2.getValue(1));
22891
22892     SDValue NewVec = DAG.getUNDEF(RegVT);
22893     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22894     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22895     return DCI.CombineTo(N, NewVec, TF, true);
22896   }
22897
22898   return SDValue();
22899 }
22900
22901 /// PerformMLOADCombine - Resolve extending loads
22902 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22903                                    TargetLowering::DAGCombinerInfo &DCI,
22904                                    const X86Subtarget *Subtarget) {
22905   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22906   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22907     return SDValue();
22908
22909   EVT VT = Mld->getValueType(0);
22910   unsigned NumElems = VT.getVectorNumElements();
22911   EVT LdVT = Mld->getMemoryVT();
22912   SDLoc dl(Mld);
22913
22914   assert(LdVT != VT && "Cannot extend to the same type");
22915   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22916   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22917   // From, To sizes and ElemCount must be pow of two
22918   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22919     "Unexpected size for extending masked load");
22920
22921   unsigned SizeRatio  = ToSz / FromSz;
22922   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22923
22924   // Create a type on which we perform the shuffle
22925   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22926           LdVT.getScalarType(), NumElems*SizeRatio);
22927   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22928
22929   // Convert Src0 value
22930   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22931   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22932     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22933     for (unsigned i = 0; i != NumElems; ++i)
22934       ShuffleVec[i] = i * SizeRatio;
22935
22936     // Can't shuffle using an illegal type.
22937     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22938             && "WideVecVT should be legal");
22939     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22940                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22941   }
22942   // Prepare the new mask
22943   SDValue NewMask;
22944   SDValue Mask = Mld->getMask();
22945   if (Mask.getValueType() == VT) {
22946     // Mask and original value have the same type
22947     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22948     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22949     for (unsigned i = 0; i != NumElems; ++i)
22950       ShuffleVec[i] = i * SizeRatio;
22951     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22952       ShuffleVec[i] = NumElems*SizeRatio;
22953     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22954                                    DAG.getConstant(0, dl, WideVecVT),
22955                                    &ShuffleVec[0]);
22956   }
22957   else {
22958     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22959     unsigned WidenNumElts = NumElems*SizeRatio;
22960     unsigned MaskNumElts = VT.getVectorNumElements();
22961     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22962                                      WidenNumElts);
22963
22964     unsigned NumConcat = WidenNumElts / MaskNumElts;
22965     SmallVector<SDValue, 16> Ops(NumConcat);
22966     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
22967     Ops[0] = Mask;
22968     for (unsigned i = 1; i != NumConcat; ++i)
22969       Ops[i] = ZeroVal;
22970
22971     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22972   }
22973
22974   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22975                                      Mld->getBasePtr(), NewMask, WideSrc0,
22976                                      Mld->getMemoryVT(), Mld->getMemOperand(),
22977                                      ISD::NON_EXTLOAD);
22978   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22979   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22980
22981 }
22982 /// PerformMSTORECombine - Resolve truncating stores
22983 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22984                                     const X86Subtarget *Subtarget) {
22985   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22986   if (!Mst->isTruncatingStore())
22987     return SDValue();
22988
22989   EVT VT = Mst->getValue().getValueType();
22990   unsigned NumElems = VT.getVectorNumElements();
22991   EVT StVT = Mst->getMemoryVT();
22992   SDLoc dl(Mst);
22993
22994   assert(StVT != VT && "Cannot truncate to the same type");
22995   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22996   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22997
22998   // From, To sizes and ElemCount must be pow of two
22999   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23000     "Unexpected size for truncating masked store");
23001   // We are going to use the original vector elt for storing.
23002   // Accumulated smaller vector elements must be a multiple of the store size.
23003   assert (((NumElems * FromSz) % ToSz) == 0 &&
23004           "Unexpected ratio for truncating masked store");
23005
23006   unsigned SizeRatio  = FromSz / ToSz;
23007   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23008
23009   // Create a type on which we perform the shuffle
23010   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23011           StVT.getScalarType(), NumElems*SizeRatio);
23012
23013   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23014
23015   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23016   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23017   for (unsigned i = 0; i != NumElems; ++i)
23018     ShuffleVec[i] = i * SizeRatio;
23019
23020   // Can't shuffle using an illegal type.
23021   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23022           && "WideVecVT should be legal");
23023
23024   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23025                                         DAG.getUNDEF(WideVecVT),
23026                                         &ShuffleVec[0]);
23027
23028   SDValue NewMask;
23029   SDValue Mask = Mst->getMask();
23030   if (Mask.getValueType() == VT) {
23031     // Mask and original value have the same type
23032     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23033     for (unsigned i = 0; i != NumElems; ++i)
23034       ShuffleVec[i] = i * SizeRatio;
23035     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23036       ShuffleVec[i] = NumElems*SizeRatio;
23037     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23038                                    DAG.getConstant(0, dl, WideVecVT),
23039                                    &ShuffleVec[0]);
23040   }
23041   else {
23042     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23043     unsigned WidenNumElts = NumElems*SizeRatio;
23044     unsigned MaskNumElts = VT.getVectorNumElements();
23045     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23046                                      WidenNumElts);
23047
23048     unsigned NumConcat = WidenNumElts / MaskNumElts;
23049     SmallVector<SDValue, 16> Ops(NumConcat);
23050     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23051     Ops[0] = Mask;
23052     for (unsigned i = 1; i != NumConcat; ++i)
23053       Ops[i] = ZeroVal;
23054
23055     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23056   }
23057
23058   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23059                             NewMask, StVT, Mst->getMemOperand(), false);
23060 }
23061 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23062 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23063                                    const X86Subtarget *Subtarget) {
23064   StoreSDNode *St = cast<StoreSDNode>(N);
23065   EVT VT = St->getValue().getValueType();
23066   EVT StVT = St->getMemoryVT();
23067   SDLoc dl(St);
23068   SDValue StoredVal = St->getOperand(1);
23069   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23070
23071   // If we are saving a concatenation of two XMM registers and 32-byte stores
23072   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23073   unsigned Alignment = St->getAlignment();
23074   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23075   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23076       StVT == VT && !IsAligned) {
23077     unsigned NumElems = VT.getVectorNumElements();
23078     if (NumElems < 2)
23079       return SDValue();
23080
23081     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23082     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23083
23084     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23085     SDValue Ptr0 = St->getBasePtr();
23086     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23087
23088     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23089                                 St->getPointerInfo(), St->isVolatile(),
23090                                 St->isNonTemporal(), Alignment);
23091     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23092                                 St->getPointerInfo(), St->isVolatile(),
23093                                 St->isNonTemporal(),
23094                                 std::min(16U, Alignment));
23095     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23096   }
23097
23098   // Optimize trunc store (of multiple scalars) to shuffle and store.
23099   // First, pack all of the elements in one place. Next, store to memory
23100   // in fewer chunks.
23101   if (St->isTruncatingStore() && VT.isVector()) {
23102     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23103     unsigned NumElems = VT.getVectorNumElements();
23104     assert(StVT != VT && "Cannot truncate to the same type");
23105     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23106     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23107
23108     // From, To sizes and ElemCount must be pow of two
23109     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23110     // We are going to use the original vector elt for storing.
23111     // Accumulated smaller vector elements must be a multiple of the store size.
23112     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23113
23114     unsigned SizeRatio  = FromSz / ToSz;
23115
23116     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23117
23118     // Create a type on which we perform the shuffle
23119     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23120             StVT.getScalarType(), NumElems*SizeRatio);
23121
23122     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23123
23124     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23125     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23126     for (unsigned i = 0; i != NumElems; ++i)
23127       ShuffleVec[i] = i * SizeRatio;
23128
23129     // Can't shuffle using an illegal type.
23130     if (!TLI.isTypeLegal(WideVecVT))
23131       return SDValue();
23132
23133     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23134                                          DAG.getUNDEF(WideVecVT),
23135                                          &ShuffleVec[0]);
23136     // At this point all of the data is stored at the bottom of the
23137     // register. We now need to save it to mem.
23138
23139     // Find the largest store unit
23140     MVT StoreType = MVT::i8;
23141     for (MVT Tp : MVT::integer_valuetypes()) {
23142       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23143         StoreType = Tp;
23144     }
23145
23146     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23147     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23148         (64 <= NumElems * ToSz))
23149       StoreType = MVT::f64;
23150
23151     // Bitcast the original vector into a vector of store-size units
23152     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23153             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23154     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23155     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23156     SmallVector<SDValue, 8> Chains;
23157     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23158                                         TLI.getPointerTy());
23159     SDValue Ptr = St->getBasePtr();
23160
23161     // Perform one or more big stores into memory.
23162     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23163       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23164                                    StoreType, ShuffWide,
23165                                    DAG.getIntPtrConstant(i, dl));
23166       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23167                                 St->getPointerInfo(), St->isVolatile(),
23168                                 St->isNonTemporal(), St->getAlignment());
23169       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23170       Chains.push_back(Ch);
23171     }
23172
23173     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23174   }
23175
23176   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23177   // the FP state in cases where an emms may be missing.
23178   // A preferable solution to the general problem is to figure out the right
23179   // places to insert EMMS.  This qualifies as a quick hack.
23180
23181   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23182   if (VT.getSizeInBits() != 64)
23183     return SDValue();
23184
23185   const Function *F = DAG.getMachineFunction().getFunction();
23186   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23187   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
23188                      && Subtarget->hasSSE2();
23189   if ((VT.isVector() ||
23190        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23191       isa<LoadSDNode>(St->getValue()) &&
23192       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23193       St->getChain().hasOneUse() && !St->isVolatile()) {
23194     SDNode* LdVal = St->getValue().getNode();
23195     LoadSDNode *Ld = nullptr;
23196     int TokenFactorIndex = -1;
23197     SmallVector<SDValue, 8> Ops;
23198     SDNode* ChainVal = St->getChain().getNode();
23199     // Must be a store of a load.  We currently handle two cases:  the load
23200     // is a direct child, and it's under an intervening TokenFactor.  It is
23201     // possible to dig deeper under nested TokenFactors.
23202     if (ChainVal == LdVal)
23203       Ld = cast<LoadSDNode>(St->getChain());
23204     else if (St->getValue().hasOneUse() &&
23205              ChainVal->getOpcode() == ISD::TokenFactor) {
23206       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23207         if (ChainVal->getOperand(i).getNode() == LdVal) {
23208           TokenFactorIndex = i;
23209           Ld = cast<LoadSDNode>(St->getValue());
23210         } else
23211           Ops.push_back(ChainVal->getOperand(i));
23212       }
23213     }
23214
23215     if (!Ld || !ISD::isNormalLoad(Ld))
23216       return SDValue();
23217
23218     // If this is not the MMX case, i.e. we are just turning i64 load/store
23219     // into f64 load/store, avoid the transformation if there are multiple
23220     // uses of the loaded value.
23221     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23222       return SDValue();
23223
23224     SDLoc LdDL(Ld);
23225     SDLoc StDL(N);
23226     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23227     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23228     // pair instead.
23229     if (Subtarget->is64Bit() || F64IsLegal) {
23230       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23231       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23232                                   Ld->getPointerInfo(), Ld->isVolatile(),
23233                                   Ld->isNonTemporal(), Ld->isInvariant(),
23234                                   Ld->getAlignment());
23235       SDValue NewChain = NewLd.getValue(1);
23236       if (TokenFactorIndex != -1) {
23237         Ops.push_back(NewChain);
23238         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23239       }
23240       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23241                           St->getPointerInfo(),
23242                           St->isVolatile(), St->isNonTemporal(),
23243                           St->getAlignment());
23244     }
23245
23246     // Otherwise, lower to two pairs of 32-bit loads / stores.
23247     SDValue LoAddr = Ld->getBasePtr();
23248     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23249                                  DAG.getConstant(4, LdDL, MVT::i32));
23250
23251     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23252                                Ld->getPointerInfo(),
23253                                Ld->isVolatile(), Ld->isNonTemporal(),
23254                                Ld->isInvariant(), Ld->getAlignment());
23255     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23256                                Ld->getPointerInfo().getWithOffset(4),
23257                                Ld->isVolatile(), Ld->isNonTemporal(),
23258                                Ld->isInvariant(),
23259                                MinAlign(Ld->getAlignment(), 4));
23260
23261     SDValue NewChain = LoLd.getValue(1);
23262     if (TokenFactorIndex != -1) {
23263       Ops.push_back(LoLd);
23264       Ops.push_back(HiLd);
23265       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23266     }
23267
23268     LoAddr = St->getBasePtr();
23269     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23270                          DAG.getConstant(4, StDL, MVT::i32));
23271
23272     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23273                                 St->getPointerInfo(),
23274                                 St->isVolatile(), St->isNonTemporal(),
23275                                 St->getAlignment());
23276     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23277                                 St->getPointerInfo().getWithOffset(4),
23278                                 St->isVolatile(),
23279                                 St->isNonTemporal(),
23280                                 MinAlign(St->getAlignment(), 4));
23281     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23282   }
23283
23284   // This is similar to the above case, but here we handle a scalar 64-bit
23285   // integer store that is extracted from a vector on a 32-bit target.
23286   // If we have SSE2, then we can treat it like a floating-point double
23287   // to get past legalization. The execution dependencies fixup pass will
23288   // choose the optimal machine instruction for the store if this really is
23289   // an integer or v2f32 rather than an f64.
23290   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23291       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23292     SDValue OldExtract = St->getOperand(1);
23293     SDValue ExtOp0 = OldExtract.getOperand(0);
23294     unsigned VecSize = ExtOp0.getValueSizeInBits();
23295     MVT VecVT = MVT::getVectorVT(MVT::f64, VecSize / 64);
23296     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23297     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23298                                      BitCast, OldExtract.getOperand(1));
23299     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23300                         St->getPointerInfo(), St->isVolatile(),
23301                         St->isNonTemporal(), St->getAlignment());
23302   }
23303
23304   return SDValue();
23305 }
23306
23307 /// Return 'true' if this vector operation is "horizontal"
23308 /// and return the operands for the horizontal operation in LHS and RHS.  A
23309 /// horizontal operation performs the binary operation on successive elements
23310 /// of its first operand, then on successive elements of its second operand,
23311 /// returning the resulting values in a vector.  For example, if
23312 ///   A = < float a0, float a1, float a2, float a3 >
23313 /// and
23314 ///   B = < float b0, float b1, float b2, float b3 >
23315 /// then the result of doing a horizontal operation on A and B is
23316 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23317 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23318 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23319 /// set to A, RHS to B, and the routine returns 'true'.
23320 /// Note that the binary operation should have the property that if one of the
23321 /// operands is UNDEF then the result is UNDEF.
23322 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23323   // Look for the following pattern: if
23324   //   A = < float a0, float a1, float a2, float a3 >
23325   //   B = < float b0, float b1, float b2, float b3 >
23326   // and
23327   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23328   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23329   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23330   // which is A horizontal-op B.
23331
23332   // At least one of the operands should be a vector shuffle.
23333   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23334       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23335     return false;
23336
23337   MVT VT = LHS.getSimpleValueType();
23338
23339   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23340          "Unsupported vector type for horizontal add/sub");
23341
23342   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23343   // operate independently on 128-bit lanes.
23344   unsigned NumElts = VT.getVectorNumElements();
23345   unsigned NumLanes = VT.getSizeInBits()/128;
23346   unsigned NumLaneElts = NumElts / NumLanes;
23347   assert((NumLaneElts % 2 == 0) &&
23348          "Vector type should have an even number of elements in each lane");
23349   unsigned HalfLaneElts = NumLaneElts/2;
23350
23351   // View LHS in the form
23352   //   LHS = VECTOR_SHUFFLE A, B, LMask
23353   // If LHS is not a shuffle then pretend it is the shuffle
23354   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23355   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23356   // type VT.
23357   SDValue A, B;
23358   SmallVector<int, 16> LMask(NumElts);
23359   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23360     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23361       A = LHS.getOperand(0);
23362     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23363       B = LHS.getOperand(1);
23364     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23365     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23366   } else {
23367     if (LHS.getOpcode() != ISD::UNDEF)
23368       A = LHS;
23369     for (unsigned i = 0; i != NumElts; ++i)
23370       LMask[i] = i;
23371   }
23372
23373   // Likewise, view RHS in the form
23374   //   RHS = VECTOR_SHUFFLE C, D, RMask
23375   SDValue C, D;
23376   SmallVector<int, 16> RMask(NumElts);
23377   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23378     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23379       C = RHS.getOperand(0);
23380     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23381       D = RHS.getOperand(1);
23382     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23383     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23384   } else {
23385     if (RHS.getOpcode() != ISD::UNDEF)
23386       C = RHS;
23387     for (unsigned i = 0; i != NumElts; ++i)
23388       RMask[i] = i;
23389   }
23390
23391   // Check that the shuffles are both shuffling the same vectors.
23392   if (!(A == C && B == D) && !(A == D && B == C))
23393     return false;
23394
23395   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23396   if (!A.getNode() && !B.getNode())
23397     return false;
23398
23399   // If A and B occur in reverse order in RHS, then "swap" them (which means
23400   // rewriting the mask).
23401   if (A != C)
23402     ShuffleVectorSDNode::commuteMask(RMask);
23403
23404   // At this point LHS and RHS are equivalent to
23405   //   LHS = VECTOR_SHUFFLE A, B, LMask
23406   //   RHS = VECTOR_SHUFFLE A, B, RMask
23407   // Check that the masks correspond to performing a horizontal operation.
23408   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23409     for (unsigned i = 0; i != NumLaneElts; ++i) {
23410       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23411
23412       // Ignore any UNDEF components.
23413       if (LIdx < 0 || RIdx < 0 ||
23414           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23415           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23416         continue;
23417
23418       // Check that successive elements are being operated on.  If not, this is
23419       // not a horizontal operation.
23420       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23421       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23422       if (!(LIdx == Index && RIdx == Index + 1) &&
23423           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23424         return false;
23425     }
23426   }
23427
23428   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23429   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23430   return true;
23431 }
23432
23433 /// Do target-specific dag combines on floating point adds.
23434 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23435                                   const X86Subtarget *Subtarget) {
23436   EVT VT = N->getValueType(0);
23437   SDValue LHS = N->getOperand(0);
23438   SDValue RHS = N->getOperand(1);
23439
23440   // Try to synthesize horizontal adds from adds of shuffles.
23441   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23442        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23443       isHorizontalBinOp(LHS, RHS, true))
23444     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23445   return SDValue();
23446 }
23447
23448 /// Do target-specific dag combines on floating point subs.
23449 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23450                                   const X86Subtarget *Subtarget) {
23451   EVT VT = N->getValueType(0);
23452   SDValue LHS = N->getOperand(0);
23453   SDValue RHS = N->getOperand(1);
23454
23455   // Try to synthesize horizontal subs from subs of shuffles.
23456   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23457        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23458       isHorizontalBinOp(LHS, RHS, false))
23459     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23460   return SDValue();
23461 }
23462
23463 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23464 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23465   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23466
23467   // F[X]OR(0.0, x) -> x
23468   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23469     if (C->getValueAPF().isPosZero())
23470       return N->getOperand(1);
23471
23472   // F[X]OR(x, 0.0) -> x
23473   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23474     if (C->getValueAPF().isPosZero())
23475       return N->getOperand(0);
23476   return SDValue();
23477 }
23478
23479 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23480 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23481   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23482
23483   // Only perform optimizations if UnsafeMath is used.
23484   if (!DAG.getTarget().Options.UnsafeFPMath)
23485     return SDValue();
23486
23487   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23488   // into FMINC and FMAXC, which are Commutative operations.
23489   unsigned NewOp = 0;
23490   switch (N->getOpcode()) {
23491     default: llvm_unreachable("unknown opcode");
23492     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23493     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23494   }
23495
23496   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23497                      N->getOperand(0), N->getOperand(1));
23498 }
23499
23500 /// Do target-specific dag combines on X86ISD::FAND nodes.
23501 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23502   // FAND(0.0, x) -> 0.0
23503   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23504     if (C->getValueAPF().isPosZero())
23505       return N->getOperand(0);
23506
23507   // FAND(x, 0.0) -> 0.0
23508   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23509     if (C->getValueAPF().isPosZero())
23510       return N->getOperand(1);
23511
23512   return SDValue();
23513 }
23514
23515 /// Do target-specific dag combines on X86ISD::FANDN nodes
23516 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23517   // FANDN(0.0, x) -> x
23518   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23519     if (C->getValueAPF().isPosZero())
23520       return N->getOperand(1);
23521
23522   // FANDN(x, 0.0) -> 0.0
23523   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23524     if (C->getValueAPF().isPosZero())
23525       return N->getOperand(1);
23526
23527   return SDValue();
23528 }
23529
23530 static SDValue PerformBTCombine(SDNode *N,
23531                                 SelectionDAG &DAG,
23532                                 TargetLowering::DAGCombinerInfo &DCI) {
23533   // BT ignores high bits in the bit index operand.
23534   SDValue Op1 = N->getOperand(1);
23535   if (Op1.hasOneUse()) {
23536     unsigned BitWidth = Op1.getValueSizeInBits();
23537     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23538     APInt KnownZero, KnownOne;
23539     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23540                                           !DCI.isBeforeLegalizeOps());
23541     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23542     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23543         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23544       DCI.CommitTargetLoweringOpt(TLO);
23545   }
23546   return SDValue();
23547 }
23548
23549 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23550   SDValue Op = N->getOperand(0);
23551   if (Op.getOpcode() == ISD::BITCAST)
23552     Op = Op.getOperand(0);
23553   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23554   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23555       VT.getVectorElementType().getSizeInBits() ==
23556       OpVT.getVectorElementType().getSizeInBits()) {
23557     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23558   }
23559   return SDValue();
23560 }
23561
23562 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23563                                                const X86Subtarget *Subtarget) {
23564   EVT VT = N->getValueType(0);
23565   if (!VT.isVector())
23566     return SDValue();
23567
23568   SDValue N0 = N->getOperand(0);
23569   SDValue N1 = N->getOperand(1);
23570   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23571   SDLoc dl(N);
23572
23573   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23574   // both SSE and AVX2 since there is no sign-extended shift right
23575   // operation on a vector with 64-bit elements.
23576   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23577   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23578   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23579       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23580     SDValue N00 = N0.getOperand(0);
23581
23582     // EXTLOAD has a better solution on AVX2,
23583     // it may be replaced with X86ISD::VSEXT node.
23584     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23585       if (!ISD::isNormalLoad(N00.getNode()))
23586         return SDValue();
23587
23588     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23589         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23590                                   N00, N1);
23591       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23592     }
23593   }
23594   return SDValue();
23595 }
23596
23597 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23598                                   TargetLowering::DAGCombinerInfo &DCI,
23599                                   const X86Subtarget *Subtarget) {
23600   SDValue N0 = N->getOperand(0);
23601   EVT VT = N->getValueType(0);
23602
23603   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23604   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23605   // This exposes the sext to the sdivrem lowering, so that it directly extends
23606   // from AH (which we otherwise need to do contortions to access).
23607   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23608       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23609     SDLoc dl(N);
23610     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23611     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23612                             N0.getOperand(0), N0.getOperand(1));
23613     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23614     return R.getValue(1);
23615   }
23616
23617   if (!DCI.isBeforeLegalizeOps())
23618     return SDValue();
23619
23620   if (!Subtarget->hasFp256())
23621     return SDValue();
23622
23623   if (VT.isVector() && VT.getSizeInBits() == 256) {
23624     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23625     if (R.getNode())
23626       return R;
23627   }
23628
23629   return SDValue();
23630 }
23631
23632 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23633                                  const X86Subtarget* Subtarget) {
23634   SDLoc dl(N);
23635   EVT VT = N->getValueType(0);
23636
23637   // Let legalize expand this if it isn't a legal type yet.
23638   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23639     return SDValue();
23640
23641   EVT ScalarVT = VT.getScalarType();
23642   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23643       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23644     return SDValue();
23645
23646   SDValue A = N->getOperand(0);
23647   SDValue B = N->getOperand(1);
23648   SDValue C = N->getOperand(2);
23649
23650   bool NegA = (A.getOpcode() == ISD::FNEG);
23651   bool NegB = (B.getOpcode() == ISD::FNEG);
23652   bool NegC = (C.getOpcode() == ISD::FNEG);
23653
23654   // Negative multiplication when NegA xor NegB
23655   bool NegMul = (NegA != NegB);
23656   if (NegA)
23657     A = A.getOperand(0);
23658   if (NegB)
23659     B = B.getOperand(0);
23660   if (NegC)
23661     C = C.getOperand(0);
23662
23663   unsigned Opcode;
23664   if (!NegMul)
23665     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23666   else
23667     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23668
23669   return DAG.getNode(Opcode, dl, VT, A, B, C);
23670 }
23671
23672 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23673                                   TargetLowering::DAGCombinerInfo &DCI,
23674                                   const X86Subtarget *Subtarget) {
23675   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23676   //           (and (i32 x86isd::setcc_carry), 1)
23677   // This eliminates the zext. This transformation is necessary because
23678   // ISD::SETCC is always legalized to i8.
23679   SDLoc dl(N);
23680   SDValue N0 = N->getOperand(0);
23681   EVT VT = N->getValueType(0);
23682
23683   if (N0.getOpcode() == ISD::AND &&
23684       N0.hasOneUse() &&
23685       N0.getOperand(0).hasOneUse()) {
23686     SDValue N00 = N0.getOperand(0);
23687     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23688       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23689       if (!C || C->getZExtValue() != 1)
23690         return SDValue();
23691       return DAG.getNode(ISD::AND, dl, VT,
23692                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23693                                      N00.getOperand(0), N00.getOperand(1)),
23694                          DAG.getConstant(1, dl, VT));
23695     }
23696   }
23697
23698   if (N0.getOpcode() == ISD::TRUNCATE &&
23699       N0.hasOneUse() &&
23700       N0.getOperand(0).hasOneUse()) {
23701     SDValue N00 = N0.getOperand(0);
23702     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23703       return DAG.getNode(ISD::AND, dl, VT,
23704                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23705                                      N00.getOperand(0), N00.getOperand(1)),
23706                          DAG.getConstant(1, dl, VT));
23707     }
23708   }
23709   if (VT.is256BitVector()) {
23710     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23711     if (R.getNode())
23712       return R;
23713   }
23714
23715   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23716   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23717   // This exposes the zext to the udivrem lowering, so that it directly extends
23718   // from AH (which we otherwise need to do contortions to access).
23719   if (N0.getOpcode() == ISD::UDIVREM &&
23720       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23721       (VT == MVT::i32 || VT == MVT::i64)) {
23722     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23723     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23724                             N0.getOperand(0), N0.getOperand(1));
23725     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23726     return R.getValue(1);
23727   }
23728
23729   return SDValue();
23730 }
23731
23732 // Optimize x == -y --> x+y == 0
23733 //          x != -y --> x+y != 0
23734 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23735                                       const X86Subtarget* Subtarget) {
23736   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23737   SDValue LHS = N->getOperand(0);
23738   SDValue RHS = N->getOperand(1);
23739   EVT VT = N->getValueType(0);
23740   SDLoc DL(N);
23741
23742   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23743     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23744       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23745         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23746                                    LHS.getOperand(1));
23747         return DAG.getSetCC(DL, N->getValueType(0), addV,
23748                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23749       }
23750   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23751     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23752       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23753         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23754                                    RHS.getOperand(1));
23755         return DAG.getSetCC(DL, N->getValueType(0), addV,
23756                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23757       }
23758
23759   if (VT.getScalarType() == MVT::i1 &&
23760       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23761     bool IsSEXT0 =
23762         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23763         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23764     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23765
23766     if (!IsSEXT0 || !IsVZero1) {
23767       // Swap the operands and update the condition code.
23768       std::swap(LHS, RHS);
23769       CC = ISD::getSetCCSwappedOperands(CC);
23770
23771       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23772                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23773       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23774     }
23775
23776     if (IsSEXT0 && IsVZero1) {
23777       assert(VT == LHS.getOperand(0).getValueType() &&
23778              "Uexpected operand type");
23779       if (CC == ISD::SETGT)
23780         return DAG.getConstant(0, DL, VT);
23781       if (CC == ISD::SETLE)
23782         return DAG.getConstant(1, DL, VT);
23783       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23784         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23785
23786       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23787              "Unexpected condition code!");
23788       return LHS.getOperand(0);
23789     }
23790   }
23791
23792   return SDValue();
23793 }
23794
23795 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23796                                          SelectionDAG &DAG) {
23797   SDLoc dl(Load);
23798   MVT VT = Load->getSimpleValueType(0);
23799   MVT EVT = VT.getVectorElementType();
23800   SDValue Addr = Load->getOperand(1);
23801   SDValue NewAddr = DAG.getNode(
23802       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23803       DAG.getConstant(Index * EVT.getStoreSize(), dl,
23804                       Addr.getSimpleValueType()));
23805
23806   SDValue NewLoad =
23807       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23808                   DAG.getMachineFunction().getMachineMemOperand(
23809                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23810   return NewLoad;
23811 }
23812
23813 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23814                                       const X86Subtarget *Subtarget) {
23815   SDLoc dl(N);
23816   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23817   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23818          "X86insertps is only defined for v4x32");
23819
23820   SDValue Ld = N->getOperand(1);
23821   if (MayFoldLoad(Ld)) {
23822     // Extract the countS bits from the immediate so we can get the proper
23823     // address when narrowing the vector load to a specific element.
23824     // When the second source op is a memory address, insertps doesn't use
23825     // countS and just gets an f32 from that address.
23826     unsigned DestIndex =
23827         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23828
23829     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23830
23831     // Create this as a scalar to vector to match the instruction pattern.
23832     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23833     // countS bits are ignored when loading from memory on insertps, which
23834     // means we don't need to explicitly set them to 0.
23835     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23836                        LoadScalarToVector, N->getOperand(2));
23837   }
23838   return SDValue();
23839 }
23840
23841 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23842   SDValue V0 = N->getOperand(0);
23843   SDValue V1 = N->getOperand(1);
23844   SDLoc DL(N);
23845   EVT VT = N->getValueType(0);
23846
23847   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23848   // operands and changing the mask to 1. This saves us a bunch of
23849   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23850   // x86InstrInfo knows how to commute this back after instruction selection
23851   // if it would help register allocation.
23852
23853   // TODO: If optimizing for size or a processor that doesn't suffer from
23854   // partial register update stalls, this should be transformed into a MOVSD
23855   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23856
23857   if (VT == MVT::v2f64)
23858     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23859       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23860         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23861         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23862       }
23863
23864   return SDValue();
23865 }
23866
23867 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23868 // as "sbb reg,reg", since it can be extended without zext and produces
23869 // an all-ones bit which is more useful than 0/1 in some cases.
23870 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23871                                MVT VT) {
23872   if (VT == MVT::i8)
23873     return DAG.getNode(ISD::AND, DL, VT,
23874                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23875                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
23876                                    EFLAGS),
23877                        DAG.getConstant(1, DL, VT));
23878   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23879   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23880                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23881                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
23882                                  EFLAGS));
23883 }
23884
23885 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23886 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23887                                    TargetLowering::DAGCombinerInfo &DCI,
23888                                    const X86Subtarget *Subtarget) {
23889   SDLoc DL(N);
23890   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23891   SDValue EFLAGS = N->getOperand(1);
23892
23893   if (CC == X86::COND_A) {
23894     // Try to convert COND_A into COND_B in an attempt to facilitate
23895     // materializing "setb reg".
23896     //
23897     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23898     // cannot take an immediate as its first operand.
23899     //
23900     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23901         EFLAGS.getValueType().isInteger() &&
23902         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23903       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23904                                    EFLAGS.getNode()->getVTList(),
23905                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23906       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23907       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23908     }
23909   }
23910
23911   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23912   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23913   // cases.
23914   if (CC == X86::COND_B)
23915     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23916
23917   SDValue Flags;
23918
23919   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23920   if (Flags.getNode()) {
23921     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23922     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23923   }
23924
23925   return SDValue();
23926 }
23927
23928 // Optimize branch condition evaluation.
23929 //
23930 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23931                                     TargetLowering::DAGCombinerInfo &DCI,
23932                                     const X86Subtarget *Subtarget) {
23933   SDLoc DL(N);
23934   SDValue Chain = N->getOperand(0);
23935   SDValue Dest = N->getOperand(1);
23936   SDValue EFLAGS = N->getOperand(3);
23937   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23938
23939   SDValue Flags;
23940
23941   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23942   if (Flags.getNode()) {
23943     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23944     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23945                        Flags);
23946   }
23947
23948   return SDValue();
23949 }
23950
23951 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23952                                                          SelectionDAG &DAG) {
23953   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23954   // optimize away operation when it's from a constant.
23955   //
23956   // The general transformation is:
23957   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23958   //       AND(VECTOR_CMP(x,y), constant2)
23959   //    constant2 = UNARYOP(constant)
23960
23961   // Early exit if this isn't a vector operation, the operand of the
23962   // unary operation isn't a bitwise AND, or if the sizes of the operations
23963   // aren't the same.
23964   EVT VT = N->getValueType(0);
23965   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23966       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23967       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23968     return SDValue();
23969
23970   // Now check that the other operand of the AND is a constant. We could
23971   // make the transformation for non-constant splats as well, but it's unclear
23972   // that would be a benefit as it would not eliminate any operations, just
23973   // perform one more step in scalar code before moving to the vector unit.
23974   if (BuildVectorSDNode *BV =
23975           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23976     // Bail out if the vector isn't a constant.
23977     if (!BV->isConstant())
23978       return SDValue();
23979
23980     // Everything checks out. Build up the new and improved node.
23981     SDLoc DL(N);
23982     EVT IntVT = BV->getValueType(0);
23983     // Create a new constant of the appropriate type for the transformed
23984     // DAG.
23985     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23986     // The AND node needs bitcasts to/from an integer vector type around it.
23987     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23988     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23989                                  N->getOperand(0)->getOperand(0), MaskConst);
23990     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23991     return Res;
23992   }
23993
23994   return SDValue();
23995 }
23996
23997 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23998                                         const X86Subtarget *Subtarget) {
23999   // First try to optimize away the conversion entirely when it's
24000   // conditionally from a constant. Vectors only.
24001   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24002   if (Res != SDValue())
24003     return Res;
24004
24005   // Now move on to more general possibilities.
24006   SDValue Op0 = N->getOperand(0);
24007   EVT InVT = Op0->getValueType(0);
24008
24009   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24010   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24011     SDLoc dl(N);
24012     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24013     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24014     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24015   }
24016
24017   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24018   // a 32-bit target where SSE doesn't support i64->FP operations.
24019   if (Op0.getOpcode() == ISD::LOAD) {
24020     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24021     EVT VT = Ld->getValueType(0);
24022     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24023         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24024         !Subtarget->is64Bit() && VT == MVT::i64) {
24025       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24026           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24027       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24028       return FILDChain;
24029     }
24030   }
24031   return SDValue();
24032 }
24033
24034 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24035 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24036                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24037   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24038   // the result is either zero or one (depending on the input carry bit).
24039   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24040   if (X86::isZeroNode(N->getOperand(0)) &&
24041       X86::isZeroNode(N->getOperand(1)) &&
24042       // We don't have a good way to replace an EFLAGS use, so only do this when
24043       // dead right now.
24044       SDValue(N, 1).use_empty()) {
24045     SDLoc DL(N);
24046     EVT VT = N->getValueType(0);
24047     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24048     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24049                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24050                                            DAG.getConstant(X86::COND_B, DL,
24051                                                            MVT::i8),
24052                                            N->getOperand(2)),
24053                                DAG.getConstant(1, DL, VT));
24054     return DCI.CombineTo(N, Res1, CarryOut);
24055   }
24056
24057   return SDValue();
24058 }
24059
24060 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24061 //      (add Y, (setne X, 0)) -> sbb -1, Y
24062 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24063 //      (sub (setne X, 0), Y) -> adc -1, Y
24064 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24065   SDLoc DL(N);
24066
24067   // Look through ZExts.
24068   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24069   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24070     return SDValue();
24071
24072   SDValue SetCC = Ext.getOperand(0);
24073   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24074     return SDValue();
24075
24076   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24077   if (CC != X86::COND_E && CC != X86::COND_NE)
24078     return SDValue();
24079
24080   SDValue Cmp = SetCC.getOperand(1);
24081   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24082       !X86::isZeroNode(Cmp.getOperand(1)) ||
24083       !Cmp.getOperand(0).getValueType().isInteger())
24084     return SDValue();
24085
24086   SDValue CmpOp0 = Cmp.getOperand(0);
24087   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24088                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24089
24090   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24091   if (CC == X86::COND_NE)
24092     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24093                        DL, OtherVal.getValueType(), OtherVal,
24094                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24095                        NewCmp);
24096   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24097                      DL, OtherVal.getValueType(), OtherVal,
24098                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24099 }
24100
24101 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24102 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24103                                  const X86Subtarget *Subtarget) {
24104   EVT VT = N->getValueType(0);
24105   SDValue Op0 = N->getOperand(0);
24106   SDValue Op1 = N->getOperand(1);
24107
24108   // Try to synthesize horizontal adds from adds of shuffles.
24109   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24110        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24111       isHorizontalBinOp(Op0, Op1, true))
24112     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24113
24114   return OptimizeConditionalInDecrement(N, DAG);
24115 }
24116
24117 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24118                                  const X86Subtarget *Subtarget) {
24119   SDValue Op0 = N->getOperand(0);
24120   SDValue Op1 = N->getOperand(1);
24121
24122   // X86 can't encode an immediate LHS of a sub. See if we can push the
24123   // negation into a preceding instruction.
24124   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24125     // If the RHS of the sub is a XOR with one use and a constant, invert the
24126     // immediate. Then add one to the LHS of the sub so we can turn
24127     // X-Y -> X+~Y+1, saving one register.
24128     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24129         isa<ConstantSDNode>(Op1.getOperand(1))) {
24130       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24131       EVT VT = Op0.getValueType();
24132       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24133                                    Op1.getOperand(0),
24134                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24135       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24136                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24137     }
24138   }
24139
24140   // Try to synthesize horizontal adds from adds of shuffles.
24141   EVT VT = N->getValueType(0);
24142   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24143        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24144       isHorizontalBinOp(Op0, Op1, true))
24145     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24146
24147   return OptimizeConditionalInDecrement(N, DAG);
24148 }
24149
24150 /// performVZEXTCombine - Performs build vector combines
24151 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24152                                    TargetLowering::DAGCombinerInfo &DCI,
24153                                    const X86Subtarget *Subtarget) {
24154   SDLoc DL(N);
24155   MVT VT = N->getSimpleValueType(0);
24156   SDValue Op = N->getOperand(0);
24157   MVT OpVT = Op.getSimpleValueType();
24158   MVT OpEltVT = OpVT.getVectorElementType();
24159   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24160
24161   // (vzext (bitcast (vzext (x)) -> (vzext x)
24162   SDValue V = Op;
24163   while (V.getOpcode() == ISD::BITCAST)
24164     V = V.getOperand(0);
24165
24166   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24167     MVT InnerVT = V.getSimpleValueType();
24168     MVT InnerEltVT = InnerVT.getVectorElementType();
24169
24170     // If the element sizes match exactly, we can just do one larger vzext. This
24171     // is always an exact type match as vzext operates on integer types.
24172     if (OpEltVT == InnerEltVT) {
24173       assert(OpVT == InnerVT && "Types must match for vzext!");
24174       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24175     }
24176
24177     // The only other way we can combine them is if only a single element of the
24178     // inner vzext is used in the input to the outer vzext.
24179     if (InnerEltVT.getSizeInBits() < InputBits)
24180       return SDValue();
24181
24182     // In this case, the inner vzext is completely dead because we're going to
24183     // only look at bits inside of the low element. Just do the outer vzext on
24184     // a bitcast of the input to the inner.
24185     return DAG.getNode(X86ISD::VZEXT, DL, VT,
24186                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24187   }
24188
24189   // Check if we can bypass extracting and re-inserting an element of an input
24190   // vector. Essentialy:
24191   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24192   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24193       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24194       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24195     SDValue ExtractedV = V.getOperand(0);
24196     SDValue OrigV = ExtractedV.getOperand(0);
24197     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24198       if (ExtractIdx->getZExtValue() == 0) {
24199         MVT OrigVT = OrigV.getSimpleValueType();
24200         // Extract a subvector if necessary...
24201         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24202           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24203           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24204                                     OrigVT.getVectorNumElements() / Ratio);
24205           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24206                               DAG.getIntPtrConstant(0, DL));
24207         }
24208         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24209         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24210       }
24211   }
24212
24213   return SDValue();
24214 }
24215
24216 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24217                                              DAGCombinerInfo &DCI) const {
24218   SelectionDAG &DAG = DCI.DAG;
24219   switch (N->getOpcode()) {
24220   default: break;
24221   case ISD::EXTRACT_VECTOR_ELT:
24222     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24223   case ISD::VSELECT:
24224   case ISD::SELECT:
24225   case X86ISD::SHRUNKBLEND:
24226     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24227   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24228   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24229   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24230   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24231   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24232   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24233   case ISD::SHL:
24234   case ISD::SRA:
24235   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24236   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24237   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24238   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24239   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24240   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24241   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24242   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24243   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24244   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24245   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24246   case X86ISD::FXOR:
24247   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24248   case X86ISD::FMIN:
24249   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24250   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24251   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24252   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24253   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24254   case ISD::ANY_EXTEND:
24255   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24256   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24257   case ISD::SIGN_EXTEND_INREG:
24258     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24259   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
24260   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24261   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24262   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24263   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24264   case X86ISD::SHUFP:       // Handle all target specific shuffles
24265   case X86ISD::PALIGNR:
24266   case X86ISD::UNPCKH:
24267   case X86ISD::UNPCKL:
24268   case X86ISD::MOVHLPS:
24269   case X86ISD::MOVLHPS:
24270   case X86ISD::PSHUFB:
24271   case X86ISD::PSHUFD:
24272   case X86ISD::PSHUFHW:
24273   case X86ISD::PSHUFLW:
24274   case X86ISD::MOVSS:
24275   case X86ISD::MOVSD:
24276   case X86ISD::VPERMILPI:
24277   case X86ISD::VPERM2X128:
24278   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24279   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24280   case ISD::INTRINSIC_WO_CHAIN:
24281     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24282   case X86ISD::INSERTPS: {
24283     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24284       return PerformINSERTPSCombine(N, DAG, Subtarget);
24285     break;
24286   }
24287   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24288   }
24289
24290   return SDValue();
24291 }
24292
24293 /// isTypeDesirableForOp - Return true if the target has native support for
24294 /// the specified value type and it is 'desirable' to use the type for the
24295 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24296 /// instruction encodings are longer and some i16 instructions are slow.
24297 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24298   if (!isTypeLegal(VT))
24299     return false;
24300   if (VT != MVT::i16)
24301     return true;
24302
24303   switch (Opc) {
24304   default:
24305     return true;
24306   case ISD::LOAD:
24307   case ISD::SIGN_EXTEND:
24308   case ISD::ZERO_EXTEND:
24309   case ISD::ANY_EXTEND:
24310   case ISD::SHL:
24311   case ISD::SRL:
24312   case ISD::SUB:
24313   case ISD::ADD:
24314   case ISD::MUL:
24315   case ISD::AND:
24316   case ISD::OR:
24317   case ISD::XOR:
24318     return false;
24319   }
24320 }
24321
24322 /// IsDesirableToPromoteOp - This method query the target whether it is
24323 /// beneficial for dag combiner to promote the specified node. If true, it
24324 /// should return the desired promotion type by reference.
24325 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24326   EVT VT = Op.getValueType();
24327   if (VT != MVT::i16)
24328     return false;
24329
24330   bool Promote = false;
24331   bool Commute = false;
24332   switch (Op.getOpcode()) {
24333   default: break;
24334   case ISD::LOAD: {
24335     LoadSDNode *LD = cast<LoadSDNode>(Op);
24336     // If the non-extending load has a single use and it's not live out, then it
24337     // might be folded.
24338     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24339                                                      Op.hasOneUse()*/) {
24340       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24341              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24342         // The only case where we'd want to promote LOAD (rather then it being
24343         // promoted as an operand is when it's only use is liveout.
24344         if (UI->getOpcode() != ISD::CopyToReg)
24345           return false;
24346       }
24347     }
24348     Promote = true;
24349     break;
24350   }
24351   case ISD::SIGN_EXTEND:
24352   case ISD::ZERO_EXTEND:
24353   case ISD::ANY_EXTEND:
24354     Promote = true;
24355     break;
24356   case ISD::SHL:
24357   case ISD::SRL: {
24358     SDValue N0 = Op.getOperand(0);
24359     // Look out for (store (shl (load), x)).
24360     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24361       return false;
24362     Promote = true;
24363     break;
24364   }
24365   case ISD::ADD:
24366   case ISD::MUL:
24367   case ISD::AND:
24368   case ISD::OR:
24369   case ISD::XOR:
24370     Commute = true;
24371     // fallthrough
24372   case ISD::SUB: {
24373     SDValue N0 = Op.getOperand(0);
24374     SDValue N1 = Op.getOperand(1);
24375     if (!Commute && MayFoldLoad(N1))
24376       return false;
24377     // Avoid disabling potential load folding opportunities.
24378     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24379       return false;
24380     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24381       return false;
24382     Promote = true;
24383   }
24384   }
24385
24386   PVT = MVT::i32;
24387   return Promote;
24388 }
24389
24390 //===----------------------------------------------------------------------===//
24391 //                           X86 Inline Assembly Support
24392 //===----------------------------------------------------------------------===//
24393
24394 // Helper to match a string separated by whitespace.
24395 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24396   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24397
24398   for (StringRef Piece : Pieces) {
24399     if (!S.startswith(Piece)) // Check if the piece matches.
24400       return false;
24401
24402     S = S.substr(Piece.size());
24403     StringRef::size_type Pos = S.find_first_not_of(" \t");
24404     if (Pos == 0) // We matched a prefix.
24405       return false;
24406
24407     S = S.substr(Pos);
24408   }
24409
24410   return S.empty();
24411 }
24412
24413 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24414
24415   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24416     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24417         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24418         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24419
24420       if (AsmPieces.size() == 3)
24421         return true;
24422       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24423         return true;
24424     }
24425   }
24426   return false;
24427 }
24428
24429 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24430   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24431
24432   std::string AsmStr = IA->getAsmString();
24433
24434   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24435   if (!Ty || Ty->getBitWidth() % 16 != 0)
24436     return false;
24437
24438   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24439   SmallVector<StringRef, 4> AsmPieces;
24440   SplitString(AsmStr, AsmPieces, ";\n");
24441
24442   switch (AsmPieces.size()) {
24443   default: return false;
24444   case 1:
24445     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24446     // we will turn this bswap into something that will be lowered to logical
24447     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24448     // lower so don't worry about this.
24449     // bswap $0
24450     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24451         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24452         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24453         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24454         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24455         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24456       // No need to check constraints, nothing other than the equivalent of
24457       // "=r,0" would be valid here.
24458       return IntrinsicLowering::LowerToByteSwap(CI);
24459     }
24460
24461     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24462     if (CI->getType()->isIntegerTy(16) &&
24463         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24464         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24465          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24466       AsmPieces.clear();
24467       const std::string &ConstraintsStr = IA->getConstraintString();
24468       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24469       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24470       if (clobbersFlagRegisters(AsmPieces))
24471         return IntrinsicLowering::LowerToByteSwap(CI);
24472     }
24473     break;
24474   case 3:
24475     if (CI->getType()->isIntegerTy(32) &&
24476         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24477         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24478         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24479         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24480       AsmPieces.clear();
24481       const std::string &ConstraintsStr = IA->getConstraintString();
24482       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24483       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24484       if (clobbersFlagRegisters(AsmPieces))
24485         return IntrinsicLowering::LowerToByteSwap(CI);
24486     }
24487
24488     if (CI->getType()->isIntegerTy(64)) {
24489       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24490       if (Constraints.size() >= 2 &&
24491           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24492           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24493         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24494         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24495             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24496             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24497           return IntrinsicLowering::LowerToByteSwap(CI);
24498       }
24499     }
24500     break;
24501   }
24502   return false;
24503 }
24504
24505 /// getConstraintType - Given a constraint letter, return the type of
24506 /// constraint it is for this target.
24507 X86TargetLowering::ConstraintType
24508 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24509   if (Constraint.size() == 1) {
24510     switch (Constraint[0]) {
24511     case 'R':
24512     case 'q':
24513     case 'Q':
24514     case 'f':
24515     case 't':
24516     case 'u':
24517     case 'y':
24518     case 'x':
24519     case 'Y':
24520     case 'l':
24521       return C_RegisterClass;
24522     case 'a':
24523     case 'b':
24524     case 'c':
24525     case 'd':
24526     case 'S':
24527     case 'D':
24528     case 'A':
24529       return C_Register;
24530     case 'I':
24531     case 'J':
24532     case 'K':
24533     case 'L':
24534     case 'M':
24535     case 'N':
24536     case 'G':
24537     case 'C':
24538     case 'e':
24539     case 'Z':
24540       return C_Other;
24541     default:
24542       break;
24543     }
24544   }
24545   return TargetLowering::getConstraintType(Constraint);
24546 }
24547
24548 /// Examine constraint type and operand type and determine a weight value.
24549 /// This object must already have been set up with the operand type
24550 /// and the current alternative constraint selected.
24551 TargetLowering::ConstraintWeight
24552   X86TargetLowering::getSingleConstraintMatchWeight(
24553     AsmOperandInfo &info, const char *constraint) const {
24554   ConstraintWeight weight = CW_Invalid;
24555   Value *CallOperandVal = info.CallOperandVal;
24556     // If we don't have a value, we can't do a match,
24557     // but allow it at the lowest weight.
24558   if (!CallOperandVal)
24559     return CW_Default;
24560   Type *type = CallOperandVal->getType();
24561   // Look at the constraint type.
24562   switch (*constraint) {
24563   default:
24564     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24565   case 'R':
24566   case 'q':
24567   case 'Q':
24568   case 'a':
24569   case 'b':
24570   case 'c':
24571   case 'd':
24572   case 'S':
24573   case 'D':
24574   case 'A':
24575     if (CallOperandVal->getType()->isIntegerTy())
24576       weight = CW_SpecificReg;
24577     break;
24578   case 'f':
24579   case 't':
24580   case 'u':
24581     if (type->isFloatingPointTy())
24582       weight = CW_SpecificReg;
24583     break;
24584   case 'y':
24585     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24586       weight = CW_SpecificReg;
24587     break;
24588   case 'x':
24589   case 'Y':
24590     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24591         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24592       weight = CW_Register;
24593     break;
24594   case 'I':
24595     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24596       if (C->getZExtValue() <= 31)
24597         weight = CW_Constant;
24598     }
24599     break;
24600   case 'J':
24601     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24602       if (C->getZExtValue() <= 63)
24603         weight = CW_Constant;
24604     }
24605     break;
24606   case 'K':
24607     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24608       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24609         weight = CW_Constant;
24610     }
24611     break;
24612   case 'L':
24613     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24614       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24615         weight = CW_Constant;
24616     }
24617     break;
24618   case 'M':
24619     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24620       if (C->getZExtValue() <= 3)
24621         weight = CW_Constant;
24622     }
24623     break;
24624   case 'N':
24625     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24626       if (C->getZExtValue() <= 0xff)
24627         weight = CW_Constant;
24628     }
24629     break;
24630   case 'G':
24631   case 'C':
24632     if (isa<ConstantFP>(CallOperandVal)) {
24633       weight = CW_Constant;
24634     }
24635     break;
24636   case 'e':
24637     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24638       if ((C->getSExtValue() >= -0x80000000LL) &&
24639           (C->getSExtValue() <= 0x7fffffffLL))
24640         weight = CW_Constant;
24641     }
24642     break;
24643   case 'Z':
24644     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24645       if (C->getZExtValue() <= 0xffffffff)
24646         weight = CW_Constant;
24647     }
24648     break;
24649   }
24650   return weight;
24651 }
24652
24653 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24654 /// with another that has more specific requirements based on the type of the
24655 /// corresponding operand.
24656 const char *X86TargetLowering::
24657 LowerXConstraint(EVT ConstraintVT) const {
24658   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24659   // 'f' like normal targets.
24660   if (ConstraintVT.isFloatingPoint()) {
24661     if (Subtarget->hasSSE2())
24662       return "Y";
24663     if (Subtarget->hasSSE1())
24664       return "x";
24665   }
24666
24667   return TargetLowering::LowerXConstraint(ConstraintVT);
24668 }
24669
24670 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24671 /// vector.  If it is invalid, don't add anything to Ops.
24672 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24673                                                      std::string &Constraint,
24674                                                      std::vector<SDValue>&Ops,
24675                                                      SelectionDAG &DAG) const {
24676   SDValue Result;
24677
24678   // Only support length 1 constraints for now.
24679   if (Constraint.length() > 1) return;
24680
24681   char ConstraintLetter = Constraint[0];
24682   switch (ConstraintLetter) {
24683   default: break;
24684   case 'I':
24685     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24686       if (C->getZExtValue() <= 31) {
24687         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24688                                        Op.getValueType());
24689         break;
24690       }
24691     }
24692     return;
24693   case 'J':
24694     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24695       if (C->getZExtValue() <= 63) {
24696         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24697                                        Op.getValueType());
24698         break;
24699       }
24700     }
24701     return;
24702   case 'K':
24703     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24704       if (isInt<8>(C->getSExtValue())) {
24705         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24706                                        Op.getValueType());
24707         break;
24708       }
24709     }
24710     return;
24711   case 'L':
24712     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24713       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24714           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24715         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24716                                        Op.getValueType());
24717         break;
24718       }
24719     }
24720     return;
24721   case 'M':
24722     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24723       if (C->getZExtValue() <= 3) {
24724         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24725                                        Op.getValueType());
24726         break;
24727       }
24728     }
24729     return;
24730   case 'N':
24731     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24732       if (C->getZExtValue() <= 255) {
24733         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24734                                        Op.getValueType());
24735         break;
24736       }
24737     }
24738     return;
24739   case 'O':
24740     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24741       if (C->getZExtValue() <= 127) {
24742         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24743                                        Op.getValueType());
24744         break;
24745       }
24746     }
24747     return;
24748   case 'e': {
24749     // 32-bit signed value
24750     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24751       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24752                                            C->getSExtValue())) {
24753         // Widen to 64 bits here to get it sign extended.
24754         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24755         break;
24756       }
24757     // FIXME gcc accepts some relocatable values here too, but only in certain
24758     // memory models; it's complicated.
24759     }
24760     return;
24761   }
24762   case 'Z': {
24763     // 32-bit unsigned value
24764     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24765       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24766                                            C->getZExtValue())) {
24767         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24768                                        Op.getValueType());
24769         break;
24770       }
24771     }
24772     // FIXME gcc accepts some relocatable values here too, but only in certain
24773     // memory models; it's complicated.
24774     return;
24775   }
24776   case 'i': {
24777     // Literal immediates are always ok.
24778     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24779       // Widen to 64 bits here to get it sign extended.
24780       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24781       break;
24782     }
24783
24784     // In any sort of PIC mode addresses need to be computed at runtime by
24785     // adding in a register or some sort of table lookup.  These can't
24786     // be used as immediates.
24787     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24788       return;
24789
24790     // If we are in non-pic codegen mode, we allow the address of a global (with
24791     // an optional displacement) to be used with 'i'.
24792     GlobalAddressSDNode *GA = nullptr;
24793     int64_t Offset = 0;
24794
24795     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24796     while (1) {
24797       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24798         Offset += GA->getOffset();
24799         break;
24800       } else if (Op.getOpcode() == ISD::ADD) {
24801         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24802           Offset += C->getZExtValue();
24803           Op = Op.getOperand(0);
24804           continue;
24805         }
24806       } else if (Op.getOpcode() == ISD::SUB) {
24807         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24808           Offset += -C->getZExtValue();
24809           Op = Op.getOperand(0);
24810           continue;
24811         }
24812       }
24813
24814       // Otherwise, this isn't something we can handle, reject it.
24815       return;
24816     }
24817
24818     const GlobalValue *GV = GA->getGlobal();
24819     // If we require an extra load to get this address, as in PIC mode, we
24820     // can't accept it.
24821     if (isGlobalStubReference(
24822             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24823       return;
24824
24825     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24826                                         GA->getValueType(0), Offset);
24827     break;
24828   }
24829   }
24830
24831   if (Result.getNode()) {
24832     Ops.push_back(Result);
24833     return;
24834   }
24835   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24836 }
24837
24838 std::pair<unsigned, const TargetRegisterClass *>
24839 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24840                                                 const std::string &Constraint,
24841                                                 MVT VT) const {
24842   // First, see if this is a constraint that directly corresponds to an LLVM
24843   // register class.
24844   if (Constraint.size() == 1) {
24845     // GCC Constraint Letters
24846     switch (Constraint[0]) {
24847     default: break;
24848       // TODO: Slight differences here in allocation order and leaving
24849       // RIP in the class. Do they matter any more here than they do
24850       // in the normal allocation?
24851     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24852       if (Subtarget->is64Bit()) {
24853         if (VT == MVT::i32 || VT == MVT::f32)
24854           return std::make_pair(0U, &X86::GR32RegClass);
24855         if (VT == MVT::i16)
24856           return std::make_pair(0U, &X86::GR16RegClass);
24857         if (VT == MVT::i8 || VT == MVT::i1)
24858           return std::make_pair(0U, &X86::GR8RegClass);
24859         if (VT == MVT::i64 || VT == MVT::f64)
24860           return std::make_pair(0U, &X86::GR64RegClass);
24861         break;
24862       }
24863       // 32-bit fallthrough
24864     case 'Q':   // Q_REGS
24865       if (VT == MVT::i32 || VT == MVT::f32)
24866         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24867       if (VT == MVT::i16)
24868         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24869       if (VT == MVT::i8 || VT == MVT::i1)
24870         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24871       if (VT == MVT::i64)
24872         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24873       break;
24874     case 'r':   // GENERAL_REGS
24875     case 'l':   // INDEX_REGS
24876       if (VT == MVT::i8 || VT == MVT::i1)
24877         return std::make_pair(0U, &X86::GR8RegClass);
24878       if (VT == MVT::i16)
24879         return std::make_pair(0U, &X86::GR16RegClass);
24880       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24881         return std::make_pair(0U, &X86::GR32RegClass);
24882       return std::make_pair(0U, &X86::GR64RegClass);
24883     case 'R':   // LEGACY_REGS
24884       if (VT == MVT::i8 || VT == MVT::i1)
24885         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24886       if (VT == MVT::i16)
24887         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24888       if (VT == MVT::i32 || !Subtarget->is64Bit())
24889         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24890       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24891     case 'f':  // FP Stack registers.
24892       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24893       // value to the correct fpstack register class.
24894       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24895         return std::make_pair(0U, &X86::RFP32RegClass);
24896       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24897         return std::make_pair(0U, &X86::RFP64RegClass);
24898       return std::make_pair(0U, &X86::RFP80RegClass);
24899     case 'y':   // MMX_REGS if MMX allowed.
24900       if (!Subtarget->hasMMX()) break;
24901       return std::make_pair(0U, &X86::VR64RegClass);
24902     case 'Y':   // SSE_REGS if SSE2 allowed
24903       if (!Subtarget->hasSSE2()) break;
24904       // FALL THROUGH.
24905     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24906       if (!Subtarget->hasSSE1()) break;
24907
24908       switch (VT.SimpleTy) {
24909       default: break;
24910       // Scalar SSE types.
24911       case MVT::f32:
24912       case MVT::i32:
24913         return std::make_pair(0U, &X86::FR32RegClass);
24914       case MVT::f64:
24915       case MVT::i64:
24916         return std::make_pair(0U, &X86::FR64RegClass);
24917       // Vector types.
24918       case MVT::v16i8:
24919       case MVT::v8i16:
24920       case MVT::v4i32:
24921       case MVT::v2i64:
24922       case MVT::v4f32:
24923       case MVT::v2f64:
24924         return std::make_pair(0U, &X86::VR128RegClass);
24925       // AVX types.
24926       case MVT::v32i8:
24927       case MVT::v16i16:
24928       case MVT::v8i32:
24929       case MVT::v4i64:
24930       case MVT::v8f32:
24931       case MVT::v4f64:
24932         return std::make_pair(0U, &X86::VR256RegClass);
24933       case MVT::v8f64:
24934       case MVT::v16f32:
24935       case MVT::v16i32:
24936       case MVT::v8i64:
24937         return std::make_pair(0U, &X86::VR512RegClass);
24938       }
24939       break;
24940     }
24941   }
24942
24943   // Use the default implementation in TargetLowering to convert the register
24944   // constraint into a member of a register class.
24945   std::pair<unsigned, const TargetRegisterClass*> Res;
24946   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24947
24948   // Not found as a standard register?
24949   if (!Res.second) {
24950     // Map st(0) -> st(7) -> ST0
24951     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24952         tolower(Constraint[1]) == 's' &&
24953         tolower(Constraint[2]) == 't' &&
24954         Constraint[3] == '(' &&
24955         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24956         Constraint[5] == ')' &&
24957         Constraint[6] == '}') {
24958
24959       Res.first = X86::FP0+Constraint[4]-'0';
24960       Res.second = &X86::RFP80RegClass;
24961       return Res;
24962     }
24963
24964     // GCC allows "st(0)" to be called just plain "st".
24965     if (StringRef("{st}").equals_lower(Constraint)) {
24966       Res.first = X86::FP0;
24967       Res.second = &X86::RFP80RegClass;
24968       return Res;
24969     }
24970
24971     // flags -> EFLAGS
24972     if (StringRef("{flags}").equals_lower(Constraint)) {
24973       Res.first = X86::EFLAGS;
24974       Res.second = &X86::CCRRegClass;
24975       return Res;
24976     }
24977
24978     // 'A' means EAX + EDX.
24979     if (Constraint == "A") {
24980       Res.first = X86::EAX;
24981       Res.second = &X86::GR32_ADRegClass;
24982       return Res;
24983     }
24984     return Res;
24985   }
24986
24987   // Otherwise, check to see if this is a register class of the wrong value
24988   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24989   // turn into {ax},{dx}.
24990   if (Res.second->hasType(VT))
24991     return Res;   // Correct type already, nothing to do.
24992
24993   // All of the single-register GCC register classes map their values onto
24994   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
24995   // really want an 8-bit or 32-bit register, map to the appropriate register
24996   // class and return the appropriate register.
24997   if (Res.second == &X86::GR16RegClass) {
24998     if (VT == MVT::i8 || VT == MVT::i1) {
24999       unsigned DestReg = 0;
25000       switch (Res.first) {
25001       default: break;
25002       case X86::AX: DestReg = X86::AL; break;
25003       case X86::DX: DestReg = X86::DL; break;
25004       case X86::CX: DestReg = X86::CL; break;
25005       case X86::BX: DestReg = X86::BL; break;
25006       }
25007       if (DestReg) {
25008         Res.first = DestReg;
25009         Res.second = &X86::GR8RegClass;
25010       }
25011     } else if (VT == MVT::i32 || VT == MVT::f32) {
25012       unsigned DestReg = 0;
25013       switch (Res.first) {
25014       default: break;
25015       case X86::AX: DestReg = X86::EAX; break;
25016       case X86::DX: DestReg = X86::EDX; break;
25017       case X86::CX: DestReg = X86::ECX; break;
25018       case X86::BX: DestReg = X86::EBX; break;
25019       case X86::SI: DestReg = X86::ESI; break;
25020       case X86::DI: DestReg = X86::EDI; break;
25021       case X86::BP: DestReg = X86::EBP; break;
25022       case X86::SP: DestReg = X86::ESP; break;
25023       }
25024       if (DestReg) {
25025         Res.first = DestReg;
25026         Res.second = &X86::GR32RegClass;
25027       }
25028     } else if (VT == MVT::i64 || VT == MVT::f64) {
25029       unsigned DestReg = 0;
25030       switch (Res.first) {
25031       default: break;
25032       case X86::AX: DestReg = X86::RAX; break;
25033       case X86::DX: DestReg = X86::RDX; break;
25034       case X86::CX: DestReg = X86::RCX; break;
25035       case X86::BX: DestReg = X86::RBX; break;
25036       case X86::SI: DestReg = X86::RSI; break;
25037       case X86::DI: DestReg = X86::RDI; break;
25038       case X86::BP: DestReg = X86::RBP; break;
25039       case X86::SP: DestReg = X86::RSP; break;
25040       }
25041       if (DestReg) {
25042         Res.first = DestReg;
25043         Res.second = &X86::GR64RegClass;
25044       }
25045     }
25046   } else if (Res.second == &X86::FR32RegClass ||
25047              Res.second == &X86::FR64RegClass ||
25048              Res.second == &X86::VR128RegClass ||
25049              Res.second == &X86::VR256RegClass ||
25050              Res.second == &X86::FR32XRegClass ||
25051              Res.second == &X86::FR64XRegClass ||
25052              Res.second == &X86::VR128XRegClass ||
25053              Res.second == &X86::VR256XRegClass ||
25054              Res.second == &X86::VR512RegClass) {
25055     // Handle references to XMM physical registers that got mapped into the
25056     // wrong class.  This can happen with constraints like {xmm0} where the
25057     // target independent register mapper will just pick the first match it can
25058     // find, ignoring the required type.
25059
25060     if (VT == MVT::f32 || VT == MVT::i32)
25061       Res.second = &X86::FR32RegClass;
25062     else if (VT == MVT::f64 || VT == MVT::i64)
25063       Res.second = &X86::FR64RegClass;
25064     else if (X86::VR128RegClass.hasType(VT))
25065       Res.second = &X86::VR128RegClass;
25066     else if (X86::VR256RegClass.hasType(VT))
25067       Res.second = &X86::VR256RegClass;
25068     else if (X86::VR512RegClass.hasType(VT))
25069       Res.second = &X86::VR512RegClass;
25070   }
25071
25072   return Res;
25073 }
25074
25075 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25076                                             Type *Ty) const {
25077   // Scaling factors are not free at all.
25078   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25079   // will take 2 allocations in the out of order engine instead of 1
25080   // for plain addressing mode, i.e. inst (reg1).
25081   // E.g.,
25082   // vaddps (%rsi,%drx), %ymm0, %ymm1
25083   // Requires two allocations (one for the load, one for the computation)
25084   // whereas:
25085   // vaddps (%rsi), %ymm0, %ymm1
25086   // Requires just 1 allocation, i.e., freeing allocations for other operations
25087   // and having less micro operations to execute.
25088   //
25089   // For some X86 architectures, this is even worse because for instance for
25090   // stores, the complex addressing mode forces the instruction to use the
25091   // "load" ports instead of the dedicated "store" port.
25092   // E.g., on Haswell:
25093   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25094   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25095   if (isLegalAddressingMode(AM, Ty))
25096     // Scale represents reg2 * scale, thus account for 1
25097     // as soon as we use a second register.
25098     return AM.Scale != 0;
25099   return -1;
25100 }
25101
25102 bool X86TargetLowering::isTargetFTOL() const {
25103   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25104 }