[WinEH] Store pointers to the LSDA in the exception registration object
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 static cl::opt<int> ReciprocalEstimateRefinementSteps(
71     "x86-recip-refinement-steps", cl::init(1),
72     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
73              "result of the hardware reciprocal estimate instruction."),
74     cl::NotHidden);
75
76 // Forward declarations.
77 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
78                        SDValue V2);
79
80 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
81                                      const X86Subtarget &STI)
82     : TargetLowering(TM), Subtarget(&STI) {
83   X86ScalarSSEf64 = Subtarget->hasSSE2();
84   X86ScalarSSEf32 = Subtarget->hasSSE1();
85   TD = getDataLayout();
86
87   // Set up the TargetLowering object.
88   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
89
90   // X86 is weird. It always uses i8 for shift amounts and setcc results.
91   setBooleanContents(ZeroOrOneBooleanContent);
92   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
93   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
94
95   // For 64-bit, since we have so many registers, use the ILP scheduler.
96   // For 32-bit, use the register pressure specific scheduling.
97   // For Atom, always use ILP scheduling.
98   if (Subtarget->isAtom())
99     setSchedulingPreference(Sched::ILP);
100   else if (Subtarget->is64Bit())
101     setSchedulingPreference(Sched::ILP);
102   else
103     setSchedulingPreference(Sched::RegPressure);
104   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
105   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
106
107   // Bypass expensive divides on Atom when compiling with O2.
108   if (TM.getOptLevel() >= CodeGenOpt::Default) {
109     if (Subtarget->hasSlowDivide32())
110       addBypassSlowDiv(32, 8);
111     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
112       addBypassSlowDiv(64, 16);
113   }
114
115   if (Subtarget->isTargetKnownWindowsMSVC()) {
116     // Setup Windows compiler runtime calls.
117     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
118     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
119     setLibcallName(RTLIB::SREM_I64, "_allrem");
120     setLibcallName(RTLIB::UREM_I64, "_aullrem");
121     setLibcallName(RTLIB::MUL_I64, "_allmul");
122     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
123     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
124     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
125     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
126     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
127
128     // The _ftol2 runtime function has an unusual calling conv, which
129     // is modeled by a special pseudo-instruction.
130     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
131     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
132     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
133     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
134   }
135
136   if (Subtarget->isTargetDarwin()) {
137     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
138     setUseUnderscoreSetJmp(false);
139     setUseUnderscoreLongJmp(false);
140   } else if (Subtarget->isTargetWindowsGNU()) {
141     // MS runtime is weird: it exports _setjmp, but longjmp!
142     setUseUnderscoreSetJmp(true);
143     setUseUnderscoreLongJmp(false);
144   } else {
145     setUseUnderscoreSetJmp(true);
146     setUseUnderscoreLongJmp(true);
147   }
148
149   // Set up the register classes.
150   addRegisterClass(MVT::i8, &X86::GR8RegClass);
151   addRegisterClass(MVT::i16, &X86::GR16RegClass);
152   addRegisterClass(MVT::i32, &X86::GR32RegClass);
153   if (Subtarget->is64Bit())
154     addRegisterClass(MVT::i64, &X86::GR64RegClass);
155
156   for (MVT VT : MVT::integer_valuetypes())
157     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
158
159   // We don't accept any truncstore of integer registers.
160   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
161   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
162   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
163   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
164   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
165   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
166
167   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
168
169   // SETOEQ and SETUNE require checking two conditions.
170   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
171   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
172   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
173   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
174   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
175   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
176
177   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
178   // operation.
179   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
180   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
181   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
182
183   if (Subtarget->is64Bit()) {
184     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
185     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
186   } else if (!Subtarget->useSoftFloat()) {
187     // We have an algorithm for SSE2->double, and we turn this into a
188     // 64-bit FILD followed by conditional FADD for other targets.
189     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
190     // We have an algorithm for SSE2, and we turn this into a 64-bit
191     // FILD for other targets.
192     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
193   }
194
195   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
196   // this operation.
197   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
198   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
199
200   if (!Subtarget->useSoftFloat()) {
201     // SSE has no i16 to fp conversion, only i32
202     if (X86ScalarSSEf32) {
203       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
204       // f32 and f64 cases are Legal, f80 case is not
205       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
206     } else {
207       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
208       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
209     }
210   } else {
211     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
212     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
213   }
214
215   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
216   // are Legal, f80 is custom lowered.
217   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
218   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
219
220   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
221   // this operation.
222   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
223   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
224
225   if (X86ScalarSSEf32) {
226     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
227     // f32 and f64 cases are Legal, f80 case is not
228     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
229   } else {
230     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
231     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
232   }
233
234   // Handle FP_TO_UINT by promoting the destination to a larger signed
235   // conversion.
236   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
237   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
238   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
239
240   if (Subtarget->is64Bit()) {
241     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
242     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
243   } else if (!Subtarget->useSoftFloat()) {
244     // Since AVX is a superset of SSE3, only check for SSE here.
245     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246       // Expand FP_TO_UINT into a select.
247       // FIXME: We would like to use a Custom expander here eventually to do
248       // the optimal thing for SSE vs. the default expansion in the legalizer.
249       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
250     else
251       // With SSE3 we can use fisttpll to convert to a signed i64; without
252       // SSE, we're stuck with a fistpll.
253       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
254   }
255
256   if (isTargetFTOL()) {
257     // Use the _ftol2 runtime function, which has a pseudo-instruction
258     // to handle its weird calling convention.
259     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
260   }
261
262   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
263   if (!X86ScalarSSEf64) {
264     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
265     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
266     if (Subtarget->is64Bit()) {
267       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
268       // Without SSE, i64->f64 goes through memory.
269       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
270     }
271   }
272
273   // Scalar integer divide and remainder are lowered to use operations that
274   // produce two results, to match the available instructions. This exposes
275   // the two-result form to trivial CSE, which is able to combine x/y and x%y
276   // into a single instruction.
277   //
278   // Scalar integer multiply-high is also lowered to use two-result
279   // operations, to match the available instructions. However, plain multiply
280   // (low) operations are left as Legal, as there are single-result
281   // instructions for this in x86. Using the two-result multiply instructions
282   // when both high and low results are needed must be arranged by dagcombine.
283   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
284     MVT VT = IntVTs[i];
285     setOperationAction(ISD::MULHS, VT, Expand);
286     setOperationAction(ISD::MULHU, VT, Expand);
287     setOperationAction(ISD::SDIV, VT, Expand);
288     setOperationAction(ISD::UDIV, VT, Expand);
289     setOperationAction(ISD::SREM, VT, Expand);
290     setOperationAction(ISD::UREM, VT, Expand);
291
292     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
293     setOperationAction(ISD::ADDC, VT, Custom);
294     setOperationAction(ISD::ADDE, VT, Custom);
295     setOperationAction(ISD::SUBC, VT, Custom);
296     setOperationAction(ISD::SUBE, VT, Custom);
297   }
298
299   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
300   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
301   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
302   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
303   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
304   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
305   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
306   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
307   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
312   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
313   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
314   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
315   if (Subtarget->is64Bit())
316     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
318   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
319   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
320   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
321   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
322   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
323   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
324   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
325
326   // Promote the i8 variants and force them on up to i32 which has a shorter
327   // encoding.
328   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
329   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
330   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
331   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
332   if (Subtarget->hasBMI()) {
333     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
334     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
335     if (Subtarget->is64Bit())
336       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
337   } else {
338     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
339     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
340     if (Subtarget->is64Bit())
341       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
342   }
343
344   if (Subtarget->hasLZCNT()) {
345     // When promoting the i8 variants, force them to i32 for a shorter
346     // encoding.
347     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
348     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
350     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
352     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
353     if (Subtarget->is64Bit())
354       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
355   } else {
356     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
357     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
358     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
361     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
362     if (Subtarget->is64Bit()) {
363       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
364       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
365     }
366   }
367
368   // Special handling for half-precision floating point conversions.
369   // If we don't have F16C support, then lower half float conversions
370   // into library calls.
371   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
372     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
374   }
375
376   // There's never any support for operations beyond MVT::f32.
377   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
381
382   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
388
389   if (Subtarget->hasPOPCNT()) {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
391   } else {
392     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
394     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
397   }
398
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400
401   if (!Subtarget->hasMOVBE())
402     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
403
404   // These should be promoted to a larger select which is supported.
405   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
406   // X86 wants to expand cmov itself.
407   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
408   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
412   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
419   if (Subtarget->is64Bit()) {
420     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
421     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
422   }
423   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
424   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426   // support continuation, user-level threading, and etc.. As a result, no
427   // other SjLj exception interfaces are implemented and please don't build
428   // your own exception handling based on them.
429   // LLVM/Clang supports zero-cost DWARF exception handling.
430   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
432
433   // Darwin ABI issue.
434   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
435   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
436   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
437   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
438   if (Subtarget->is64Bit())
439     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
441   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
442   if (Subtarget->is64Bit()) {
443     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
444     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
445     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
446     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
447     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
448   }
449   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
451   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
452   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
455     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
456     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
457   }
458
459   if (Subtarget->hasSSE1())
460     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
461
462   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
463
464   // Expand certain atomics
465   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
466     MVT VT = IntVTs[i];
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
470   }
471
472   if (Subtarget->hasCmpxchg16b()) {
473     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
474   }
475
476   // FIXME - use subtarget debug flags
477   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
480   }
481
482   if (Subtarget->is64Bit()) {
483     setExceptionPointerRegister(X86::RAX);
484     setExceptionSelectorRegister(X86::RDX);
485   } else {
486     setExceptionPointerRegister(X86::EAX);
487     setExceptionSelectorRegister(X86::EDX);
488   }
489   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
491
492   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
494
495   setOperationAction(ISD::TRAP, MVT::Other, Legal);
496   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
497
498   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
500   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
501   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
502     // TargetInfo::X86_64ABIBuiltinVaList
503     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
505   } else {
506     // TargetInfo::CharPtrBuiltinVaList
507     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
508     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
509   }
510
511   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
512   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
513
514   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
515
516   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
517   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
518   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
519
520   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
521     // f32 and f64 use SSE.
522     // Set up the FP register classes.
523     addRegisterClass(MVT::f32, &X86::FR32RegClass);
524     addRegisterClass(MVT::f64, &X86::FR64RegClass);
525
526     // Use ANDPD to simulate FABS.
527     setOperationAction(ISD::FABS , MVT::f64, Custom);
528     setOperationAction(ISD::FABS , MVT::f32, Custom);
529
530     // Use XORP to simulate FNEG.
531     setOperationAction(ISD::FNEG , MVT::f64, Custom);
532     setOperationAction(ISD::FNEG , MVT::f32, Custom);
533
534     // Use ANDPD and ORPD to simulate FCOPYSIGN.
535     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
536     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
537
538     // Lower this to FGETSIGNx86 plus an AND.
539     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
540     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
541
542     // We don't support sin/cos/fmod
543     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
544     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
545     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
546     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
547     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
548     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
549
550     // Expand FP immediates into loads from the stack, except for the special
551     // cases we handle.
552     addLegalFPImmediate(APFloat(+0.0)); // xorpd
553     addLegalFPImmediate(APFloat(+0.0f)); // xorps
554   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
555     // Use SSE for f32, x87 for f64.
556     // Set up the FP register classes.
557     addRegisterClass(MVT::f32, &X86::FR32RegClass);
558     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
559
560     // Use ANDPS to simulate FABS.
561     setOperationAction(ISD::FABS , MVT::f32, Custom);
562
563     // Use XORP to simulate FNEG.
564     setOperationAction(ISD::FNEG , MVT::f32, Custom);
565
566     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
567
568     // Use ANDPS and ORPS to simulate FCOPYSIGN.
569     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
570     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571
572     // We don't support sin/cos/fmod
573     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
574     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
575     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
576
577     // Special cases we handle for FP constants.
578     addLegalFPImmediate(APFloat(+0.0f)); // xorps
579     addLegalFPImmediate(APFloat(+0.0)); // FLD0
580     addLegalFPImmediate(APFloat(+1.0)); // FLD1
581     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
582     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
583
584     if (!TM.Options.UnsafeFPMath) {
585       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
586       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
587       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
588     }
589   } else if (!Subtarget->useSoftFloat()) {
590     // f32 and f64 in x87.
591     // Set up the FP register classes.
592     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
593     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
594
595     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
596     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
597     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
599
600     if (!TM.Options.UnsafeFPMath) {
601       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
602       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
603       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
604       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
605       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
606       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
607     }
608     addLegalFPImmediate(APFloat(+0.0)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
612     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
613     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
614     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
615     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
616   }
617
618   // We don't support FMA.
619   setOperationAction(ISD::FMA, MVT::f64, Expand);
620   setOperationAction(ISD::FMA, MVT::f32, Expand);
621
622   // Long double always uses X87.
623   if (!Subtarget->useSoftFloat()) {
624     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
625     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
626     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
627     {
628       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
629       addLegalFPImmediate(TmpFlt);  // FLD0
630       TmpFlt.changeSign();
631       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
632
633       bool ignored;
634       APFloat TmpFlt2(+1.0);
635       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
636                       &ignored);
637       addLegalFPImmediate(TmpFlt2);  // FLD1
638       TmpFlt2.changeSign();
639       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
640     }
641
642     if (!TM.Options.UnsafeFPMath) {
643       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
644       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
645       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
646     }
647
648     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
649     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
650     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
651     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
652     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
653     setOperationAction(ISD::FMA, MVT::f80, Expand);
654   }
655
656   // Always use a library call for pow.
657   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
658   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
659   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
660
661   setOperationAction(ISD::FLOG, MVT::f80, Expand);
662   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
663   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
664   setOperationAction(ISD::FEXP, MVT::f80, Expand);
665   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
666   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
667   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
668
669   // First set operation action for all vector types to either promote
670   // (for widening) or expand (for scalarization). Then we will selectively
671   // turn on ones that can be effectively codegen'd.
672   for (MVT VT : MVT::vector_valuetypes()) {
673     setOperationAction(ISD::ADD , VT, Expand);
674     setOperationAction(ISD::SUB , VT, Expand);
675     setOperationAction(ISD::FADD, VT, Expand);
676     setOperationAction(ISD::FNEG, VT, Expand);
677     setOperationAction(ISD::FSUB, VT, Expand);
678     setOperationAction(ISD::MUL , VT, Expand);
679     setOperationAction(ISD::FMUL, VT, Expand);
680     setOperationAction(ISD::SDIV, VT, Expand);
681     setOperationAction(ISD::UDIV, VT, Expand);
682     setOperationAction(ISD::FDIV, VT, Expand);
683     setOperationAction(ISD::SREM, VT, Expand);
684     setOperationAction(ISD::UREM, VT, Expand);
685     setOperationAction(ISD::LOAD, VT, Expand);
686     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
687     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
688     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
689     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
690     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
691     setOperationAction(ISD::FABS, VT, Expand);
692     setOperationAction(ISD::FSIN, VT, Expand);
693     setOperationAction(ISD::FSINCOS, VT, Expand);
694     setOperationAction(ISD::FCOS, VT, Expand);
695     setOperationAction(ISD::FSINCOS, VT, Expand);
696     setOperationAction(ISD::FREM, VT, Expand);
697     setOperationAction(ISD::FMA,  VT, Expand);
698     setOperationAction(ISD::FPOWI, VT, Expand);
699     setOperationAction(ISD::FSQRT, VT, Expand);
700     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
701     setOperationAction(ISD::FFLOOR, VT, Expand);
702     setOperationAction(ISD::FCEIL, VT, Expand);
703     setOperationAction(ISD::FTRUNC, VT, Expand);
704     setOperationAction(ISD::FRINT, VT, Expand);
705     setOperationAction(ISD::FNEARBYINT, VT, Expand);
706     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
707     setOperationAction(ISD::MULHS, VT, Expand);
708     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
709     setOperationAction(ISD::MULHU, VT, Expand);
710     setOperationAction(ISD::SDIVREM, VT, Expand);
711     setOperationAction(ISD::UDIVREM, VT, Expand);
712     setOperationAction(ISD::FPOW, VT, Expand);
713     setOperationAction(ISD::CTPOP, VT, Expand);
714     setOperationAction(ISD::CTTZ, VT, Expand);
715     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
716     setOperationAction(ISD::CTLZ, VT, Expand);
717     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
718     setOperationAction(ISD::SHL, VT, Expand);
719     setOperationAction(ISD::SRA, VT, Expand);
720     setOperationAction(ISD::SRL, VT, Expand);
721     setOperationAction(ISD::ROTL, VT, Expand);
722     setOperationAction(ISD::ROTR, VT, Expand);
723     setOperationAction(ISD::BSWAP, VT, Expand);
724     setOperationAction(ISD::SETCC, VT, Expand);
725     setOperationAction(ISD::FLOG, VT, Expand);
726     setOperationAction(ISD::FLOG2, VT, Expand);
727     setOperationAction(ISD::FLOG10, VT, Expand);
728     setOperationAction(ISD::FEXP, VT, Expand);
729     setOperationAction(ISD::FEXP2, VT, Expand);
730     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
731     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
732     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
733     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
734     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
735     setOperationAction(ISD::TRUNCATE, VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
737     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
738     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
739     setOperationAction(ISD::VSELECT, VT, Expand);
740     setOperationAction(ISD::SELECT_CC, VT, Expand);
741     for (MVT InnerVT : MVT::vector_valuetypes()) {
742       setTruncStoreAction(InnerVT, VT, Expand);
743
744       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
745       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
746
747       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
748       // types, we have to deal with them whether we ask for Expansion or not.
749       // Setting Expand causes its own optimisation problems though, so leave
750       // them legal.
751       if (VT.getVectorElementType() == MVT::i1)
752         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
753
754       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
755       // split/scalarized right now.
756       if (VT.getVectorElementType() == MVT::f16)
757         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
758     }
759   }
760
761   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
762   // with -msoft-float, disable use of MMX as well.
763   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
764     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
765     // No operations on x86mmx supported, everything uses intrinsics.
766   }
767
768   // MMX-sized vectors (other than x86mmx) are expected to be expanded
769   // into smaller operations.
770   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
771     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
772     setOperationAction(ISD::AND,                MMXTy,      Expand);
773     setOperationAction(ISD::OR,                 MMXTy,      Expand);
774     setOperationAction(ISD::XOR,                MMXTy,      Expand);
775     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
776     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
777     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
778   }
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780
781   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
782     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
783
784     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
786     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
787     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
788     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
789     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
790     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
791     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
792     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
793     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
794     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
795     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
796     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
797     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
798   }
799
800   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
801     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
802
803     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
804     // registers cannot be used even for integer operations.
805     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
806     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
807     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
808     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
809
810     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
811     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
812     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
813     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
814     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
815     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
816     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
817     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
818     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
819     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
820     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
833
834     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
837     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
838
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
840     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
844
845     // Only provide customized ctpop vector bit twiddling for vector types we
846     // know to perform better than using the popcnt instructions on each vector
847     // element. If popcnt isn't supported, always provide the custom version.
848     if (!Subtarget->hasPOPCNT()) {
849       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
850       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
851     }
852
853     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
854     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
855       MVT VT = (MVT::SimpleValueType)i;
856       // Do not attempt to custom lower non-power-of-2 vectors
857       if (!isPowerOf2_32(VT.getVectorNumElements()))
858         continue;
859       // Do not attempt to custom lower non-128-bit vectors
860       if (!VT.is128BitVector())
861         continue;
862       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
863       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
864       setOperationAction(ISD::VSELECT,            VT, Custom);
865       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
866     }
867
868     // We support custom legalizing of sext and anyext loads for specific
869     // memory vector types which we can load as a scalar (or sequence of
870     // scalars) and extend in-register to a legal 128-bit vector type. For sext
871     // loads these must work with a single scalar load.
872     for (MVT VT : MVT::integer_vector_valuetypes()) {
873       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
874       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
875       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
878       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
879       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
880       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
881       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
882     }
883
884     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
885     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
887     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
888     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
889     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
891     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
892
893     if (Subtarget->is64Bit()) {
894       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
895       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
896     }
897
898     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
899     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
900       MVT VT = (MVT::SimpleValueType)i;
901
902       // Do not attempt to promote non-128-bit vectors
903       if (!VT.is128BitVector())
904         continue;
905
906       setOperationAction(ISD::AND,    VT, Promote);
907       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
908       setOperationAction(ISD::OR,     VT, Promote);
909       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
910       setOperationAction(ISD::XOR,    VT, Promote);
911       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
912       setOperationAction(ISD::LOAD,   VT, Promote);
913       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
914       setOperationAction(ISD::SELECT, VT, Promote);
915       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
916     }
917
918     // Custom lower v2i64 and v2f64 selects.
919     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
920     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
921     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
922     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
923
924     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
925     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
926
927     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
928     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
929     // As there is no 64-bit GPR available, we need build a special custom
930     // sequence to convert from v2i32 to v2f32.
931     if (!Subtarget->is64Bit())
932       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
933
934     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
935     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
936
937     for (MVT VT : MVT::fp_vector_valuetypes())
938       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
939
940     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
941     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
942     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
943   }
944
945   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
946     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
947       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
948       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
949       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
950       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
951       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
952     }
953
954     // FIXME: Do we need to handle scalar-to-vector here?
955     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
956
957     // We directly match byte blends in the backend as they match the VSELECT
958     // condition form.
959     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
960
961     // SSE41 brings specific instructions for doing vector sign extend even in
962     // cases where we don't have SRA.
963     for (MVT VT : MVT::integer_vector_valuetypes()) {
964       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
965       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
966       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
967     }
968
969     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
970     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
971     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
972     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
973     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
974     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
975     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
976
977     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     // i8 and i16 vectors are custom because the source register and source
985     // source memory operand types are not the same width.  f32 vectors are
986     // custom since the immediate controlling the insert encodes additional
987     // information.
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
989     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
990     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
992
993     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
994     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
995     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
996     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
997
998     // FIXME: these should be Legal, but that's only for the case where
999     // the index is constant.  For now custom expand to deal with that.
1000     if (Subtarget->is64Bit()) {
1001       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1002       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1003     }
1004   }
1005
1006   if (Subtarget->hasSSE2()) {
1007     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1008     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1009
1010     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1011     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1012
1013     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1014     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1015
1016     // In the customized shift lowering, the legal cases in AVX2 will be
1017     // recognized.
1018     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1019     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1020
1021     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1022     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1023
1024     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1025   }
1026
1027   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1028     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1029     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1030     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1031     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1032     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1033     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1034
1035     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1036     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1037     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1038
1039     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1040     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1041     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1042     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1043     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1044     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1045     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1046     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1047     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1048     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1049     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1050     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1051
1052     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1053     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1054     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1055     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1056     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1057     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1058     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1059     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1060     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1061     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1062     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1063     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1064
1065     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1066     // even though v8i16 is a legal type.
1067     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1068     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1069     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1070
1071     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1072     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1073     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1074
1075     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1076     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1077
1078     for (MVT VT : MVT::fp_vector_valuetypes())
1079       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1080
1081     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1082     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1083
1084     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1085     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1086
1087     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1088     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1089
1090     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1091     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1092     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1093     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1094
1095     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1096     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1097     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1098
1099     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1100     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1101     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1102     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1103     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1104     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1105     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1106     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1107     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1108     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1109     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1110     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1111
1112     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1113       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1114       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1115       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1116       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1117       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1118       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1119     }
1120
1121     if (Subtarget->hasInt256()) {
1122       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1123       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1124       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1125       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1126
1127       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1128       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1129       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1130       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1131
1132       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1133       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1134       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1135       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1136
1137       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1138       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1139       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1140       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1141
1142       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1143       // when we have a 256bit-wide blend with immediate.
1144       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1145
1146       // Only provide customized ctpop vector bit twiddling for vector types we
1147       // know to perform better than using the popcnt instructions on each
1148       // vector element. If popcnt isn't supported, always provide the custom
1149       // version.
1150       if (!Subtarget->hasPOPCNT())
1151         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1152
1153       // Custom CTPOP always performs better on natively supported v8i32
1154       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1155
1156       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1157       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1158       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1159       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1160       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1161       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1162       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1163
1164       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1165       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1166       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1167       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1168       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1169       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1170     } else {
1171       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1172       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1173       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1174       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1175
1176       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1177       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1178       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1179       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1180
1181       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1182       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1183       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1184       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1185     }
1186
1187     // In the customized shift lowering, the legal cases in AVX2 will be
1188     // recognized.
1189     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1190     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1191
1192     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1193     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1194
1195     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1196
1197     // Custom lower several nodes for 256-bit types.
1198     for (MVT VT : MVT::vector_valuetypes()) {
1199       if (VT.getScalarSizeInBits() >= 32) {
1200         setOperationAction(ISD::MLOAD,  VT, Legal);
1201         setOperationAction(ISD::MSTORE, VT, Legal);
1202       }
1203       // Extract subvector is special because the value type
1204       // (result) is 128-bit but the source is 256-bit wide.
1205       if (VT.is128BitVector()) {
1206         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1207       }
1208       // Do not attempt to custom lower other non-256-bit vectors
1209       if (!VT.is256BitVector())
1210         continue;
1211
1212       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1213       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1214       setOperationAction(ISD::VSELECT,            VT, Custom);
1215       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1216       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1217       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1218       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1219       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1220     }
1221
1222     if (Subtarget->hasInt256())
1223       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1224
1225
1226     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1227     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1228       MVT VT = (MVT::SimpleValueType)i;
1229
1230       // Do not attempt to promote non-256-bit vectors
1231       if (!VT.is256BitVector())
1232         continue;
1233
1234       setOperationAction(ISD::AND,    VT, Promote);
1235       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1236       setOperationAction(ISD::OR,     VT, Promote);
1237       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1238       setOperationAction(ISD::XOR,    VT, Promote);
1239       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1240       setOperationAction(ISD::LOAD,   VT, Promote);
1241       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1242       setOperationAction(ISD::SELECT, VT, Promote);
1243       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1244     }
1245   }
1246
1247   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1248     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1249     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1250     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1251     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1252
1253     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1254     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1255     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1256
1257     for (MVT VT : MVT::fp_vector_valuetypes())
1258       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1259
1260     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1261     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1262     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1263     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1264     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1265     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1266     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1267     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1268     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1269     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1270
1271     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1272     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1273     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1274     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1275     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1276     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1277
1278     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1279     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1280     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1281     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1282     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1283     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1284     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1285     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1286
1287     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1288     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1289     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1290     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1291     if (Subtarget->is64Bit()) {
1292       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1293       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1294       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1295       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1296     }
1297     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1298     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1299     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1300     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1301     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1302     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1303     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1304     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1305     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1306     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1307     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1308     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1309     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1310     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1311     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1312     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1313
1314     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1315     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1316     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1317     if (Subtarget->hasDQI()) {
1318       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1319       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1320     }
1321     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1322     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1323     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1324     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1325     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1326     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1327     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1328     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1329     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1330     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1331     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1332     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1333     if (Subtarget->hasDQI()) {
1334       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1335       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1336     }
1337     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1338     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1339     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1340     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1341     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1342     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1343     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1344     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1345     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1346     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1347
1348     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1349     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1350     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1351     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1352     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1353
1354     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1355     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1356
1357     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1358
1359     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1360     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1361     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1362     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1363     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1364     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1365     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1366     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1367     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1368     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1369     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1370
1371     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1372     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1373
1374     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1375     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1376
1377     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1378
1379     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1380     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1381
1382     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1383     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1384
1385     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1386     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1387
1388     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1389     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1390     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1391     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1392     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1393     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1394
1395     if (Subtarget->hasCDI()) {
1396       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1397       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1398     }
1399     if (Subtarget->hasDQI()) {
1400       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1401       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1402       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1403     }
1404     // Custom lower several nodes.
1405     for (MVT VT : MVT::vector_valuetypes()) {
1406       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1407       if (EltSize == 1) {
1408         setOperationAction(ISD::AND, VT, Legal);
1409         setOperationAction(ISD::OR,  VT, Legal);
1410         setOperationAction(ISD::XOR,  VT, Legal);
1411       }
1412       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1413         setOperationAction(ISD::MGATHER,  VT, Custom);
1414         setOperationAction(ISD::MSCATTER, VT, Custom);
1415       }
1416       // Extract subvector is special because the value type
1417       // (result) is 256/128-bit but the source is 512-bit wide.
1418       if (VT.is128BitVector() || VT.is256BitVector()) {
1419         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1420       }
1421       if (VT.getVectorElementType() == MVT::i1)
1422         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1423
1424       // Do not attempt to custom lower other non-512-bit vectors
1425       if (!VT.is512BitVector())
1426         continue;
1427
1428       if (EltSize >= 32) {
1429         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1430         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1431         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1432         setOperationAction(ISD::VSELECT,             VT, Legal);
1433         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1434         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1435         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1436         setOperationAction(ISD::MLOAD,               VT, Legal);
1437         setOperationAction(ISD::MSTORE,              VT, Legal);
1438       }
1439     }
1440     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1441       MVT VT = (MVT::SimpleValueType)i;
1442
1443       // Do not attempt to promote non-512-bit vectors.
1444       if (!VT.is512BitVector())
1445         continue;
1446
1447       setOperationAction(ISD::SELECT, VT, Promote);
1448       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1449     }
1450   }// has  AVX-512
1451
1452   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1453     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1454     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1455
1456     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1457     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1458
1459     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1460     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1461     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1462     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1463     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1464     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1465     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1466     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1467     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1468     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1469     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1470     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1471     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1472     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1473     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1474     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1475     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1476     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1477     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1478
1479     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1480       const MVT VT = (MVT::SimpleValueType)i;
1481
1482       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1483
1484       // Do not attempt to promote non-512-bit vectors.
1485       if (!VT.is512BitVector())
1486         continue;
1487
1488       if (EltSize < 32) {
1489         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1490         setOperationAction(ISD::VSELECT,             VT, Legal);
1491       }
1492     }
1493   }
1494
1495   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1496     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1497     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1498
1499     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1500     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1501     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1502     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1503     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1504     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1505     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1506     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1507     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1508     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1509
1510     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1511     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1512     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1513     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1514     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1515     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1516     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1517     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1518   }
1519
1520   // We want to custom lower some of our intrinsics.
1521   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1522   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1523   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1524   if (!Subtarget->is64Bit())
1525     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1526
1527   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1528   // handle type legalization for these operations here.
1529   //
1530   // FIXME: We really should do custom legalization for addition and
1531   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1532   // than generic legalization for 64-bit multiplication-with-overflow, though.
1533   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1534     // Add/Sub/Mul with overflow operations are custom lowered.
1535     MVT VT = IntVTs[i];
1536     setOperationAction(ISD::SADDO, VT, Custom);
1537     setOperationAction(ISD::UADDO, VT, Custom);
1538     setOperationAction(ISD::SSUBO, VT, Custom);
1539     setOperationAction(ISD::USUBO, VT, Custom);
1540     setOperationAction(ISD::SMULO, VT, Custom);
1541     setOperationAction(ISD::UMULO, VT, Custom);
1542   }
1543
1544
1545   if (!Subtarget->is64Bit()) {
1546     // These libcalls are not available in 32-bit.
1547     setLibcallName(RTLIB::SHL_I128, nullptr);
1548     setLibcallName(RTLIB::SRL_I128, nullptr);
1549     setLibcallName(RTLIB::SRA_I128, nullptr);
1550   }
1551
1552   // Combine sin / cos into one node or libcall if possible.
1553   if (Subtarget->hasSinCos()) {
1554     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1555     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1556     if (Subtarget->isTargetDarwin()) {
1557       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1558       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1559       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1560       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1561     }
1562   }
1563
1564   if (Subtarget->isTargetWin64()) {
1565     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1566     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1567     setOperationAction(ISD::SREM, MVT::i128, Custom);
1568     setOperationAction(ISD::UREM, MVT::i128, Custom);
1569     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1570     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1571   }
1572
1573   // We have target-specific dag combine patterns for the following nodes:
1574   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1575   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1576   setTargetDAGCombine(ISD::BITCAST);
1577   setTargetDAGCombine(ISD::VSELECT);
1578   setTargetDAGCombine(ISD::SELECT);
1579   setTargetDAGCombine(ISD::SHL);
1580   setTargetDAGCombine(ISD::SRA);
1581   setTargetDAGCombine(ISD::SRL);
1582   setTargetDAGCombine(ISD::OR);
1583   setTargetDAGCombine(ISD::AND);
1584   setTargetDAGCombine(ISD::ADD);
1585   setTargetDAGCombine(ISD::FADD);
1586   setTargetDAGCombine(ISD::FSUB);
1587   setTargetDAGCombine(ISD::FMA);
1588   setTargetDAGCombine(ISD::SUB);
1589   setTargetDAGCombine(ISD::LOAD);
1590   setTargetDAGCombine(ISD::MLOAD);
1591   setTargetDAGCombine(ISD::STORE);
1592   setTargetDAGCombine(ISD::MSTORE);
1593   setTargetDAGCombine(ISD::ZERO_EXTEND);
1594   setTargetDAGCombine(ISD::ANY_EXTEND);
1595   setTargetDAGCombine(ISD::SIGN_EXTEND);
1596   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1597   setTargetDAGCombine(ISD::SINT_TO_FP);
1598   setTargetDAGCombine(ISD::SETCC);
1599   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1600   setTargetDAGCombine(ISD::BUILD_VECTOR);
1601   setTargetDAGCombine(ISD::MUL);
1602   setTargetDAGCombine(ISD::XOR);
1603
1604   computeRegisterProperties(Subtarget->getRegisterInfo());
1605
1606   // On Darwin, -Os means optimize for size without hurting performance,
1607   // do not reduce the limit.
1608   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1609   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1610   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1611   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1612   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1613   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1614   setPrefLoopAlignment(4); // 2^4 bytes.
1615
1616   // Predictable cmov don't hurt on atom because it's in-order.
1617   PredictableSelectIsExpensive = !Subtarget->isAtom();
1618   EnableExtLdPromotion = true;
1619   setPrefFunctionAlignment(4); // 2^4 bytes.
1620
1621   verifyIntrinsicTables();
1622 }
1623
1624 // This has so far only been implemented for 64-bit MachO.
1625 bool X86TargetLowering::useLoadStackGuardNode() const {
1626   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1627 }
1628
1629 TargetLoweringBase::LegalizeTypeAction
1630 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1631   if (ExperimentalVectorWideningLegalization &&
1632       VT.getVectorNumElements() != 1 &&
1633       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1634     return TypeWidenVector;
1635
1636   return TargetLoweringBase::getPreferredVectorAction(VT);
1637 }
1638
1639 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1640   if (!VT.isVector())
1641     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1642
1643   const unsigned NumElts = VT.getVectorNumElements();
1644   const EVT EltVT = VT.getVectorElementType();
1645   if (VT.is512BitVector()) {
1646     if (Subtarget->hasAVX512())
1647       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1648           EltVT == MVT::f32 || EltVT == MVT::f64)
1649         switch(NumElts) {
1650         case  8: return MVT::v8i1;
1651         case 16: return MVT::v16i1;
1652       }
1653     if (Subtarget->hasBWI())
1654       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1655         switch(NumElts) {
1656         case 32: return MVT::v32i1;
1657         case 64: return MVT::v64i1;
1658       }
1659   }
1660
1661   if (VT.is256BitVector() || VT.is128BitVector()) {
1662     if (Subtarget->hasVLX())
1663       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1664           EltVT == MVT::f32 || EltVT == MVT::f64)
1665         switch(NumElts) {
1666         case 2: return MVT::v2i1;
1667         case 4: return MVT::v4i1;
1668         case 8: return MVT::v8i1;
1669       }
1670     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1671       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1672         switch(NumElts) {
1673         case  8: return MVT::v8i1;
1674         case 16: return MVT::v16i1;
1675         case 32: return MVT::v32i1;
1676       }
1677   }
1678
1679   return VT.changeVectorElementTypeToInteger();
1680 }
1681
1682 /// Helper for getByValTypeAlignment to determine
1683 /// the desired ByVal argument alignment.
1684 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1685   if (MaxAlign == 16)
1686     return;
1687   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1688     if (VTy->getBitWidth() == 128)
1689       MaxAlign = 16;
1690   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1691     unsigned EltAlign = 0;
1692     getMaxByValAlign(ATy->getElementType(), EltAlign);
1693     if (EltAlign > MaxAlign)
1694       MaxAlign = EltAlign;
1695   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1696     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1697       unsigned EltAlign = 0;
1698       getMaxByValAlign(STy->getElementType(i), EltAlign);
1699       if (EltAlign > MaxAlign)
1700         MaxAlign = EltAlign;
1701       if (MaxAlign == 16)
1702         break;
1703     }
1704   }
1705 }
1706
1707 /// Return the desired alignment for ByVal aggregate
1708 /// function arguments in the caller parameter area. For X86, aggregates
1709 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1710 /// are at 4-byte boundaries.
1711 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1712   if (Subtarget->is64Bit()) {
1713     // Max of 8 and alignment of type.
1714     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1715     if (TyAlign > 8)
1716       return TyAlign;
1717     return 8;
1718   }
1719
1720   unsigned Align = 4;
1721   if (Subtarget->hasSSE1())
1722     getMaxByValAlign(Ty, Align);
1723   return Align;
1724 }
1725
1726 /// Returns the target specific optimal type for load
1727 /// and store operations as a result of memset, memcpy, and memmove
1728 /// lowering. If DstAlign is zero that means it's safe to destination
1729 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1730 /// means there isn't a need to check it against alignment requirement,
1731 /// probably because the source does not need to be loaded. If 'IsMemset' is
1732 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1733 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1734 /// source is constant so it does not need to be loaded.
1735 /// It returns EVT::Other if the type should be determined using generic
1736 /// target-independent logic.
1737 EVT
1738 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1739                                        unsigned DstAlign, unsigned SrcAlign,
1740                                        bool IsMemset, bool ZeroMemset,
1741                                        bool MemcpyStrSrc,
1742                                        MachineFunction &MF) const {
1743   const Function *F = MF.getFunction();
1744   if ((!IsMemset || ZeroMemset) &&
1745       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1746     if (Size >= 16 &&
1747         (Subtarget->isUnalignedMemAccessFast() ||
1748          ((DstAlign == 0 || DstAlign >= 16) &&
1749           (SrcAlign == 0 || SrcAlign >= 16)))) {
1750       if (Size >= 32) {
1751         if (Subtarget->hasInt256())
1752           return MVT::v8i32;
1753         if (Subtarget->hasFp256())
1754           return MVT::v8f32;
1755       }
1756       if (Subtarget->hasSSE2())
1757         return MVT::v4i32;
1758       if (Subtarget->hasSSE1())
1759         return MVT::v4f32;
1760     } else if (!MemcpyStrSrc && Size >= 8 &&
1761                !Subtarget->is64Bit() &&
1762                Subtarget->hasSSE2()) {
1763       // Do not use f64 to lower memcpy if source is string constant. It's
1764       // better to use i32 to avoid the loads.
1765       return MVT::f64;
1766     }
1767   }
1768   if (Subtarget->is64Bit() && Size >= 8)
1769     return MVT::i64;
1770   return MVT::i32;
1771 }
1772
1773 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1774   if (VT == MVT::f32)
1775     return X86ScalarSSEf32;
1776   else if (VT == MVT::f64)
1777     return X86ScalarSSEf64;
1778   return true;
1779 }
1780
1781 bool
1782 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1783                                                   unsigned,
1784                                                   unsigned,
1785                                                   bool *Fast) const {
1786   if (Fast)
1787     *Fast = Subtarget->isUnalignedMemAccessFast();
1788   return true;
1789 }
1790
1791 /// Return the entry encoding for a jump table in the
1792 /// current function.  The returned value is a member of the
1793 /// MachineJumpTableInfo::JTEntryKind enum.
1794 unsigned X86TargetLowering::getJumpTableEncoding() const {
1795   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1796   // symbol.
1797   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1798       Subtarget->isPICStyleGOT())
1799     return MachineJumpTableInfo::EK_Custom32;
1800
1801   // Otherwise, use the normal jump table encoding heuristics.
1802   return TargetLowering::getJumpTableEncoding();
1803 }
1804
1805 bool X86TargetLowering::useSoftFloat() const {
1806   return Subtarget->useSoftFloat();
1807 }
1808
1809 const MCExpr *
1810 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1811                                              const MachineBasicBlock *MBB,
1812                                              unsigned uid,MCContext &Ctx) const{
1813   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1814          Subtarget->isPICStyleGOT());
1815   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1816   // entries.
1817   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1818                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1819 }
1820
1821 /// Returns relocation base for the given PIC jumptable.
1822 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1823                                                     SelectionDAG &DAG) const {
1824   if (!Subtarget->is64Bit())
1825     // This doesn't have SDLoc associated with it, but is not really the
1826     // same as a Register.
1827     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1828   return Table;
1829 }
1830
1831 /// This returns the relocation base for the given PIC jumptable,
1832 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1833 const MCExpr *X86TargetLowering::
1834 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1835                              MCContext &Ctx) const {
1836   // X86-64 uses RIP relative addressing based on the jump table label.
1837   if (Subtarget->isPICStyleRIPRel())
1838     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1839
1840   // Otherwise, the reference is relative to the PIC base.
1841   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1842 }
1843
1844 std::pair<const TargetRegisterClass *, uint8_t>
1845 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1846                                            MVT VT) const {
1847   const TargetRegisterClass *RRC = nullptr;
1848   uint8_t Cost = 1;
1849   switch (VT.SimpleTy) {
1850   default:
1851     return TargetLowering::findRepresentativeClass(TRI, VT);
1852   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1853     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1854     break;
1855   case MVT::x86mmx:
1856     RRC = &X86::VR64RegClass;
1857     break;
1858   case MVT::f32: case MVT::f64:
1859   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1860   case MVT::v4f32: case MVT::v2f64:
1861   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1862   case MVT::v4f64:
1863     RRC = &X86::VR128RegClass;
1864     break;
1865   }
1866   return std::make_pair(RRC, Cost);
1867 }
1868
1869 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1870                                                unsigned &Offset) const {
1871   if (!Subtarget->isTargetLinux())
1872     return false;
1873
1874   if (Subtarget->is64Bit()) {
1875     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1876     Offset = 0x28;
1877     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1878       AddressSpace = 256;
1879     else
1880       AddressSpace = 257;
1881   } else {
1882     // %gs:0x14 on i386
1883     Offset = 0x14;
1884     AddressSpace = 256;
1885   }
1886   return true;
1887 }
1888
1889 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1890                                             unsigned DestAS) const {
1891   assert(SrcAS != DestAS && "Expected different address spaces!");
1892
1893   return SrcAS < 256 && DestAS < 256;
1894 }
1895
1896 //===----------------------------------------------------------------------===//
1897 //               Return Value Calling Convention Implementation
1898 //===----------------------------------------------------------------------===//
1899
1900 #include "X86GenCallingConv.inc"
1901
1902 bool
1903 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1904                                   MachineFunction &MF, bool isVarArg,
1905                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1906                         LLVMContext &Context) const {
1907   SmallVector<CCValAssign, 16> RVLocs;
1908   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1909   return CCInfo.CheckReturn(Outs, RetCC_X86);
1910 }
1911
1912 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1913   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1914   return ScratchRegs;
1915 }
1916
1917 SDValue
1918 X86TargetLowering::LowerReturn(SDValue Chain,
1919                                CallingConv::ID CallConv, bool isVarArg,
1920                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1921                                const SmallVectorImpl<SDValue> &OutVals,
1922                                SDLoc dl, SelectionDAG &DAG) const {
1923   MachineFunction &MF = DAG.getMachineFunction();
1924   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1925
1926   SmallVector<CCValAssign, 16> RVLocs;
1927   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1928   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1929
1930   SDValue Flag;
1931   SmallVector<SDValue, 6> RetOps;
1932   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1933   // Operand #1 = Bytes To Pop
1934   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1935                    MVT::i16));
1936
1937   // Copy the result values into the output registers.
1938   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1939     CCValAssign &VA = RVLocs[i];
1940     assert(VA.isRegLoc() && "Can only return in registers!");
1941     SDValue ValToCopy = OutVals[i];
1942     EVT ValVT = ValToCopy.getValueType();
1943
1944     // Promote values to the appropriate types.
1945     if (VA.getLocInfo() == CCValAssign::SExt)
1946       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1947     else if (VA.getLocInfo() == CCValAssign::ZExt)
1948       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1949     else if (VA.getLocInfo() == CCValAssign::AExt) {
1950       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
1951         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1952       else
1953         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1954     }
1955     else if (VA.getLocInfo() == CCValAssign::BCvt)
1956       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1957
1958     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1959            "Unexpected FP-extend for return value.");
1960
1961     // If this is x86-64, and we disabled SSE, we can't return FP values,
1962     // or SSE or MMX vectors.
1963     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1964          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1965           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1966       report_fatal_error("SSE register return with SSE disabled");
1967     }
1968     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1969     // llvm-gcc has never done it right and no one has noticed, so this
1970     // should be OK for now.
1971     if (ValVT == MVT::f64 &&
1972         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1973       report_fatal_error("SSE2 register return with SSE2 disabled");
1974
1975     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1976     // the RET instruction and handled by the FP Stackifier.
1977     if (VA.getLocReg() == X86::FP0 ||
1978         VA.getLocReg() == X86::FP1) {
1979       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1980       // change the value to the FP stack register class.
1981       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1982         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1983       RetOps.push_back(ValToCopy);
1984       // Don't emit a copytoreg.
1985       continue;
1986     }
1987
1988     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1989     // which is returned in RAX / RDX.
1990     if (Subtarget->is64Bit()) {
1991       if (ValVT == MVT::x86mmx) {
1992         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1993           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1994           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1995                                   ValToCopy);
1996           // If we don't have SSE2 available, convert to v4f32 so the generated
1997           // register is legal.
1998           if (!Subtarget->hasSSE2())
1999             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2000         }
2001       }
2002     }
2003
2004     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2005     Flag = Chain.getValue(1);
2006     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2007   }
2008
2009   // All x86 ABIs require that for returning structs by value we copy
2010   // the sret argument into %rax/%eax (depending on ABI) for the return.
2011   // We saved the argument into a virtual register in the entry block,
2012   // so now we copy the value out and into %rax/%eax.
2013   //
2014   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2015   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2016   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2017   // either case FuncInfo->setSRetReturnReg() will have been called.
2018   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2019     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2020
2021     unsigned RetValReg
2022         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2023           X86::RAX : X86::EAX;
2024     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2025     Flag = Chain.getValue(1);
2026
2027     // RAX/EAX now acts like a return value.
2028     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2029   }
2030
2031   RetOps[0] = Chain;  // Update chain.
2032
2033   // Add the flag if we have it.
2034   if (Flag.getNode())
2035     RetOps.push_back(Flag);
2036
2037   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2038 }
2039
2040 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2041   if (N->getNumValues() != 1)
2042     return false;
2043   if (!N->hasNUsesOfValue(1, 0))
2044     return false;
2045
2046   SDValue TCChain = Chain;
2047   SDNode *Copy = *N->use_begin();
2048   if (Copy->getOpcode() == ISD::CopyToReg) {
2049     // If the copy has a glue operand, we conservatively assume it isn't safe to
2050     // perform a tail call.
2051     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2052       return false;
2053     TCChain = Copy->getOperand(0);
2054   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2055     return false;
2056
2057   bool HasRet = false;
2058   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2059        UI != UE; ++UI) {
2060     if (UI->getOpcode() != X86ISD::RET_FLAG)
2061       return false;
2062     // If we are returning more than one value, we can definitely
2063     // not make a tail call see PR19530
2064     if (UI->getNumOperands() > 4)
2065       return false;
2066     if (UI->getNumOperands() == 4 &&
2067         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2068       return false;
2069     HasRet = true;
2070   }
2071
2072   if (!HasRet)
2073     return false;
2074
2075   Chain = TCChain;
2076   return true;
2077 }
2078
2079 EVT
2080 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2081                                             ISD::NodeType ExtendKind) const {
2082   MVT ReturnMVT;
2083   // TODO: Is this also valid on 32-bit?
2084   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2085     ReturnMVT = MVT::i8;
2086   else
2087     ReturnMVT = MVT::i32;
2088
2089   EVT MinVT = getRegisterType(Context, ReturnMVT);
2090   return VT.bitsLT(MinVT) ? MinVT : VT;
2091 }
2092
2093 /// Lower the result values of a call into the
2094 /// appropriate copies out of appropriate physical registers.
2095 ///
2096 SDValue
2097 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2098                                    CallingConv::ID CallConv, bool isVarArg,
2099                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2100                                    SDLoc dl, SelectionDAG &DAG,
2101                                    SmallVectorImpl<SDValue> &InVals) const {
2102
2103   // Assign locations to each value returned by this call.
2104   SmallVector<CCValAssign, 16> RVLocs;
2105   bool Is64Bit = Subtarget->is64Bit();
2106   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2107                  *DAG.getContext());
2108   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2109
2110   // Copy all of the result registers out of their specified physreg.
2111   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2112     CCValAssign &VA = RVLocs[i];
2113     EVT CopyVT = VA.getLocVT();
2114
2115     // If this is x86-64, and we disabled SSE, we can't return FP values
2116     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2117         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2118       report_fatal_error("SSE register return with SSE disabled");
2119     }
2120
2121     // If we prefer to use the value in xmm registers, copy it out as f80 and
2122     // use a truncate to move it from fp stack reg to xmm reg.
2123     bool RoundAfterCopy = false;
2124     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2125         isScalarFPTypeInSSEReg(VA.getValVT())) {
2126       CopyVT = MVT::f80;
2127       RoundAfterCopy = (CopyVT != VA.getLocVT());
2128     }
2129
2130     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2131                                CopyVT, InFlag).getValue(1);
2132     SDValue Val = Chain.getValue(0);
2133
2134     if (RoundAfterCopy)
2135       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2136                         // This truncation won't change the value.
2137                         DAG.getIntPtrConstant(1, dl));
2138
2139     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2140       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2141
2142     InFlag = Chain.getValue(2);
2143     InVals.push_back(Val);
2144   }
2145
2146   return Chain;
2147 }
2148
2149 //===----------------------------------------------------------------------===//
2150 //                C & StdCall & Fast Calling Convention implementation
2151 //===----------------------------------------------------------------------===//
2152 //  StdCall calling convention seems to be standard for many Windows' API
2153 //  routines and around. It differs from C calling convention just a little:
2154 //  callee should clean up the stack, not caller. Symbols should be also
2155 //  decorated in some fancy way :) It doesn't support any vector arguments.
2156 //  For info on fast calling convention see Fast Calling Convention (tail call)
2157 //  implementation LowerX86_32FastCCCallTo.
2158
2159 /// CallIsStructReturn - Determines whether a call uses struct return
2160 /// semantics.
2161 enum StructReturnType {
2162   NotStructReturn,
2163   RegStructReturn,
2164   StackStructReturn
2165 };
2166 static StructReturnType
2167 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2168   if (Outs.empty())
2169     return NotStructReturn;
2170
2171   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2172   if (!Flags.isSRet())
2173     return NotStructReturn;
2174   if (Flags.isInReg())
2175     return RegStructReturn;
2176   return StackStructReturn;
2177 }
2178
2179 /// Determines whether a function uses struct return semantics.
2180 static StructReturnType
2181 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2182   if (Ins.empty())
2183     return NotStructReturn;
2184
2185   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2186   if (!Flags.isSRet())
2187     return NotStructReturn;
2188   if (Flags.isInReg())
2189     return RegStructReturn;
2190   return StackStructReturn;
2191 }
2192
2193 /// Make a copy of an aggregate at address specified by "Src" to address
2194 /// "Dst" with size and alignment information specified by the specific
2195 /// parameter attribute. The copy will be passed as a byval function parameter.
2196 static SDValue
2197 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2198                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2199                           SDLoc dl) {
2200   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2201
2202   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2203                        /*isVolatile*/false, /*AlwaysInline=*/true,
2204                        /*isTailCall*/false,
2205                        MachinePointerInfo(), MachinePointerInfo());
2206 }
2207
2208 /// Return true if the calling convention is one that
2209 /// supports tail call optimization.
2210 static bool IsTailCallConvention(CallingConv::ID CC) {
2211   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2212           CC == CallingConv::HiPE);
2213 }
2214
2215 /// \brief Return true if the calling convention is a C calling convention.
2216 static bool IsCCallConvention(CallingConv::ID CC) {
2217   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2218           CC == CallingConv::X86_64_SysV);
2219 }
2220
2221 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2222   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2223     return false;
2224
2225   CallSite CS(CI);
2226   CallingConv::ID CalleeCC = CS.getCallingConv();
2227   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2228     return false;
2229
2230   return true;
2231 }
2232
2233 /// Return true if the function is being made into
2234 /// a tailcall target by changing its ABI.
2235 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2236                                    bool GuaranteedTailCallOpt) {
2237   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2238 }
2239
2240 SDValue
2241 X86TargetLowering::LowerMemArgument(SDValue Chain,
2242                                     CallingConv::ID CallConv,
2243                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2244                                     SDLoc dl, SelectionDAG &DAG,
2245                                     const CCValAssign &VA,
2246                                     MachineFrameInfo *MFI,
2247                                     unsigned i) const {
2248   // Create the nodes corresponding to a load from this parameter slot.
2249   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2250   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2251       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2252   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2253   EVT ValVT;
2254
2255   // If value is passed by pointer we have address passed instead of the value
2256   // itself.
2257   bool ExtendedInMem = VA.isExtInLoc() &&
2258     VA.getValVT().getScalarType() == MVT::i1;
2259
2260   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2261     ValVT = VA.getLocVT();
2262   else
2263     ValVT = VA.getValVT();
2264
2265   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2266   // changed with more analysis.
2267   // In case of tail call optimization mark all arguments mutable. Since they
2268   // could be overwritten by lowering of arguments in case of a tail call.
2269   if (Flags.isByVal()) {
2270     unsigned Bytes = Flags.getByValSize();
2271     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2272     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2273     return DAG.getFrameIndex(FI, getPointerTy());
2274   } else {
2275     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2276                                     VA.getLocMemOffset(), isImmutable);
2277     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2278     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2279                                MachinePointerInfo::getFixedStack(FI),
2280                                false, false, false, 0);
2281     return ExtendedInMem ?
2282       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2283   }
2284 }
2285
2286 // FIXME: Get this from tablegen.
2287 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2288                                                 const X86Subtarget *Subtarget) {
2289   assert(Subtarget->is64Bit());
2290
2291   if (Subtarget->isCallingConvWin64(CallConv)) {
2292     static const MCPhysReg GPR64ArgRegsWin64[] = {
2293       X86::RCX, X86::RDX, X86::R8,  X86::R9
2294     };
2295     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2296   }
2297
2298   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2299     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2300   };
2301   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2302 }
2303
2304 // FIXME: Get this from tablegen.
2305 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2306                                                 CallingConv::ID CallConv,
2307                                                 const X86Subtarget *Subtarget) {
2308   assert(Subtarget->is64Bit());
2309   if (Subtarget->isCallingConvWin64(CallConv)) {
2310     // The XMM registers which might contain var arg parameters are shadowed
2311     // in their paired GPR.  So we only need to save the GPR to their home
2312     // slots.
2313     // TODO: __vectorcall will change this.
2314     return None;
2315   }
2316
2317   const Function *Fn = MF.getFunction();
2318   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2319   bool isSoftFloat = Subtarget->useSoftFloat();
2320   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2321          "SSE register cannot be used when SSE is disabled!");
2322   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2323     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2324     // registers.
2325     return None;
2326
2327   static const MCPhysReg XMMArgRegs64Bit[] = {
2328     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2329     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2330   };
2331   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2332 }
2333
2334 SDValue
2335 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2336                                         CallingConv::ID CallConv,
2337                                         bool isVarArg,
2338                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2339                                         SDLoc dl,
2340                                         SelectionDAG &DAG,
2341                                         SmallVectorImpl<SDValue> &InVals)
2342                                           const {
2343   MachineFunction &MF = DAG.getMachineFunction();
2344   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2345   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2346
2347   const Function* Fn = MF.getFunction();
2348   if (Fn->hasExternalLinkage() &&
2349       Subtarget->isTargetCygMing() &&
2350       Fn->getName() == "main")
2351     FuncInfo->setForceFramePointer(true);
2352
2353   MachineFrameInfo *MFI = MF.getFrameInfo();
2354   bool Is64Bit = Subtarget->is64Bit();
2355   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2356
2357   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2358          "Var args not supported with calling convention fastcc, ghc or hipe");
2359
2360   // Assign locations to all of the incoming arguments.
2361   SmallVector<CCValAssign, 16> ArgLocs;
2362   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2363
2364   // Allocate shadow area for Win64
2365   if (IsWin64)
2366     CCInfo.AllocateStack(32, 8);
2367
2368   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2369
2370   unsigned LastVal = ~0U;
2371   SDValue ArgValue;
2372   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2373     CCValAssign &VA = ArgLocs[i];
2374     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2375     // places.
2376     assert(VA.getValNo() != LastVal &&
2377            "Don't support value assigned to multiple locs yet");
2378     (void)LastVal;
2379     LastVal = VA.getValNo();
2380
2381     if (VA.isRegLoc()) {
2382       EVT RegVT = VA.getLocVT();
2383       const TargetRegisterClass *RC;
2384       if (RegVT == MVT::i32)
2385         RC = &X86::GR32RegClass;
2386       else if (Is64Bit && RegVT == MVT::i64)
2387         RC = &X86::GR64RegClass;
2388       else if (RegVT == MVT::f32)
2389         RC = &X86::FR32RegClass;
2390       else if (RegVT == MVT::f64)
2391         RC = &X86::FR64RegClass;
2392       else if (RegVT.is512BitVector())
2393         RC = &X86::VR512RegClass;
2394       else if (RegVT.is256BitVector())
2395         RC = &X86::VR256RegClass;
2396       else if (RegVT.is128BitVector())
2397         RC = &X86::VR128RegClass;
2398       else if (RegVT == MVT::x86mmx)
2399         RC = &X86::VR64RegClass;
2400       else if (RegVT == MVT::i1)
2401         RC = &X86::VK1RegClass;
2402       else if (RegVT == MVT::v8i1)
2403         RC = &X86::VK8RegClass;
2404       else if (RegVT == MVT::v16i1)
2405         RC = &X86::VK16RegClass;
2406       else if (RegVT == MVT::v32i1)
2407         RC = &X86::VK32RegClass;
2408       else if (RegVT == MVT::v64i1)
2409         RC = &X86::VK64RegClass;
2410       else
2411         llvm_unreachable("Unknown argument type!");
2412
2413       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2414       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2415
2416       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2417       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2418       // right size.
2419       if (VA.getLocInfo() == CCValAssign::SExt)
2420         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2421                                DAG.getValueType(VA.getValVT()));
2422       else if (VA.getLocInfo() == CCValAssign::ZExt)
2423         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2424                                DAG.getValueType(VA.getValVT()));
2425       else if (VA.getLocInfo() == CCValAssign::BCvt)
2426         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2427
2428       if (VA.isExtInLoc()) {
2429         // Handle MMX values passed in XMM regs.
2430         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2431           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2432         else
2433           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2434       }
2435     } else {
2436       assert(VA.isMemLoc());
2437       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2438     }
2439
2440     // If value is passed via pointer - do a load.
2441     if (VA.getLocInfo() == CCValAssign::Indirect)
2442       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2443                              MachinePointerInfo(), false, false, false, 0);
2444
2445     InVals.push_back(ArgValue);
2446   }
2447
2448   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2449     // All x86 ABIs require that for returning structs by value we copy the
2450     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2451     // the argument into a virtual register so that we can access it from the
2452     // return points.
2453     if (Ins[i].Flags.isSRet()) {
2454       unsigned Reg = FuncInfo->getSRetReturnReg();
2455       if (!Reg) {
2456         MVT PtrTy = getPointerTy();
2457         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2458         FuncInfo->setSRetReturnReg(Reg);
2459       }
2460       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2461       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2462       break;
2463     }
2464   }
2465
2466   unsigned StackSize = CCInfo.getNextStackOffset();
2467   // Align stack specially for tail calls.
2468   if (FuncIsMadeTailCallSafe(CallConv,
2469                              MF.getTarget().Options.GuaranteedTailCallOpt))
2470     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2471
2472   // If the function takes variable number of arguments, make a frame index for
2473   // the start of the first vararg value... for expansion of llvm.va_start. We
2474   // can skip this if there are no va_start calls.
2475   if (MFI->hasVAStart() &&
2476       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2477                    CallConv != CallingConv::X86_ThisCall))) {
2478     FuncInfo->setVarArgsFrameIndex(
2479         MFI->CreateFixedObject(1, StackSize, true));
2480   }
2481
2482   MachineModuleInfo &MMI = MF.getMMI();
2483   const Function *WinEHParent = nullptr;
2484   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2485     WinEHParent = MMI.getWinEHParent(Fn);
2486   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2487   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2488
2489   // Figure out if XMM registers are in use.
2490   assert(!(Subtarget->useSoftFloat() &&
2491            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2492          "SSE register cannot be used when SSE is disabled!");
2493
2494   // 64-bit calling conventions support varargs and register parameters, so we
2495   // have to do extra work to spill them in the prologue.
2496   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2497     // Find the first unallocated argument registers.
2498     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2499     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2500     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2501     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2502     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2503            "SSE register cannot be used when SSE is disabled!");
2504
2505     // Gather all the live in physical registers.
2506     SmallVector<SDValue, 6> LiveGPRs;
2507     SmallVector<SDValue, 8> LiveXMMRegs;
2508     SDValue ALVal;
2509     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2510       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2511       LiveGPRs.push_back(
2512           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2513     }
2514     if (!ArgXMMs.empty()) {
2515       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2516       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2517       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2518         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2519         LiveXMMRegs.push_back(
2520             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2521       }
2522     }
2523
2524     if (IsWin64) {
2525       // Get to the caller-allocated home save location.  Add 8 to account
2526       // for the return address.
2527       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2528       FuncInfo->setRegSaveFrameIndex(
2529           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2530       // Fixup to set vararg frame on shadow area (4 x i64).
2531       if (NumIntRegs < 4)
2532         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2533     } else {
2534       // For X86-64, if there are vararg parameters that are passed via
2535       // registers, then we must store them to their spots on the stack so
2536       // they may be loaded by deferencing the result of va_next.
2537       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2538       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2539       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2540           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2541     }
2542
2543     // Store the integer parameter registers.
2544     SmallVector<SDValue, 8> MemOps;
2545     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2546                                       getPointerTy());
2547     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2548     for (SDValue Val : LiveGPRs) {
2549       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2550                                 DAG.getIntPtrConstant(Offset, dl));
2551       SDValue Store =
2552         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2553                      MachinePointerInfo::getFixedStack(
2554                        FuncInfo->getRegSaveFrameIndex(), Offset),
2555                      false, false, 0);
2556       MemOps.push_back(Store);
2557       Offset += 8;
2558     }
2559
2560     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2561       // Now store the XMM (fp + vector) parameter registers.
2562       SmallVector<SDValue, 12> SaveXMMOps;
2563       SaveXMMOps.push_back(Chain);
2564       SaveXMMOps.push_back(ALVal);
2565       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2566                              FuncInfo->getRegSaveFrameIndex(), dl));
2567       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2568                              FuncInfo->getVarArgsFPOffset(), dl));
2569       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2570                         LiveXMMRegs.end());
2571       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2572                                    MVT::Other, SaveXMMOps));
2573     }
2574
2575     if (!MemOps.empty())
2576       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2577   } else if (IsWinEHOutlined) {
2578     // Get to the caller-allocated home save location.  Add 8 to account
2579     // for the return address.
2580     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2581     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2582         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2583
2584     MMI.getWinEHFuncInfo(Fn)
2585         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2586         FuncInfo->getRegSaveFrameIndex();
2587
2588     // Store the second integer parameter (rdx) into rsp+16 relative to the
2589     // stack pointer at the entry of the function.
2590     SDValue RSFIN =
2591         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2592     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2593     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2594     Chain = DAG.getStore(
2595         Val.getValue(1), dl, Val, RSFIN,
2596         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2597         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2598   }
2599
2600   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2601     // Find the largest legal vector type.
2602     MVT VecVT = MVT::Other;
2603     // FIXME: Only some x86_32 calling conventions support AVX512.
2604     if (Subtarget->hasAVX512() &&
2605         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2606                      CallConv == CallingConv::Intel_OCL_BI)))
2607       VecVT = MVT::v16f32;
2608     else if (Subtarget->hasAVX())
2609       VecVT = MVT::v8f32;
2610     else if (Subtarget->hasSSE2())
2611       VecVT = MVT::v4f32;
2612
2613     // We forward some GPRs and some vector types.
2614     SmallVector<MVT, 2> RegParmTypes;
2615     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2616     RegParmTypes.push_back(IntVT);
2617     if (VecVT != MVT::Other)
2618       RegParmTypes.push_back(VecVT);
2619
2620     // Compute the set of forwarded registers. The rest are scratch.
2621     SmallVectorImpl<ForwardedRegister> &Forwards =
2622         FuncInfo->getForwardedMustTailRegParms();
2623     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2624
2625     // Conservatively forward AL on x86_64, since it might be used for varargs.
2626     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2627       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2628       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2629     }
2630
2631     // Copy all forwards from physical to virtual registers.
2632     for (ForwardedRegister &F : Forwards) {
2633       // FIXME: Can we use a less constrained schedule?
2634       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2635       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2636       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2637     }
2638   }
2639
2640   // Some CCs need callee pop.
2641   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2642                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2643     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2644   } else {
2645     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2646     // If this is an sret function, the return should pop the hidden pointer.
2647     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2648         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2649         argsAreStructReturn(Ins) == StackStructReturn)
2650       FuncInfo->setBytesToPopOnReturn(4);
2651   }
2652
2653   if (!Is64Bit) {
2654     // RegSaveFrameIndex is X86-64 only.
2655     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2656     if (CallConv == CallingConv::X86_FastCall ||
2657         CallConv == CallingConv::X86_ThisCall)
2658       // fastcc functions can't have varargs.
2659       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2660   }
2661
2662   FuncInfo->setArgumentStackSize(StackSize);
2663
2664   if (IsWinEHParent) {
2665     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2666     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2667     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2668     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2669     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2670                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2671                          /*isVolatile=*/true,
2672                          /*isNonTemporal=*/false, /*Alignment=*/0);
2673   }
2674
2675   return Chain;
2676 }
2677
2678 SDValue
2679 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2680                                     SDValue StackPtr, SDValue Arg,
2681                                     SDLoc dl, SelectionDAG &DAG,
2682                                     const CCValAssign &VA,
2683                                     ISD::ArgFlagsTy Flags) const {
2684   unsigned LocMemOffset = VA.getLocMemOffset();
2685   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2686   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2687   if (Flags.isByVal())
2688     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2689
2690   return DAG.getStore(Chain, dl, Arg, PtrOff,
2691                       MachinePointerInfo::getStack(LocMemOffset),
2692                       false, false, 0);
2693 }
2694
2695 /// Emit a load of return address if tail call
2696 /// optimization is performed and it is required.
2697 SDValue
2698 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2699                                            SDValue &OutRetAddr, SDValue Chain,
2700                                            bool IsTailCall, bool Is64Bit,
2701                                            int FPDiff, SDLoc dl) const {
2702   // Adjust the Return address stack slot.
2703   EVT VT = getPointerTy();
2704   OutRetAddr = getReturnAddressFrameIndex(DAG);
2705
2706   // Load the "old" Return address.
2707   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2708                            false, false, false, 0);
2709   return SDValue(OutRetAddr.getNode(), 1);
2710 }
2711
2712 /// Emit a store of the return address if tail call
2713 /// optimization is performed and it is required (FPDiff!=0).
2714 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2715                                         SDValue Chain, SDValue RetAddrFrIdx,
2716                                         EVT PtrVT, unsigned SlotSize,
2717                                         int FPDiff, SDLoc dl) {
2718   // Store the return address to the appropriate stack slot.
2719   if (!FPDiff) return Chain;
2720   // Calculate the new stack slot for the return address.
2721   int NewReturnAddrFI =
2722     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2723                                          false);
2724   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2725   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2726                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2727                        false, false, 0);
2728   return Chain;
2729 }
2730
2731 SDValue
2732 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2733                              SmallVectorImpl<SDValue> &InVals) const {
2734   SelectionDAG &DAG                     = CLI.DAG;
2735   SDLoc &dl                             = CLI.DL;
2736   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2737   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2738   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2739   SDValue Chain                         = CLI.Chain;
2740   SDValue Callee                        = CLI.Callee;
2741   CallingConv::ID CallConv              = CLI.CallConv;
2742   bool &isTailCall                      = CLI.IsTailCall;
2743   bool isVarArg                         = CLI.IsVarArg;
2744
2745   MachineFunction &MF = DAG.getMachineFunction();
2746   bool Is64Bit        = Subtarget->is64Bit();
2747   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2748   StructReturnType SR = callIsStructReturn(Outs);
2749   bool IsSibcall      = false;
2750   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2751
2752   if (MF.getTarget().Options.DisableTailCalls)
2753     isTailCall = false;
2754
2755   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2756   if (IsMustTail) {
2757     // Force this to be a tail call.  The verifier rules are enough to ensure
2758     // that we can lower this successfully without moving the return address
2759     // around.
2760     isTailCall = true;
2761   } else if (isTailCall) {
2762     // Check if it's really possible to do a tail call.
2763     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2764                     isVarArg, SR != NotStructReturn,
2765                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2766                     Outs, OutVals, Ins, DAG);
2767
2768     // Sibcalls are automatically detected tailcalls which do not require
2769     // ABI changes.
2770     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2771       IsSibcall = true;
2772
2773     if (isTailCall)
2774       ++NumTailCalls;
2775   }
2776
2777   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2778          "Var args not supported with calling convention fastcc, ghc or hipe");
2779
2780   // Analyze operands of the call, assigning locations to each operand.
2781   SmallVector<CCValAssign, 16> ArgLocs;
2782   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2783
2784   // Allocate shadow area for Win64
2785   if (IsWin64)
2786     CCInfo.AllocateStack(32, 8);
2787
2788   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2789
2790   // Get a count of how many bytes are to be pushed on the stack.
2791   unsigned NumBytes = CCInfo.getNextStackOffset();
2792   if (IsSibcall)
2793     // This is a sibcall. The memory operands are available in caller's
2794     // own caller's stack.
2795     NumBytes = 0;
2796   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2797            IsTailCallConvention(CallConv))
2798     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2799
2800   int FPDiff = 0;
2801   if (isTailCall && !IsSibcall && !IsMustTail) {
2802     // Lower arguments at fp - stackoffset + fpdiff.
2803     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2804
2805     FPDiff = NumBytesCallerPushed - NumBytes;
2806
2807     // Set the delta of movement of the returnaddr stackslot.
2808     // But only set if delta is greater than previous delta.
2809     if (FPDiff < X86Info->getTCReturnAddrDelta())
2810       X86Info->setTCReturnAddrDelta(FPDiff);
2811   }
2812
2813   unsigned NumBytesToPush = NumBytes;
2814   unsigned NumBytesToPop = NumBytes;
2815
2816   // If we have an inalloca argument, all stack space has already been allocated
2817   // for us and be right at the top of the stack.  We don't support multiple
2818   // arguments passed in memory when using inalloca.
2819   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2820     NumBytesToPush = 0;
2821     if (!ArgLocs.back().isMemLoc())
2822       report_fatal_error("cannot use inalloca attribute on a register "
2823                          "parameter");
2824     if (ArgLocs.back().getLocMemOffset() != 0)
2825       report_fatal_error("any parameter with the inalloca attribute must be "
2826                          "the only memory argument");
2827   }
2828
2829   if (!IsSibcall)
2830     Chain = DAG.getCALLSEQ_START(
2831         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2832
2833   SDValue RetAddrFrIdx;
2834   // Load return address for tail calls.
2835   if (isTailCall && FPDiff)
2836     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2837                                     Is64Bit, FPDiff, dl);
2838
2839   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2840   SmallVector<SDValue, 8> MemOpChains;
2841   SDValue StackPtr;
2842
2843   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2844   // of tail call optimization arguments are handle later.
2845   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2846   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2847     // Skip inalloca arguments, they have already been written.
2848     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2849     if (Flags.isInAlloca())
2850       continue;
2851
2852     CCValAssign &VA = ArgLocs[i];
2853     EVT RegVT = VA.getLocVT();
2854     SDValue Arg = OutVals[i];
2855     bool isByVal = Flags.isByVal();
2856
2857     // Promote the value if needed.
2858     switch (VA.getLocInfo()) {
2859     default: llvm_unreachable("Unknown loc info!");
2860     case CCValAssign::Full: break;
2861     case CCValAssign::SExt:
2862       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2863       break;
2864     case CCValAssign::ZExt:
2865       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2866       break;
2867     case CCValAssign::AExt:
2868       if (Arg.getValueType().isVector() &&
2869           Arg.getValueType().getScalarType() == MVT::i1)
2870         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2871       else if (RegVT.is128BitVector()) {
2872         // Special case: passing MMX values in XMM registers.
2873         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2874         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2875         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2876       } else
2877         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2878       break;
2879     case CCValAssign::BCvt:
2880       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2881       break;
2882     case CCValAssign::Indirect: {
2883       // Store the argument.
2884       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2885       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2886       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2887                            MachinePointerInfo::getFixedStack(FI),
2888                            false, false, 0);
2889       Arg = SpillSlot;
2890       break;
2891     }
2892     }
2893
2894     if (VA.isRegLoc()) {
2895       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2896       if (isVarArg && IsWin64) {
2897         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2898         // shadow reg if callee is a varargs function.
2899         unsigned ShadowReg = 0;
2900         switch (VA.getLocReg()) {
2901         case X86::XMM0: ShadowReg = X86::RCX; break;
2902         case X86::XMM1: ShadowReg = X86::RDX; break;
2903         case X86::XMM2: ShadowReg = X86::R8; break;
2904         case X86::XMM3: ShadowReg = X86::R9; break;
2905         }
2906         if (ShadowReg)
2907           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2908       }
2909     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2910       assert(VA.isMemLoc());
2911       if (!StackPtr.getNode())
2912         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2913                                       getPointerTy());
2914       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2915                                              dl, DAG, VA, Flags));
2916     }
2917   }
2918
2919   if (!MemOpChains.empty())
2920     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2921
2922   if (Subtarget->isPICStyleGOT()) {
2923     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2924     // GOT pointer.
2925     if (!isTailCall) {
2926       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2927                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2928     } else {
2929       // If we are tail calling and generating PIC/GOT style code load the
2930       // address of the callee into ECX. The value in ecx is used as target of
2931       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2932       // for tail calls on PIC/GOT architectures. Normally we would just put the
2933       // address of GOT into ebx and then call target@PLT. But for tail calls
2934       // ebx would be restored (since ebx is callee saved) before jumping to the
2935       // target@PLT.
2936
2937       // Note: The actual moving to ECX is done further down.
2938       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2939       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2940           !G->getGlobal()->hasProtectedVisibility())
2941         Callee = LowerGlobalAddress(Callee, DAG);
2942       else if (isa<ExternalSymbolSDNode>(Callee))
2943         Callee = LowerExternalSymbol(Callee, DAG);
2944     }
2945   }
2946
2947   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2948     // From AMD64 ABI document:
2949     // For calls that may call functions that use varargs or stdargs
2950     // (prototype-less calls or calls to functions containing ellipsis (...) in
2951     // the declaration) %al is used as hidden argument to specify the number
2952     // of SSE registers used. The contents of %al do not need to match exactly
2953     // the number of registers, but must be an ubound on the number of SSE
2954     // registers used and is in the range 0 - 8 inclusive.
2955
2956     // Count the number of XMM registers allocated.
2957     static const MCPhysReg XMMArgRegs[] = {
2958       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2959       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2960     };
2961     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2962     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2963            && "SSE registers cannot be used when SSE is disabled");
2964
2965     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2966                                         DAG.getConstant(NumXMMRegs, dl,
2967                                                         MVT::i8)));
2968   }
2969
2970   if (isVarArg && IsMustTail) {
2971     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2972     for (const auto &F : Forwards) {
2973       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2974       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2975     }
2976   }
2977
2978   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2979   // don't need this because the eligibility check rejects calls that require
2980   // shuffling arguments passed in memory.
2981   if (!IsSibcall && isTailCall) {
2982     // Force all the incoming stack arguments to be loaded from the stack
2983     // before any new outgoing arguments are stored to the stack, because the
2984     // outgoing stack slots may alias the incoming argument stack slots, and
2985     // the alias isn't otherwise explicit. This is slightly more conservative
2986     // than necessary, because it means that each store effectively depends
2987     // on every argument instead of just those arguments it would clobber.
2988     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2989
2990     SmallVector<SDValue, 8> MemOpChains2;
2991     SDValue FIN;
2992     int FI = 0;
2993     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2994       CCValAssign &VA = ArgLocs[i];
2995       if (VA.isRegLoc())
2996         continue;
2997       assert(VA.isMemLoc());
2998       SDValue Arg = OutVals[i];
2999       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3000       // Skip inalloca arguments.  They don't require any work.
3001       if (Flags.isInAlloca())
3002         continue;
3003       // Create frame index.
3004       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3005       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3006       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3007       FIN = DAG.getFrameIndex(FI, getPointerTy());
3008
3009       if (Flags.isByVal()) {
3010         // Copy relative to framepointer.
3011         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3012         if (!StackPtr.getNode())
3013           StackPtr = DAG.getCopyFromReg(Chain, dl,
3014                                         RegInfo->getStackRegister(),
3015                                         getPointerTy());
3016         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3017
3018         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3019                                                          ArgChain,
3020                                                          Flags, DAG, dl));
3021       } else {
3022         // Store relative to framepointer.
3023         MemOpChains2.push_back(
3024           DAG.getStore(ArgChain, dl, Arg, FIN,
3025                        MachinePointerInfo::getFixedStack(FI),
3026                        false, false, 0));
3027       }
3028     }
3029
3030     if (!MemOpChains2.empty())
3031       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3032
3033     // Store the return address to the appropriate stack slot.
3034     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3035                                      getPointerTy(), RegInfo->getSlotSize(),
3036                                      FPDiff, dl);
3037   }
3038
3039   // Build a sequence of copy-to-reg nodes chained together with token chain
3040   // and flag operands which copy the outgoing args into registers.
3041   SDValue InFlag;
3042   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3043     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3044                              RegsToPass[i].second, InFlag);
3045     InFlag = Chain.getValue(1);
3046   }
3047
3048   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3049     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3050     // In the 64-bit large code model, we have to make all calls
3051     // through a register, since the call instruction's 32-bit
3052     // pc-relative offset may not be large enough to hold the whole
3053     // address.
3054   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3055     // If the callee is a GlobalAddress node (quite common, every direct call
3056     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3057     // it.
3058     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3059
3060     // We should use extra load for direct calls to dllimported functions in
3061     // non-JIT mode.
3062     const GlobalValue *GV = G->getGlobal();
3063     if (!GV->hasDLLImportStorageClass()) {
3064       unsigned char OpFlags = 0;
3065       bool ExtraLoad = false;
3066       unsigned WrapperKind = ISD::DELETED_NODE;
3067
3068       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3069       // external symbols most go through the PLT in PIC mode.  If the symbol
3070       // has hidden or protected visibility, or if it is static or local, then
3071       // we don't need to use the PLT - we can directly call it.
3072       if (Subtarget->isTargetELF() &&
3073           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3074           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3075         OpFlags = X86II::MO_PLT;
3076       } else if (Subtarget->isPICStyleStubAny() &&
3077                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3078                  (!Subtarget->getTargetTriple().isMacOSX() ||
3079                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3080         // PC-relative references to external symbols should go through $stub,
3081         // unless we're building with the leopard linker or later, which
3082         // automatically synthesizes these stubs.
3083         OpFlags = X86II::MO_DARWIN_STUB;
3084       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3085                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3086         // If the function is marked as non-lazy, generate an indirect call
3087         // which loads from the GOT directly. This avoids runtime overhead
3088         // at the cost of eager binding (and one extra byte of encoding).
3089         OpFlags = X86II::MO_GOTPCREL;
3090         WrapperKind = X86ISD::WrapperRIP;
3091         ExtraLoad = true;
3092       }
3093
3094       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3095                                           G->getOffset(), OpFlags);
3096
3097       // Add a wrapper if needed.
3098       if (WrapperKind != ISD::DELETED_NODE)
3099         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3100       // Add extra indirection if needed.
3101       if (ExtraLoad)
3102         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3103                              MachinePointerInfo::getGOT(),
3104                              false, false, false, 0);
3105     }
3106   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3107     unsigned char OpFlags = 0;
3108
3109     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3110     // external symbols should go through the PLT.
3111     if (Subtarget->isTargetELF() &&
3112         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3113       OpFlags = X86II::MO_PLT;
3114     } else if (Subtarget->isPICStyleStubAny() &&
3115                (!Subtarget->getTargetTriple().isMacOSX() ||
3116                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3117       // PC-relative references to external symbols should go through $stub,
3118       // unless we're building with the leopard linker or later, which
3119       // automatically synthesizes these stubs.
3120       OpFlags = X86II::MO_DARWIN_STUB;
3121     }
3122
3123     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3124                                          OpFlags);
3125   } else if (Subtarget->isTarget64BitILP32() &&
3126              Callee->getValueType(0) == MVT::i32) {
3127     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3128     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3129   }
3130
3131   // Returns a chain & a flag for retval copy to use.
3132   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3133   SmallVector<SDValue, 8> Ops;
3134
3135   if (!IsSibcall && isTailCall) {
3136     Chain = DAG.getCALLSEQ_END(Chain,
3137                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3138                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3139     InFlag = Chain.getValue(1);
3140   }
3141
3142   Ops.push_back(Chain);
3143   Ops.push_back(Callee);
3144
3145   if (isTailCall)
3146     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3147
3148   // Add argument registers to the end of the list so that they are known live
3149   // into the call.
3150   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3151     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3152                                   RegsToPass[i].second.getValueType()));
3153
3154   // Add a register mask operand representing the call-preserved registers.
3155   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3156   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3157   assert(Mask && "Missing call preserved mask for calling convention");
3158   Ops.push_back(DAG.getRegisterMask(Mask));
3159
3160   if (InFlag.getNode())
3161     Ops.push_back(InFlag);
3162
3163   if (isTailCall) {
3164     // We used to do:
3165     //// If this is the first return lowered for this function, add the regs
3166     //// to the liveout set for the function.
3167     // This isn't right, although it's probably harmless on x86; liveouts
3168     // should be computed from returns not tail calls.  Consider a void
3169     // function making a tail call to a function returning int.
3170     MF.getFrameInfo()->setHasTailCall();
3171     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3172   }
3173
3174   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3175   InFlag = Chain.getValue(1);
3176
3177   // Create the CALLSEQ_END node.
3178   unsigned NumBytesForCalleeToPop;
3179   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3180                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3181     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3182   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3183            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3184            SR == StackStructReturn)
3185     // If this is a call to a struct-return function, the callee
3186     // pops the hidden struct pointer, so we have to push it back.
3187     // This is common for Darwin/X86, Linux & Mingw32 targets.
3188     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3189     NumBytesForCalleeToPop = 4;
3190   else
3191     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3192
3193   // Returns a flag for retval copy to use.
3194   if (!IsSibcall) {
3195     Chain = DAG.getCALLSEQ_END(Chain,
3196                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3197                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3198                                                      true),
3199                                InFlag, dl);
3200     InFlag = Chain.getValue(1);
3201   }
3202
3203   // Handle result values, copying them out of physregs into vregs that we
3204   // return.
3205   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3206                          Ins, dl, DAG, InVals);
3207 }
3208
3209 //===----------------------------------------------------------------------===//
3210 //                Fast Calling Convention (tail call) implementation
3211 //===----------------------------------------------------------------------===//
3212
3213 //  Like std call, callee cleans arguments, convention except that ECX is
3214 //  reserved for storing the tail called function address. Only 2 registers are
3215 //  free for argument passing (inreg). Tail call optimization is performed
3216 //  provided:
3217 //                * tailcallopt is enabled
3218 //                * caller/callee are fastcc
3219 //  On X86_64 architecture with GOT-style position independent code only local
3220 //  (within module) calls are supported at the moment.
3221 //  To keep the stack aligned according to platform abi the function
3222 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3223 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3224 //  If a tail called function callee has more arguments than the caller the
3225 //  caller needs to make sure that there is room to move the RETADDR to. This is
3226 //  achieved by reserving an area the size of the argument delta right after the
3227 //  original RETADDR, but before the saved framepointer or the spilled registers
3228 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3229 //  stack layout:
3230 //    arg1
3231 //    arg2
3232 //    RETADDR
3233 //    [ new RETADDR
3234 //      move area ]
3235 //    (possible EBP)
3236 //    ESI
3237 //    EDI
3238 //    local1 ..
3239
3240 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3241 /// for a 16 byte align requirement.
3242 unsigned
3243 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3244                                                SelectionDAG& DAG) const {
3245   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3246   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3247   unsigned StackAlignment = TFI.getStackAlignment();
3248   uint64_t AlignMask = StackAlignment - 1;
3249   int64_t Offset = StackSize;
3250   unsigned SlotSize = RegInfo->getSlotSize();
3251   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3252     // Number smaller than 12 so just add the difference.
3253     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3254   } else {
3255     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3256     Offset = ((~AlignMask) & Offset) + StackAlignment +
3257       (StackAlignment-SlotSize);
3258   }
3259   return Offset;
3260 }
3261
3262 /// MatchingStackOffset - Return true if the given stack call argument is
3263 /// already available in the same position (relatively) of the caller's
3264 /// incoming argument stack.
3265 static
3266 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3267                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3268                          const X86InstrInfo *TII) {
3269   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3270   int FI = INT_MAX;
3271   if (Arg.getOpcode() == ISD::CopyFromReg) {
3272     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3273     if (!TargetRegisterInfo::isVirtualRegister(VR))
3274       return false;
3275     MachineInstr *Def = MRI->getVRegDef(VR);
3276     if (!Def)
3277       return false;
3278     if (!Flags.isByVal()) {
3279       if (!TII->isLoadFromStackSlot(Def, FI))
3280         return false;
3281     } else {
3282       unsigned Opcode = Def->getOpcode();
3283       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3284            Opcode == X86::LEA64_32r) &&
3285           Def->getOperand(1).isFI()) {
3286         FI = Def->getOperand(1).getIndex();
3287         Bytes = Flags.getByValSize();
3288       } else
3289         return false;
3290     }
3291   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3292     if (Flags.isByVal())
3293       // ByVal argument is passed in as a pointer but it's now being
3294       // dereferenced. e.g.
3295       // define @foo(%struct.X* %A) {
3296       //   tail call @bar(%struct.X* byval %A)
3297       // }
3298       return false;
3299     SDValue Ptr = Ld->getBasePtr();
3300     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3301     if (!FINode)
3302       return false;
3303     FI = FINode->getIndex();
3304   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3305     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3306     FI = FINode->getIndex();
3307     Bytes = Flags.getByValSize();
3308   } else
3309     return false;
3310
3311   assert(FI != INT_MAX);
3312   if (!MFI->isFixedObjectIndex(FI))
3313     return false;
3314   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3315 }
3316
3317 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3318 /// for tail call optimization. Targets which want to do tail call
3319 /// optimization should implement this function.
3320 bool
3321 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3322                                                      CallingConv::ID CalleeCC,
3323                                                      bool isVarArg,
3324                                                      bool isCalleeStructRet,
3325                                                      bool isCallerStructRet,
3326                                                      Type *RetTy,
3327                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3328                                     const SmallVectorImpl<SDValue> &OutVals,
3329                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3330                                                      SelectionDAG &DAG) const {
3331   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3332     return false;
3333
3334   // If -tailcallopt is specified, make fastcc functions tail-callable.
3335   const MachineFunction &MF = DAG.getMachineFunction();
3336   const Function *CallerF = MF.getFunction();
3337
3338   // If the function return type is x86_fp80 and the callee return type is not,
3339   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3340   // perform a tailcall optimization here.
3341   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3342     return false;
3343
3344   CallingConv::ID CallerCC = CallerF->getCallingConv();
3345   bool CCMatch = CallerCC == CalleeCC;
3346   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3347   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3348
3349   // Win64 functions have extra shadow space for argument homing. Don't do the
3350   // sibcall if the caller and callee have mismatched expectations for this
3351   // space.
3352   if (IsCalleeWin64 != IsCallerWin64)
3353     return false;
3354
3355   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3356     if (IsTailCallConvention(CalleeCC) && CCMatch)
3357       return true;
3358     return false;
3359   }
3360
3361   // Look for obvious safe cases to perform tail call optimization that do not
3362   // require ABI changes. This is what gcc calls sibcall.
3363
3364   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3365   // emit a special epilogue.
3366   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3367   if (RegInfo->needsStackRealignment(MF))
3368     return false;
3369
3370   // Also avoid sibcall optimization if either caller or callee uses struct
3371   // return semantics.
3372   if (isCalleeStructRet || isCallerStructRet)
3373     return false;
3374
3375   // An stdcall/thiscall caller is expected to clean up its arguments; the
3376   // callee isn't going to do that.
3377   // FIXME: this is more restrictive than needed. We could produce a tailcall
3378   // when the stack adjustment matches. For example, with a thiscall that takes
3379   // only one argument.
3380   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3381                    CallerCC == CallingConv::X86_ThisCall))
3382     return false;
3383
3384   // Do not sibcall optimize vararg calls unless all arguments are passed via
3385   // registers.
3386   if (isVarArg && !Outs.empty()) {
3387
3388     // Optimizing for varargs on Win64 is unlikely to be safe without
3389     // additional testing.
3390     if (IsCalleeWin64 || IsCallerWin64)
3391       return false;
3392
3393     SmallVector<CCValAssign, 16> ArgLocs;
3394     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3395                    *DAG.getContext());
3396
3397     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3398     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3399       if (!ArgLocs[i].isRegLoc())
3400         return false;
3401   }
3402
3403   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3404   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3405   // this into a sibcall.
3406   bool Unused = false;
3407   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3408     if (!Ins[i].Used) {
3409       Unused = true;
3410       break;
3411     }
3412   }
3413   if (Unused) {
3414     SmallVector<CCValAssign, 16> RVLocs;
3415     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3416                    *DAG.getContext());
3417     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3418     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3419       CCValAssign &VA = RVLocs[i];
3420       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3421         return false;
3422     }
3423   }
3424
3425   // If the calling conventions do not match, then we'd better make sure the
3426   // results are returned in the same way as what the caller expects.
3427   if (!CCMatch) {
3428     SmallVector<CCValAssign, 16> RVLocs1;
3429     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3430                     *DAG.getContext());
3431     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3432
3433     SmallVector<CCValAssign, 16> RVLocs2;
3434     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3435                     *DAG.getContext());
3436     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3437
3438     if (RVLocs1.size() != RVLocs2.size())
3439       return false;
3440     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3441       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3442         return false;
3443       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3444         return false;
3445       if (RVLocs1[i].isRegLoc()) {
3446         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3447           return false;
3448       } else {
3449         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3450           return false;
3451       }
3452     }
3453   }
3454
3455   // If the callee takes no arguments then go on to check the results of the
3456   // call.
3457   if (!Outs.empty()) {
3458     // Check if stack adjustment is needed. For now, do not do this if any
3459     // argument is passed on the stack.
3460     SmallVector<CCValAssign, 16> ArgLocs;
3461     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3462                    *DAG.getContext());
3463
3464     // Allocate shadow area for Win64
3465     if (IsCalleeWin64)
3466       CCInfo.AllocateStack(32, 8);
3467
3468     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3469     if (CCInfo.getNextStackOffset()) {
3470       MachineFunction &MF = DAG.getMachineFunction();
3471       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3472         return false;
3473
3474       // Check if the arguments are already laid out in the right way as
3475       // the caller's fixed stack objects.
3476       MachineFrameInfo *MFI = MF.getFrameInfo();
3477       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3478       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3479       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3480         CCValAssign &VA = ArgLocs[i];
3481         SDValue Arg = OutVals[i];
3482         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3483         if (VA.getLocInfo() == CCValAssign::Indirect)
3484           return false;
3485         if (!VA.isRegLoc()) {
3486           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3487                                    MFI, MRI, TII))
3488             return false;
3489         }
3490       }
3491     }
3492
3493     // If the tailcall address may be in a register, then make sure it's
3494     // possible to register allocate for it. In 32-bit, the call address can
3495     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3496     // callee-saved registers are restored. These happen to be the same
3497     // registers used to pass 'inreg' arguments so watch out for those.
3498     if (!Subtarget->is64Bit() &&
3499         ((!isa<GlobalAddressSDNode>(Callee) &&
3500           !isa<ExternalSymbolSDNode>(Callee)) ||
3501          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3502       unsigned NumInRegs = 0;
3503       // In PIC we need an extra register to formulate the address computation
3504       // for the callee.
3505       unsigned MaxInRegs =
3506         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3507
3508       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3509         CCValAssign &VA = ArgLocs[i];
3510         if (!VA.isRegLoc())
3511           continue;
3512         unsigned Reg = VA.getLocReg();
3513         switch (Reg) {
3514         default: break;
3515         case X86::EAX: case X86::EDX: case X86::ECX:
3516           if (++NumInRegs == MaxInRegs)
3517             return false;
3518           break;
3519         }
3520       }
3521     }
3522   }
3523
3524   return true;
3525 }
3526
3527 FastISel *
3528 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3529                                   const TargetLibraryInfo *libInfo) const {
3530   return X86::createFastISel(funcInfo, libInfo);
3531 }
3532
3533 //===----------------------------------------------------------------------===//
3534 //                           Other Lowering Hooks
3535 //===----------------------------------------------------------------------===//
3536
3537 static bool MayFoldLoad(SDValue Op) {
3538   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3539 }
3540
3541 static bool MayFoldIntoStore(SDValue Op) {
3542   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3543 }
3544
3545 static bool isTargetShuffle(unsigned Opcode) {
3546   switch(Opcode) {
3547   default: return false;
3548   case X86ISD::BLENDI:
3549   case X86ISD::PSHUFB:
3550   case X86ISD::PSHUFD:
3551   case X86ISD::PSHUFHW:
3552   case X86ISD::PSHUFLW:
3553   case X86ISD::SHUFP:
3554   case X86ISD::PALIGNR:
3555   case X86ISD::MOVLHPS:
3556   case X86ISD::MOVLHPD:
3557   case X86ISD::MOVHLPS:
3558   case X86ISD::MOVLPS:
3559   case X86ISD::MOVLPD:
3560   case X86ISD::MOVSHDUP:
3561   case X86ISD::MOVSLDUP:
3562   case X86ISD::MOVDDUP:
3563   case X86ISD::MOVSS:
3564   case X86ISD::MOVSD:
3565   case X86ISD::UNPCKL:
3566   case X86ISD::UNPCKH:
3567   case X86ISD::VPERMILPI:
3568   case X86ISD::VPERM2X128:
3569   case X86ISD::VPERMI:
3570     return true;
3571   }
3572 }
3573
3574 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3575                                     SDValue V1, unsigned TargetMask,
3576                                     SelectionDAG &DAG) {
3577   switch(Opc) {
3578   default: llvm_unreachable("Unknown x86 shuffle node");
3579   case X86ISD::PSHUFD:
3580   case X86ISD::PSHUFHW:
3581   case X86ISD::PSHUFLW:
3582   case X86ISD::VPERMILPI:
3583   case X86ISD::VPERMI:
3584     return DAG.getNode(Opc, dl, VT, V1,
3585                        DAG.getConstant(TargetMask, dl, MVT::i8));
3586   }
3587 }
3588
3589 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3590                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3591   switch(Opc) {
3592   default: llvm_unreachable("Unknown x86 shuffle node");
3593   case X86ISD::MOVLHPS:
3594   case X86ISD::MOVLHPD:
3595   case X86ISD::MOVHLPS:
3596   case X86ISD::MOVLPS:
3597   case X86ISD::MOVLPD:
3598   case X86ISD::MOVSS:
3599   case X86ISD::MOVSD:
3600   case X86ISD::UNPCKL:
3601   case X86ISD::UNPCKH:
3602     return DAG.getNode(Opc, dl, VT, V1, V2);
3603   }
3604 }
3605
3606 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3607   MachineFunction &MF = DAG.getMachineFunction();
3608   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3609   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3610   int ReturnAddrIndex = FuncInfo->getRAIndex();
3611
3612   if (ReturnAddrIndex == 0) {
3613     // Set up a frame object for the return address.
3614     unsigned SlotSize = RegInfo->getSlotSize();
3615     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3616                                                            -(int64_t)SlotSize,
3617                                                            false);
3618     FuncInfo->setRAIndex(ReturnAddrIndex);
3619   }
3620
3621   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3622 }
3623
3624 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3625                                        bool hasSymbolicDisplacement) {
3626   // Offset should fit into 32 bit immediate field.
3627   if (!isInt<32>(Offset))
3628     return false;
3629
3630   // If we don't have a symbolic displacement - we don't have any extra
3631   // restrictions.
3632   if (!hasSymbolicDisplacement)
3633     return true;
3634
3635   // FIXME: Some tweaks might be needed for medium code model.
3636   if (M != CodeModel::Small && M != CodeModel::Kernel)
3637     return false;
3638
3639   // For small code model we assume that latest object is 16MB before end of 31
3640   // bits boundary. We may also accept pretty large negative constants knowing
3641   // that all objects are in the positive half of address space.
3642   if (M == CodeModel::Small && Offset < 16*1024*1024)
3643     return true;
3644
3645   // For kernel code model we know that all object resist in the negative half
3646   // of 32bits address space. We may not accept negative offsets, since they may
3647   // be just off and we may accept pretty large positive ones.
3648   if (M == CodeModel::Kernel && Offset >= 0)
3649     return true;
3650
3651   return false;
3652 }
3653
3654 /// isCalleePop - Determines whether the callee is required to pop its
3655 /// own arguments. Callee pop is necessary to support tail calls.
3656 bool X86::isCalleePop(CallingConv::ID CallingConv,
3657                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3658   switch (CallingConv) {
3659   default:
3660     return false;
3661   case CallingConv::X86_StdCall:
3662   case CallingConv::X86_FastCall:
3663   case CallingConv::X86_ThisCall:
3664     return !is64Bit;
3665   case CallingConv::Fast:
3666   case CallingConv::GHC:
3667   case CallingConv::HiPE:
3668     if (IsVarArg)
3669       return false;
3670     return TailCallOpt;
3671   }
3672 }
3673
3674 /// \brief Return true if the condition is an unsigned comparison operation.
3675 static bool isX86CCUnsigned(unsigned X86CC) {
3676   switch (X86CC) {
3677   default: llvm_unreachable("Invalid integer condition!");
3678   case X86::COND_E:     return true;
3679   case X86::COND_G:     return false;
3680   case X86::COND_GE:    return false;
3681   case X86::COND_L:     return false;
3682   case X86::COND_LE:    return false;
3683   case X86::COND_NE:    return true;
3684   case X86::COND_B:     return true;
3685   case X86::COND_A:     return true;
3686   case X86::COND_BE:    return true;
3687   case X86::COND_AE:    return true;
3688   }
3689   llvm_unreachable("covered switch fell through?!");
3690 }
3691
3692 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3693 /// specific condition code, returning the condition code and the LHS/RHS of the
3694 /// comparison to make.
3695 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3696                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3697   if (!isFP) {
3698     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3699       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3700         // X > -1   -> X == 0, jump !sign.
3701         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3702         return X86::COND_NS;
3703       }
3704       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3705         // X < 0   -> X == 0, jump on sign.
3706         return X86::COND_S;
3707       }
3708       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3709         // X < 1   -> X <= 0
3710         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3711         return X86::COND_LE;
3712       }
3713     }
3714
3715     switch (SetCCOpcode) {
3716     default: llvm_unreachable("Invalid integer condition!");
3717     case ISD::SETEQ:  return X86::COND_E;
3718     case ISD::SETGT:  return X86::COND_G;
3719     case ISD::SETGE:  return X86::COND_GE;
3720     case ISD::SETLT:  return X86::COND_L;
3721     case ISD::SETLE:  return X86::COND_LE;
3722     case ISD::SETNE:  return X86::COND_NE;
3723     case ISD::SETULT: return X86::COND_B;
3724     case ISD::SETUGT: return X86::COND_A;
3725     case ISD::SETULE: return X86::COND_BE;
3726     case ISD::SETUGE: return X86::COND_AE;
3727     }
3728   }
3729
3730   // First determine if it is required or is profitable to flip the operands.
3731
3732   // If LHS is a foldable load, but RHS is not, flip the condition.
3733   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3734       !ISD::isNON_EXTLoad(RHS.getNode())) {
3735     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3736     std::swap(LHS, RHS);
3737   }
3738
3739   switch (SetCCOpcode) {
3740   default: break;
3741   case ISD::SETOLT:
3742   case ISD::SETOLE:
3743   case ISD::SETUGT:
3744   case ISD::SETUGE:
3745     std::swap(LHS, RHS);
3746     break;
3747   }
3748
3749   // On a floating point condition, the flags are set as follows:
3750   // ZF  PF  CF   op
3751   //  0 | 0 | 0 | X > Y
3752   //  0 | 0 | 1 | X < Y
3753   //  1 | 0 | 0 | X == Y
3754   //  1 | 1 | 1 | unordered
3755   switch (SetCCOpcode) {
3756   default: llvm_unreachable("Condcode should be pre-legalized away");
3757   case ISD::SETUEQ:
3758   case ISD::SETEQ:   return X86::COND_E;
3759   case ISD::SETOLT:              // flipped
3760   case ISD::SETOGT:
3761   case ISD::SETGT:   return X86::COND_A;
3762   case ISD::SETOLE:              // flipped
3763   case ISD::SETOGE:
3764   case ISD::SETGE:   return X86::COND_AE;
3765   case ISD::SETUGT:              // flipped
3766   case ISD::SETULT:
3767   case ISD::SETLT:   return X86::COND_B;
3768   case ISD::SETUGE:              // flipped
3769   case ISD::SETULE:
3770   case ISD::SETLE:   return X86::COND_BE;
3771   case ISD::SETONE:
3772   case ISD::SETNE:   return X86::COND_NE;
3773   case ISD::SETUO:   return X86::COND_P;
3774   case ISD::SETO:    return X86::COND_NP;
3775   case ISD::SETOEQ:
3776   case ISD::SETUNE:  return X86::COND_INVALID;
3777   }
3778 }
3779
3780 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3781 /// code. Current x86 isa includes the following FP cmov instructions:
3782 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3783 static bool hasFPCMov(unsigned X86CC) {
3784   switch (X86CC) {
3785   default:
3786     return false;
3787   case X86::COND_B:
3788   case X86::COND_BE:
3789   case X86::COND_E:
3790   case X86::COND_P:
3791   case X86::COND_A:
3792   case X86::COND_AE:
3793   case X86::COND_NE:
3794   case X86::COND_NP:
3795     return true;
3796   }
3797 }
3798
3799 /// isFPImmLegal - Returns true if the target can instruction select the
3800 /// specified FP immediate natively. If false, the legalizer will
3801 /// materialize the FP immediate as a load from a constant pool.
3802 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3803   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3804     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3805       return true;
3806   }
3807   return false;
3808 }
3809
3810 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3811                                               ISD::LoadExtType ExtTy,
3812                                               EVT NewVT) const {
3813   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3814   // relocation target a movq or addq instruction: don't let the load shrink.
3815   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3816   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3817     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3818       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3819   return true;
3820 }
3821
3822 /// \brief Returns true if it is beneficial to convert a load of a constant
3823 /// to just the constant itself.
3824 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3825                                                           Type *Ty) const {
3826   assert(Ty->isIntegerTy());
3827
3828   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3829   if (BitSize == 0 || BitSize > 64)
3830     return false;
3831   return true;
3832 }
3833
3834 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3835                                                 unsigned Index) const {
3836   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3837     return false;
3838
3839   return (Index == 0 || Index == ResVT.getVectorNumElements());
3840 }
3841
3842 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3843   // Speculate cttz only if we can directly use TZCNT.
3844   return Subtarget->hasBMI();
3845 }
3846
3847 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3848   // Speculate ctlz only if we can directly use LZCNT.
3849   return Subtarget->hasLZCNT();
3850 }
3851
3852 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3853 /// the specified range (L, H].
3854 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3855   return (Val < 0) || (Val >= Low && Val < Hi);
3856 }
3857
3858 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3859 /// specified value.
3860 static bool isUndefOrEqual(int Val, int CmpVal) {
3861   return (Val < 0 || Val == CmpVal);
3862 }
3863
3864 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3865 /// from position Pos and ending in Pos+Size, falls within the specified
3866 /// sequential range (Low, Low+Size]. or is undef.
3867 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3868                                        unsigned Pos, unsigned Size, int Low) {
3869   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3870     if (!isUndefOrEqual(Mask[i], Low))
3871       return false;
3872   return true;
3873 }
3874
3875 /// isVEXTRACTIndex - Return true if the specified
3876 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3877 /// suitable for instruction that extract 128 or 256 bit vectors
3878 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3879   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3880   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3881     return false;
3882
3883   // The index should be aligned on a vecWidth-bit boundary.
3884   uint64_t Index =
3885     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3886
3887   MVT VT = N->getSimpleValueType(0);
3888   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3889   bool Result = (Index * ElSize) % vecWidth == 0;
3890
3891   return Result;
3892 }
3893
3894 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3895 /// operand specifies a subvector insert that is suitable for input to
3896 /// insertion of 128 or 256-bit subvectors
3897 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3898   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3899   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3900     return false;
3901   // The index should be aligned on a vecWidth-bit boundary.
3902   uint64_t Index =
3903     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3904
3905   MVT VT = N->getSimpleValueType(0);
3906   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3907   bool Result = (Index * ElSize) % vecWidth == 0;
3908
3909   return Result;
3910 }
3911
3912 bool X86::isVINSERT128Index(SDNode *N) {
3913   return isVINSERTIndex(N, 128);
3914 }
3915
3916 bool X86::isVINSERT256Index(SDNode *N) {
3917   return isVINSERTIndex(N, 256);
3918 }
3919
3920 bool X86::isVEXTRACT128Index(SDNode *N) {
3921   return isVEXTRACTIndex(N, 128);
3922 }
3923
3924 bool X86::isVEXTRACT256Index(SDNode *N) {
3925   return isVEXTRACTIndex(N, 256);
3926 }
3927
3928 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3929   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3930   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3931     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3932
3933   uint64_t Index =
3934     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3935
3936   MVT VecVT = N->getOperand(0).getSimpleValueType();
3937   MVT ElVT = VecVT.getVectorElementType();
3938
3939   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3940   return Index / NumElemsPerChunk;
3941 }
3942
3943 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3944   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3945   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3946     llvm_unreachable("Illegal insert subvector for VINSERT");
3947
3948   uint64_t Index =
3949     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3950
3951   MVT VecVT = N->getSimpleValueType(0);
3952   MVT ElVT = VecVT.getVectorElementType();
3953
3954   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3955   return Index / NumElemsPerChunk;
3956 }
3957
3958 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3959 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3960 /// and VINSERTI128 instructions.
3961 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3962   return getExtractVEXTRACTImmediate(N, 128);
3963 }
3964
3965 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3966 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3967 /// and VINSERTI64x4 instructions.
3968 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3969   return getExtractVEXTRACTImmediate(N, 256);
3970 }
3971
3972 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3973 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3974 /// and VINSERTI128 instructions.
3975 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3976   return getInsertVINSERTImmediate(N, 128);
3977 }
3978
3979 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3980 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3981 /// and VINSERTI64x4 instructions.
3982 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3983   return getInsertVINSERTImmediate(N, 256);
3984 }
3985
3986 /// isZero - Returns true if Elt is a constant integer zero
3987 static bool isZero(SDValue V) {
3988   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3989   return C && C->isNullValue();
3990 }
3991
3992 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3993 /// constant +0.0.
3994 bool X86::isZeroNode(SDValue Elt) {
3995   if (isZero(Elt))
3996     return true;
3997   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3998     return CFP->getValueAPF().isPosZero();
3999   return false;
4000 }
4001
4002 /// getZeroVector - Returns a vector of specified type with all zero elements.
4003 ///
4004 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4005                              SelectionDAG &DAG, SDLoc dl) {
4006   assert(VT.isVector() && "Expected a vector type");
4007
4008   // Always build SSE zero vectors as <4 x i32> bitcasted
4009   // to their dest type. This ensures they get CSE'd.
4010   SDValue Vec;
4011   if (VT.is128BitVector()) {  // SSE
4012     if (Subtarget->hasSSE2()) {  // SSE2
4013       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4014       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4015     } else { // SSE1
4016       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4017       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4018     }
4019   } else if (VT.is256BitVector()) { // AVX
4020     if (Subtarget->hasInt256()) { // AVX2
4021       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4022       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4023       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4024     } else {
4025       // 256-bit logic and arithmetic instructions in AVX are all
4026       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4027       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4028       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4029       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4030     }
4031   } else if (VT.is512BitVector()) { // AVX-512
4032       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4033       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4034                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4035       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4036   } else if (VT.getScalarType() == MVT::i1) {
4037
4038     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4039             && "Unexpected vector type");
4040     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4041             && "Unexpected vector type");
4042     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4043     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4044     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4045   } else
4046     llvm_unreachable("Unexpected vector type");
4047
4048   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4049 }
4050
4051 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4052                                 SelectionDAG &DAG, SDLoc dl,
4053                                 unsigned vectorWidth) {
4054   assert((vectorWidth == 128 || vectorWidth == 256) &&
4055          "Unsupported vector width");
4056   EVT VT = Vec.getValueType();
4057   EVT ElVT = VT.getVectorElementType();
4058   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4059   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4060                                   VT.getVectorNumElements()/Factor);
4061
4062   // Extract from UNDEF is UNDEF.
4063   if (Vec.getOpcode() == ISD::UNDEF)
4064     return DAG.getUNDEF(ResultVT);
4065
4066   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4067   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4068
4069   // This is the index of the first element of the vectorWidth-bit chunk
4070   // we want.
4071   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4072                                * ElemsPerChunk);
4073
4074   // If the input is a buildvector just emit a smaller one.
4075   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4076     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4077                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4078                                     ElemsPerChunk));
4079
4080   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4081   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4082 }
4083
4084 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4085 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4086 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4087 /// instructions or a simple subregister reference. Idx is an index in the
4088 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4089 /// lowering EXTRACT_VECTOR_ELT operations easier.
4090 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4091                                    SelectionDAG &DAG, SDLoc dl) {
4092   assert((Vec.getValueType().is256BitVector() ||
4093           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4094   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4095 }
4096
4097 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4098 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4099                                    SelectionDAG &DAG, SDLoc dl) {
4100   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4101   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4102 }
4103
4104 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4105                                unsigned IdxVal, SelectionDAG &DAG,
4106                                SDLoc dl, unsigned vectorWidth) {
4107   assert((vectorWidth == 128 || vectorWidth == 256) &&
4108          "Unsupported vector width");
4109   // Inserting UNDEF is Result
4110   if (Vec.getOpcode() == ISD::UNDEF)
4111     return Result;
4112   EVT VT = Vec.getValueType();
4113   EVT ElVT = VT.getVectorElementType();
4114   EVT ResultVT = Result.getValueType();
4115
4116   // Insert the relevant vectorWidth bits.
4117   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4118
4119   // This is the index of the first element of the vectorWidth-bit chunk
4120   // we want.
4121   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4122                                * ElemsPerChunk);
4123
4124   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4125   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4126 }
4127
4128 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4129 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4130 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4131 /// simple superregister reference.  Idx is an index in the 128 bits
4132 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4133 /// lowering INSERT_VECTOR_ELT operations easier.
4134 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4135                                   SelectionDAG &DAG, SDLoc dl) {
4136   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4137
4138   // For insertion into the zero index (low half) of a 256-bit vector, it is
4139   // more efficient to generate a blend with immediate instead of an insert*128.
4140   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4141   // extend the subvector to the size of the result vector. Make sure that
4142   // we are not recursing on that node by checking for undef here.
4143   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4144       Result.getOpcode() != ISD::UNDEF) {
4145     EVT ResultVT = Result.getValueType();
4146     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4147     SDValue Undef = DAG.getUNDEF(ResultVT);
4148     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4149                                  Vec, ZeroIndex);
4150
4151     // The blend instruction, and therefore its mask, depend on the data type.
4152     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4153     if (ScalarType.isFloatingPoint()) {
4154       // Choose either vblendps (float) or vblendpd (double).
4155       unsigned ScalarSize = ScalarType.getSizeInBits();
4156       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4157       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4158       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4159       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4160     }
4161
4162     const X86Subtarget &Subtarget =
4163     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4164
4165     // AVX2 is needed for 256-bit integer blend support.
4166     // Integers must be cast to 32-bit because there is only vpblendd;
4167     // vpblendw can't be used for this because it has a handicapped mask.
4168
4169     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4170     // is still more efficient than using the wrong domain vinsertf128 that
4171     // will be created by InsertSubVector().
4172     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4173
4174     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4175     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4176     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4177     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4178   }
4179
4180   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4181 }
4182
4183 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4184                                   SelectionDAG &DAG, SDLoc dl) {
4185   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4186   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4187 }
4188
4189 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4190 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4191 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4192 /// large BUILD_VECTORS.
4193 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4194                                    unsigned NumElems, SelectionDAG &DAG,
4195                                    SDLoc dl) {
4196   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4197   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4198 }
4199
4200 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4201                                    unsigned NumElems, SelectionDAG &DAG,
4202                                    SDLoc dl) {
4203   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4204   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4205 }
4206
4207 /// getOnesVector - Returns a vector of specified type with all bits set.
4208 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4209 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4210 /// Then bitcast to their original type, ensuring they get CSE'd.
4211 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4212                              SDLoc dl) {
4213   assert(VT.isVector() && "Expected a vector type");
4214
4215   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4216   SDValue Vec;
4217   if (VT.is256BitVector()) {
4218     if (HasInt256) { // AVX2
4219       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4220       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4221     } else { // AVX
4222       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4223       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4224     }
4225   } else if (VT.is128BitVector()) {
4226     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4227   } else
4228     llvm_unreachable("Unexpected vector type");
4229
4230   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4231 }
4232
4233 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4234 /// operation of specified width.
4235 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4236                        SDValue V2) {
4237   unsigned NumElems = VT.getVectorNumElements();
4238   SmallVector<int, 8> Mask;
4239   Mask.push_back(NumElems);
4240   for (unsigned i = 1; i != NumElems; ++i)
4241     Mask.push_back(i);
4242   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4243 }
4244
4245 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4246 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4247                           SDValue V2) {
4248   unsigned NumElems = VT.getVectorNumElements();
4249   SmallVector<int, 8> Mask;
4250   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4251     Mask.push_back(i);
4252     Mask.push_back(i + NumElems);
4253   }
4254   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4255 }
4256
4257 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4258 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4259                           SDValue V2) {
4260   unsigned NumElems = VT.getVectorNumElements();
4261   SmallVector<int, 8> Mask;
4262   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4263     Mask.push_back(i + Half);
4264     Mask.push_back(i + NumElems + Half);
4265   }
4266   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4267 }
4268
4269 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4270 /// vector of zero or undef vector.  This produces a shuffle where the low
4271 /// element of V2 is swizzled into the zero/undef vector, landing at element
4272 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4273 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4274                                            bool IsZero,
4275                                            const X86Subtarget *Subtarget,
4276                                            SelectionDAG &DAG) {
4277   MVT VT = V2.getSimpleValueType();
4278   SDValue V1 = IsZero
4279     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4280   unsigned NumElems = VT.getVectorNumElements();
4281   SmallVector<int, 16> MaskVec;
4282   for (unsigned i = 0; i != NumElems; ++i)
4283     // If this is the insertion idx, put the low elt of V2 here.
4284     MaskVec.push_back(i == Idx ? NumElems : i);
4285   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4286 }
4287
4288 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4289 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4290 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4291 /// shuffles which use a single input multiple times, and in those cases it will
4292 /// adjust the mask to only have indices within that single input.
4293 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4294                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4295   unsigned NumElems = VT.getVectorNumElements();
4296   SDValue ImmN;
4297
4298   IsUnary = false;
4299   bool IsFakeUnary = false;
4300   switch(N->getOpcode()) {
4301   case X86ISD::BLENDI:
4302     ImmN = N->getOperand(N->getNumOperands()-1);
4303     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4304     break;
4305   case X86ISD::SHUFP:
4306     ImmN = N->getOperand(N->getNumOperands()-1);
4307     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4308     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4309     break;
4310   case X86ISD::UNPCKH:
4311     DecodeUNPCKHMask(VT, Mask);
4312     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4313     break;
4314   case X86ISD::UNPCKL:
4315     DecodeUNPCKLMask(VT, Mask);
4316     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4317     break;
4318   case X86ISD::MOVHLPS:
4319     DecodeMOVHLPSMask(NumElems, Mask);
4320     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4321     break;
4322   case X86ISD::MOVLHPS:
4323     DecodeMOVLHPSMask(NumElems, Mask);
4324     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4325     break;
4326   case X86ISD::PALIGNR:
4327     ImmN = N->getOperand(N->getNumOperands()-1);
4328     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4329     break;
4330   case X86ISD::PSHUFD:
4331   case X86ISD::VPERMILPI:
4332     ImmN = N->getOperand(N->getNumOperands()-1);
4333     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4334     IsUnary = true;
4335     break;
4336   case X86ISD::PSHUFHW:
4337     ImmN = N->getOperand(N->getNumOperands()-1);
4338     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4339     IsUnary = true;
4340     break;
4341   case X86ISD::PSHUFLW:
4342     ImmN = N->getOperand(N->getNumOperands()-1);
4343     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4344     IsUnary = true;
4345     break;
4346   case X86ISD::PSHUFB: {
4347     IsUnary = true;
4348     SDValue MaskNode = N->getOperand(1);
4349     while (MaskNode->getOpcode() == ISD::BITCAST)
4350       MaskNode = MaskNode->getOperand(0);
4351
4352     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4353       // If we have a build-vector, then things are easy.
4354       EVT VT = MaskNode.getValueType();
4355       assert(VT.isVector() &&
4356              "Can't produce a non-vector with a build_vector!");
4357       if (!VT.isInteger())
4358         return false;
4359
4360       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4361
4362       SmallVector<uint64_t, 32> RawMask;
4363       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4364         SDValue Op = MaskNode->getOperand(i);
4365         if (Op->getOpcode() == ISD::UNDEF) {
4366           RawMask.push_back((uint64_t)SM_SentinelUndef);
4367           continue;
4368         }
4369         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4370         if (!CN)
4371           return false;
4372         APInt MaskElement = CN->getAPIntValue();
4373
4374         // We now have to decode the element which could be any integer size and
4375         // extract each byte of it.
4376         for (int j = 0; j < NumBytesPerElement; ++j) {
4377           // Note that this is x86 and so always little endian: the low byte is
4378           // the first byte of the mask.
4379           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4380           MaskElement = MaskElement.lshr(8);
4381         }
4382       }
4383       DecodePSHUFBMask(RawMask, Mask);
4384       break;
4385     }
4386
4387     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4388     if (!MaskLoad)
4389       return false;
4390
4391     SDValue Ptr = MaskLoad->getBasePtr();
4392     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4393         Ptr->getOpcode() == X86ISD::WrapperRIP)
4394       Ptr = Ptr->getOperand(0);
4395
4396     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4397     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4398       return false;
4399
4400     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4401       DecodePSHUFBMask(C, Mask);
4402       if (Mask.empty())
4403         return false;
4404       break;
4405     }
4406
4407     return false;
4408   }
4409   case X86ISD::VPERMI:
4410     ImmN = N->getOperand(N->getNumOperands()-1);
4411     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4412     IsUnary = true;
4413     break;
4414   case X86ISD::MOVSS:
4415   case X86ISD::MOVSD:
4416     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4417     break;
4418   case X86ISD::VPERM2X128:
4419     ImmN = N->getOperand(N->getNumOperands()-1);
4420     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4421     if (Mask.empty()) return false;
4422     break;
4423   case X86ISD::MOVSLDUP:
4424     DecodeMOVSLDUPMask(VT, Mask);
4425     IsUnary = true;
4426     break;
4427   case X86ISD::MOVSHDUP:
4428     DecodeMOVSHDUPMask(VT, Mask);
4429     IsUnary = true;
4430     break;
4431   case X86ISD::MOVDDUP:
4432     DecodeMOVDDUPMask(VT, Mask);
4433     IsUnary = true;
4434     break;
4435   case X86ISD::MOVLHPD:
4436   case X86ISD::MOVLPD:
4437   case X86ISD::MOVLPS:
4438     // Not yet implemented
4439     return false;
4440   default: llvm_unreachable("unknown target shuffle node");
4441   }
4442
4443   // If we have a fake unary shuffle, the shuffle mask is spread across two
4444   // inputs that are actually the same node. Re-map the mask to always point
4445   // into the first input.
4446   if (IsFakeUnary)
4447     for (int &M : Mask)
4448       if (M >= (int)Mask.size())
4449         M -= Mask.size();
4450
4451   return true;
4452 }
4453
4454 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4455 /// element of the result of the vector shuffle.
4456 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4457                                    unsigned Depth) {
4458   if (Depth == 6)
4459     return SDValue();  // Limit search depth.
4460
4461   SDValue V = SDValue(N, 0);
4462   EVT VT = V.getValueType();
4463   unsigned Opcode = V.getOpcode();
4464
4465   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4466   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4467     int Elt = SV->getMaskElt(Index);
4468
4469     if (Elt < 0)
4470       return DAG.getUNDEF(VT.getVectorElementType());
4471
4472     unsigned NumElems = VT.getVectorNumElements();
4473     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4474                                          : SV->getOperand(1);
4475     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4476   }
4477
4478   // Recurse into target specific vector shuffles to find scalars.
4479   if (isTargetShuffle(Opcode)) {
4480     MVT ShufVT = V.getSimpleValueType();
4481     unsigned NumElems = ShufVT.getVectorNumElements();
4482     SmallVector<int, 16> ShuffleMask;
4483     bool IsUnary;
4484
4485     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4486       return SDValue();
4487
4488     int Elt = ShuffleMask[Index];
4489     if (Elt < 0)
4490       return DAG.getUNDEF(ShufVT.getVectorElementType());
4491
4492     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4493                                          : N->getOperand(1);
4494     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4495                                Depth+1);
4496   }
4497
4498   // Actual nodes that may contain scalar elements
4499   if (Opcode == ISD::BITCAST) {
4500     V = V.getOperand(0);
4501     EVT SrcVT = V.getValueType();
4502     unsigned NumElems = VT.getVectorNumElements();
4503
4504     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4505       return SDValue();
4506   }
4507
4508   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4509     return (Index == 0) ? V.getOperand(0)
4510                         : DAG.getUNDEF(VT.getVectorElementType());
4511
4512   if (V.getOpcode() == ISD::BUILD_VECTOR)
4513     return V.getOperand(Index);
4514
4515   return SDValue();
4516 }
4517
4518 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4519 ///
4520 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4521                                        unsigned NumNonZero, unsigned NumZero,
4522                                        SelectionDAG &DAG,
4523                                        const X86Subtarget* Subtarget,
4524                                        const TargetLowering &TLI) {
4525   if (NumNonZero > 8)
4526     return SDValue();
4527
4528   SDLoc dl(Op);
4529   SDValue V;
4530   bool First = true;
4531
4532   // SSE4.1 - use PINSRB to insert each byte directly.
4533   if (Subtarget->hasSSE41()) {
4534     for (unsigned i = 0; i < 16; ++i) {
4535       bool isNonZero = (NonZeros & (1 << i)) != 0;
4536       if (isNonZero) {
4537         if (First) {
4538           if (NumZero)
4539             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4540           else
4541             V = DAG.getUNDEF(MVT::v16i8);
4542           First = false;
4543         }
4544         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4545                         MVT::v16i8, V, Op.getOperand(i),
4546                         DAG.getIntPtrConstant(i, dl));
4547       }
4548     }
4549
4550     return V;
4551   }
4552
4553   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4554   for (unsigned i = 0; i < 16; ++i) {
4555     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4556     if (ThisIsNonZero && First) {
4557       if (NumZero)
4558         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4559       else
4560         V = DAG.getUNDEF(MVT::v8i16);
4561       First = false;
4562     }
4563
4564     if ((i & 1) != 0) {
4565       SDValue ThisElt, LastElt;
4566       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4567       if (LastIsNonZero) {
4568         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4569                               MVT::i16, Op.getOperand(i-1));
4570       }
4571       if (ThisIsNonZero) {
4572         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4573         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4574                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4575         if (LastIsNonZero)
4576           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4577       } else
4578         ThisElt = LastElt;
4579
4580       if (ThisElt.getNode())
4581         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4582                         DAG.getIntPtrConstant(i/2, dl));
4583     }
4584   }
4585
4586   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4587 }
4588
4589 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4590 ///
4591 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4592                                      unsigned NumNonZero, unsigned NumZero,
4593                                      SelectionDAG &DAG,
4594                                      const X86Subtarget* Subtarget,
4595                                      const TargetLowering &TLI) {
4596   if (NumNonZero > 4)
4597     return SDValue();
4598
4599   SDLoc dl(Op);
4600   SDValue V;
4601   bool First = true;
4602   for (unsigned i = 0; i < 8; ++i) {
4603     bool isNonZero = (NonZeros & (1 << i)) != 0;
4604     if (isNonZero) {
4605       if (First) {
4606         if (NumZero)
4607           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4608         else
4609           V = DAG.getUNDEF(MVT::v8i16);
4610         First = false;
4611       }
4612       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4613                       MVT::v8i16, V, Op.getOperand(i),
4614                       DAG.getIntPtrConstant(i, dl));
4615     }
4616   }
4617
4618   return V;
4619 }
4620
4621 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4622 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4623                                      const X86Subtarget *Subtarget,
4624                                      const TargetLowering &TLI) {
4625   // Find all zeroable elements.
4626   std::bitset<4> Zeroable;
4627   for (int i=0; i < 4; ++i) {
4628     SDValue Elt = Op->getOperand(i);
4629     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4630   }
4631   assert(Zeroable.size() - Zeroable.count() > 1 &&
4632          "We expect at least two non-zero elements!");
4633
4634   // We only know how to deal with build_vector nodes where elements are either
4635   // zeroable or extract_vector_elt with constant index.
4636   SDValue FirstNonZero;
4637   unsigned FirstNonZeroIdx;
4638   for (unsigned i=0; i < 4; ++i) {
4639     if (Zeroable[i])
4640       continue;
4641     SDValue Elt = Op->getOperand(i);
4642     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4643         !isa<ConstantSDNode>(Elt.getOperand(1)))
4644       return SDValue();
4645     // Make sure that this node is extracting from a 128-bit vector.
4646     MVT VT = Elt.getOperand(0).getSimpleValueType();
4647     if (!VT.is128BitVector())
4648       return SDValue();
4649     if (!FirstNonZero.getNode()) {
4650       FirstNonZero = Elt;
4651       FirstNonZeroIdx = i;
4652     }
4653   }
4654
4655   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4656   SDValue V1 = FirstNonZero.getOperand(0);
4657   MVT VT = V1.getSimpleValueType();
4658
4659   // See if this build_vector can be lowered as a blend with zero.
4660   SDValue Elt;
4661   unsigned EltMaskIdx, EltIdx;
4662   int Mask[4];
4663   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4664     if (Zeroable[EltIdx]) {
4665       // The zero vector will be on the right hand side.
4666       Mask[EltIdx] = EltIdx+4;
4667       continue;
4668     }
4669
4670     Elt = Op->getOperand(EltIdx);
4671     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4672     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4673     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4674       break;
4675     Mask[EltIdx] = EltIdx;
4676   }
4677
4678   if (EltIdx == 4) {
4679     // Let the shuffle legalizer deal with blend operations.
4680     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4681     if (V1.getSimpleValueType() != VT)
4682       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4683     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4684   }
4685
4686   // See if we can lower this build_vector to a INSERTPS.
4687   if (!Subtarget->hasSSE41())
4688     return SDValue();
4689
4690   SDValue V2 = Elt.getOperand(0);
4691   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4692     V1 = SDValue();
4693
4694   bool CanFold = true;
4695   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4696     if (Zeroable[i])
4697       continue;
4698
4699     SDValue Current = Op->getOperand(i);
4700     SDValue SrcVector = Current->getOperand(0);
4701     if (!V1.getNode())
4702       V1 = SrcVector;
4703     CanFold = SrcVector == V1 &&
4704       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4705   }
4706
4707   if (!CanFold)
4708     return SDValue();
4709
4710   assert(V1.getNode() && "Expected at least two non-zero elements!");
4711   if (V1.getSimpleValueType() != MVT::v4f32)
4712     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4713   if (V2.getSimpleValueType() != MVT::v4f32)
4714     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4715
4716   // Ok, we can emit an INSERTPS instruction.
4717   unsigned ZMask = Zeroable.to_ulong();
4718
4719   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4720   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4721   SDLoc DL(Op);
4722   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4723                                DAG.getIntPtrConstant(InsertPSMask, DL));
4724   return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4725 }
4726
4727 /// Return a vector logical shift node.
4728 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4729                          unsigned NumBits, SelectionDAG &DAG,
4730                          const TargetLowering &TLI, SDLoc dl) {
4731   assert(VT.is128BitVector() && "Unknown type for VShift");
4732   MVT ShVT = MVT::v2i64;
4733   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4734   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4735   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4736   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4737   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4738   return DAG.getNode(ISD::BITCAST, dl, VT,
4739                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4740 }
4741
4742 static SDValue
4743 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4744
4745   // Check if the scalar load can be widened into a vector load. And if
4746   // the address is "base + cst" see if the cst can be "absorbed" into
4747   // the shuffle mask.
4748   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4749     SDValue Ptr = LD->getBasePtr();
4750     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4751       return SDValue();
4752     EVT PVT = LD->getValueType(0);
4753     if (PVT != MVT::i32 && PVT != MVT::f32)
4754       return SDValue();
4755
4756     int FI = -1;
4757     int64_t Offset = 0;
4758     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4759       FI = FINode->getIndex();
4760       Offset = 0;
4761     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4762                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4763       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4764       Offset = Ptr.getConstantOperandVal(1);
4765       Ptr = Ptr.getOperand(0);
4766     } else {
4767       return SDValue();
4768     }
4769
4770     // FIXME: 256-bit vector instructions don't require a strict alignment,
4771     // improve this code to support it better.
4772     unsigned RequiredAlign = VT.getSizeInBits()/8;
4773     SDValue Chain = LD->getChain();
4774     // Make sure the stack object alignment is at least 16 or 32.
4775     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4776     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4777       if (MFI->isFixedObjectIndex(FI)) {
4778         // Can't change the alignment. FIXME: It's possible to compute
4779         // the exact stack offset and reference FI + adjust offset instead.
4780         // If someone *really* cares about this. That's the way to implement it.
4781         return SDValue();
4782       } else {
4783         MFI->setObjectAlignment(FI, RequiredAlign);
4784       }
4785     }
4786
4787     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4788     // Ptr + (Offset & ~15).
4789     if (Offset < 0)
4790       return SDValue();
4791     if ((Offset % RequiredAlign) & 3)
4792       return SDValue();
4793     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4794     if (StartOffset) {
4795       SDLoc DL(Ptr);
4796       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4797                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4798     }
4799
4800     int EltNo = (Offset - StartOffset) >> 2;
4801     unsigned NumElems = VT.getVectorNumElements();
4802
4803     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4804     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4805                              LD->getPointerInfo().getWithOffset(StartOffset),
4806                              false, false, false, 0);
4807
4808     SmallVector<int, 8> Mask(NumElems, EltNo);
4809
4810     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4811   }
4812
4813   return SDValue();
4814 }
4815
4816 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4817 /// elements can be replaced by a single large load which has the same value as
4818 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4819 ///
4820 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4821 ///
4822 /// FIXME: we'd also like to handle the case where the last elements are zero
4823 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4824 /// There's even a handy isZeroNode for that purpose.
4825 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4826                                         SDLoc &DL, SelectionDAG &DAG,
4827                                         bool isAfterLegalize) {
4828   unsigned NumElems = Elts.size();
4829
4830   LoadSDNode *LDBase = nullptr;
4831   unsigned LastLoadedElt = -1U;
4832
4833   // For each element in the initializer, see if we've found a load or an undef.
4834   // If we don't find an initial load element, or later load elements are
4835   // non-consecutive, bail out.
4836   for (unsigned i = 0; i < NumElems; ++i) {
4837     SDValue Elt = Elts[i];
4838     // Look through a bitcast.
4839     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4840       Elt = Elt.getOperand(0);
4841     if (!Elt.getNode() ||
4842         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4843       return SDValue();
4844     if (!LDBase) {
4845       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4846         return SDValue();
4847       LDBase = cast<LoadSDNode>(Elt.getNode());
4848       LastLoadedElt = i;
4849       continue;
4850     }
4851     if (Elt.getOpcode() == ISD::UNDEF)
4852       continue;
4853
4854     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4855     EVT LdVT = Elt.getValueType();
4856     // Each loaded element must be the correct fractional portion of the
4857     // requested vector load.
4858     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4859       return SDValue();
4860     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4861       return SDValue();
4862     LastLoadedElt = i;
4863   }
4864
4865   // If we have found an entire vector of loads and undefs, then return a large
4866   // load of the entire vector width starting at the base pointer.  If we found
4867   // consecutive loads for the low half, generate a vzext_load node.
4868   if (LastLoadedElt == NumElems - 1) {
4869     assert(LDBase && "Did not find base load for merging consecutive loads");
4870     EVT EltVT = LDBase->getValueType(0);
4871     // Ensure that the input vector size for the merged loads matches the
4872     // cumulative size of the input elements.
4873     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4874       return SDValue();
4875
4876     if (isAfterLegalize &&
4877         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4878       return SDValue();
4879
4880     SDValue NewLd = SDValue();
4881
4882     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4883                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4884                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4885                         LDBase->getAlignment());
4886
4887     if (LDBase->hasAnyUseOfValue(1)) {
4888       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4889                                      SDValue(LDBase, 1),
4890                                      SDValue(NewLd.getNode(), 1));
4891       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4892       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4893                              SDValue(NewLd.getNode(), 1));
4894     }
4895
4896     return NewLd;
4897   }
4898
4899   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4900   //of a v4i32 / v4f32. It's probably worth generalizing.
4901   EVT EltVT = VT.getVectorElementType();
4902   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4903       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4904     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4905     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4906     SDValue ResNode =
4907         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4908                                 LDBase->getPointerInfo(),
4909                                 LDBase->getAlignment(),
4910                                 false/*isVolatile*/, true/*ReadMem*/,
4911                                 false/*WriteMem*/);
4912
4913     // Make sure the newly-created LOAD is in the same position as LDBase in
4914     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4915     // update uses of LDBase's output chain to use the TokenFactor.
4916     if (LDBase->hasAnyUseOfValue(1)) {
4917       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4918                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4919       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4920       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4921                              SDValue(ResNode.getNode(), 1));
4922     }
4923
4924     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4925   }
4926   return SDValue();
4927 }
4928
4929 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4930 /// to generate a splat value for the following cases:
4931 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4932 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4933 /// a scalar load, or a constant.
4934 /// The VBROADCAST node is returned when a pattern is found,
4935 /// or SDValue() otherwise.
4936 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4937                                     SelectionDAG &DAG) {
4938   // VBROADCAST requires AVX.
4939   // TODO: Splats could be generated for non-AVX CPUs using SSE
4940   // instructions, but there's less potential gain for only 128-bit vectors.
4941   if (!Subtarget->hasAVX())
4942     return SDValue();
4943
4944   MVT VT = Op.getSimpleValueType();
4945   SDLoc dl(Op);
4946
4947   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4948          "Unsupported vector type for broadcast.");
4949
4950   SDValue Ld;
4951   bool ConstSplatVal;
4952
4953   switch (Op.getOpcode()) {
4954     default:
4955       // Unknown pattern found.
4956       return SDValue();
4957
4958     case ISD::BUILD_VECTOR: {
4959       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4960       BitVector UndefElements;
4961       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4962
4963       // We need a splat of a single value to use broadcast, and it doesn't
4964       // make any sense if the value is only in one element of the vector.
4965       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4966         return SDValue();
4967
4968       Ld = Splat;
4969       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4970                        Ld.getOpcode() == ISD::ConstantFP);
4971
4972       // Make sure that all of the users of a non-constant load are from the
4973       // BUILD_VECTOR node.
4974       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4975         return SDValue();
4976       break;
4977     }
4978
4979     case ISD::VECTOR_SHUFFLE: {
4980       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4981
4982       // Shuffles must have a splat mask where the first element is
4983       // broadcasted.
4984       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4985         return SDValue();
4986
4987       SDValue Sc = Op.getOperand(0);
4988       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4989           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4990
4991         if (!Subtarget->hasInt256())
4992           return SDValue();
4993
4994         // Use the register form of the broadcast instruction available on AVX2.
4995         if (VT.getSizeInBits() >= 256)
4996           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4997         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4998       }
4999
5000       Ld = Sc.getOperand(0);
5001       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5002                        Ld.getOpcode() == ISD::ConstantFP);
5003
5004       // The scalar_to_vector node and the suspected
5005       // load node must have exactly one user.
5006       // Constants may have multiple users.
5007
5008       // AVX-512 has register version of the broadcast
5009       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5010         Ld.getValueType().getSizeInBits() >= 32;
5011       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5012           !hasRegVer))
5013         return SDValue();
5014       break;
5015     }
5016   }
5017
5018   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5019   bool IsGE256 = (VT.getSizeInBits() >= 256);
5020
5021   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5022   // instruction to save 8 or more bytes of constant pool data.
5023   // TODO: If multiple splats are generated to load the same constant,
5024   // it may be detrimental to overall size. There needs to be a way to detect
5025   // that condition to know if this is truly a size win.
5026   const Function *F = DAG.getMachineFunction().getFunction();
5027   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5028
5029   // Handle broadcasting a single constant scalar from the constant pool
5030   // into a vector.
5031   // On Sandybridge (no AVX2), it is still better to load a constant vector
5032   // from the constant pool and not to broadcast it from a scalar.
5033   // But override that restriction when optimizing for size.
5034   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5035   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5036     EVT CVT = Ld.getValueType();
5037     assert(!CVT.isVector() && "Must not broadcast a vector type");
5038
5039     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5040     // For size optimization, also splat v2f64 and v2i64, and for size opt
5041     // with AVX2, also splat i8 and i16.
5042     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5043     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5044         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5045       const Constant *C = nullptr;
5046       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5047         C = CI->getConstantIntValue();
5048       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5049         C = CF->getConstantFPValue();
5050
5051       assert(C && "Invalid constant type");
5052
5053       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5054       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5055       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5056       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5057                        MachinePointerInfo::getConstantPool(),
5058                        false, false, false, Alignment);
5059
5060       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5061     }
5062   }
5063
5064   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5065
5066   // Handle AVX2 in-register broadcasts.
5067   if (!IsLoad && Subtarget->hasInt256() &&
5068       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5069     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5070
5071   // The scalar source must be a normal load.
5072   if (!IsLoad)
5073     return SDValue();
5074
5075   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5076       (Subtarget->hasVLX() && ScalarSize == 64))
5077     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5078
5079   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5080   // double since there is no vbroadcastsd xmm
5081   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5082     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5083       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5084   }
5085
5086   // Unsupported broadcast.
5087   return SDValue();
5088 }
5089
5090 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5091 /// underlying vector and index.
5092 ///
5093 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5094 /// index.
5095 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5096                                          SDValue ExtIdx) {
5097   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5098   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5099     return Idx;
5100
5101   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5102   // lowered this:
5103   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5104   // to:
5105   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5106   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5107   //                           undef)
5108   //                       Constant<0>)
5109   // In this case the vector is the extract_subvector expression and the index
5110   // is 2, as specified by the shuffle.
5111   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5112   SDValue ShuffleVec = SVOp->getOperand(0);
5113   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5114   assert(ShuffleVecVT.getVectorElementType() ==
5115          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5116
5117   int ShuffleIdx = SVOp->getMaskElt(Idx);
5118   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5119     ExtractedFromVec = ShuffleVec;
5120     return ShuffleIdx;
5121   }
5122   return Idx;
5123 }
5124
5125 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5126   MVT VT = Op.getSimpleValueType();
5127
5128   // Skip if insert_vec_elt is not supported.
5129   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5130   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5131     return SDValue();
5132
5133   SDLoc DL(Op);
5134   unsigned NumElems = Op.getNumOperands();
5135
5136   SDValue VecIn1;
5137   SDValue VecIn2;
5138   SmallVector<unsigned, 4> InsertIndices;
5139   SmallVector<int, 8> Mask(NumElems, -1);
5140
5141   for (unsigned i = 0; i != NumElems; ++i) {
5142     unsigned Opc = Op.getOperand(i).getOpcode();
5143
5144     if (Opc == ISD::UNDEF)
5145       continue;
5146
5147     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5148       // Quit if more than 1 elements need inserting.
5149       if (InsertIndices.size() > 1)
5150         return SDValue();
5151
5152       InsertIndices.push_back(i);
5153       continue;
5154     }
5155
5156     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5157     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5158     // Quit if non-constant index.
5159     if (!isa<ConstantSDNode>(ExtIdx))
5160       return SDValue();
5161     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5162
5163     // Quit if extracted from vector of different type.
5164     if (ExtractedFromVec.getValueType() != VT)
5165       return SDValue();
5166
5167     if (!VecIn1.getNode())
5168       VecIn1 = ExtractedFromVec;
5169     else if (VecIn1 != ExtractedFromVec) {
5170       if (!VecIn2.getNode())
5171         VecIn2 = ExtractedFromVec;
5172       else if (VecIn2 != ExtractedFromVec)
5173         // Quit if more than 2 vectors to shuffle
5174         return SDValue();
5175     }
5176
5177     if (ExtractedFromVec == VecIn1)
5178       Mask[i] = Idx;
5179     else if (ExtractedFromVec == VecIn2)
5180       Mask[i] = Idx + NumElems;
5181   }
5182
5183   if (!VecIn1.getNode())
5184     return SDValue();
5185
5186   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5187   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5188   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5189     unsigned Idx = InsertIndices[i];
5190     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5191                      DAG.getIntPtrConstant(Idx, DL));
5192   }
5193
5194   return NV;
5195 }
5196
5197 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5198   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5199          Op.getScalarValueSizeInBits() == 1 &&
5200          "Can not convert non-constant vector");
5201   uint64_t Immediate = 0;
5202   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5203     SDValue In = Op.getOperand(idx);
5204     if (In.getOpcode() != ISD::UNDEF)
5205       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5206   }
5207   SDLoc dl(Op);
5208   MVT VT =
5209    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5210   return DAG.getConstant(Immediate, dl, VT);
5211 }
5212 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5213 SDValue
5214 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5215
5216   MVT VT = Op.getSimpleValueType();
5217   assert((VT.getVectorElementType() == MVT::i1) &&
5218          "Unexpected type in LowerBUILD_VECTORvXi1!");
5219
5220   SDLoc dl(Op);
5221   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5222     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5223     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5224     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5225   }
5226
5227   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5228     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5229     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5230     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5231   }
5232
5233   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5234     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5235     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5236       return DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5237     SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5238     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5239                         DAG.getIntPtrConstant(0, dl));
5240   }
5241
5242   // Vector has one or more non-const elements
5243   uint64_t Immediate = 0;
5244   SmallVector<unsigned, 16> NonConstIdx;
5245   bool IsSplat = true;
5246   bool HasConstElts = false;
5247   int SplatIdx = -1;
5248   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5249     SDValue In = Op.getOperand(idx);
5250     if (In.getOpcode() == ISD::UNDEF)
5251       continue;
5252     if (!isa<ConstantSDNode>(In)) 
5253       NonConstIdx.push_back(idx);
5254     else {
5255       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5256       HasConstElts = true;
5257     }
5258     if (SplatIdx == -1)
5259       SplatIdx = idx;
5260     else if (In != Op.getOperand(SplatIdx))
5261       IsSplat = false;
5262   }
5263
5264   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5265   if (IsSplat)
5266     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5267                        DAG.getConstant(1, dl, VT),
5268                        DAG.getConstant(0, dl, VT));
5269
5270   // insert elements one by one
5271   SDValue DstVec;
5272   SDValue Imm;
5273   if (Immediate) {
5274     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5275     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5276   }
5277   else if (HasConstElts)
5278     Imm = DAG.getConstant(0, dl, VT);
5279   else 
5280     Imm = DAG.getUNDEF(VT);
5281   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5282     DstVec = DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5283   else {
5284     SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5285     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5286                          DAG.getIntPtrConstant(0, dl));
5287   }
5288
5289   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5290     unsigned InsertIdx = NonConstIdx[i];
5291     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5292                          Op.getOperand(InsertIdx),
5293                          DAG.getIntPtrConstant(InsertIdx, dl));
5294   }
5295   return DstVec;
5296 }
5297
5298 /// \brief Return true if \p N implements a horizontal binop and return the
5299 /// operands for the horizontal binop into V0 and V1.
5300 ///
5301 /// This is a helper function of LowerToHorizontalOp().
5302 /// This function checks that the build_vector \p N in input implements a
5303 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5304 /// operation to match.
5305 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5306 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5307 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5308 /// arithmetic sub.
5309 ///
5310 /// This function only analyzes elements of \p N whose indices are
5311 /// in range [BaseIdx, LastIdx).
5312 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5313                               SelectionDAG &DAG,
5314                               unsigned BaseIdx, unsigned LastIdx,
5315                               SDValue &V0, SDValue &V1) {
5316   EVT VT = N->getValueType(0);
5317
5318   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5319   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5320          "Invalid Vector in input!");
5321
5322   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5323   bool CanFold = true;
5324   unsigned ExpectedVExtractIdx = BaseIdx;
5325   unsigned NumElts = LastIdx - BaseIdx;
5326   V0 = DAG.getUNDEF(VT);
5327   V1 = DAG.getUNDEF(VT);
5328
5329   // Check if N implements a horizontal binop.
5330   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5331     SDValue Op = N->getOperand(i + BaseIdx);
5332
5333     // Skip UNDEFs.
5334     if (Op->getOpcode() == ISD::UNDEF) {
5335       // Update the expected vector extract index.
5336       if (i * 2 == NumElts)
5337         ExpectedVExtractIdx = BaseIdx;
5338       ExpectedVExtractIdx += 2;
5339       continue;
5340     }
5341
5342     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5343
5344     if (!CanFold)
5345       break;
5346
5347     SDValue Op0 = Op.getOperand(0);
5348     SDValue Op1 = Op.getOperand(1);
5349
5350     // Try to match the following pattern:
5351     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5352     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5353         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5354         Op0.getOperand(0) == Op1.getOperand(0) &&
5355         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5356         isa<ConstantSDNode>(Op1.getOperand(1)));
5357     if (!CanFold)
5358       break;
5359
5360     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5361     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5362
5363     if (i * 2 < NumElts) {
5364       if (V0.getOpcode() == ISD::UNDEF) {
5365         V0 = Op0.getOperand(0);
5366         if (V0.getValueType() != VT)
5367           return false;
5368       }
5369     } else {
5370       if (V1.getOpcode() == ISD::UNDEF) {
5371         V1 = Op0.getOperand(0);
5372         if (V1.getValueType() != VT)
5373           return false;
5374       }
5375       if (i * 2 == NumElts)
5376         ExpectedVExtractIdx = BaseIdx;
5377     }
5378
5379     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5380     if (I0 == ExpectedVExtractIdx)
5381       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5382     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5383       // Try to match the following dag sequence:
5384       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5385       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5386     } else
5387       CanFold = false;
5388
5389     ExpectedVExtractIdx += 2;
5390   }
5391
5392   return CanFold;
5393 }
5394
5395 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5396 /// a concat_vector.
5397 ///
5398 /// This is a helper function of LowerToHorizontalOp().
5399 /// This function expects two 256-bit vectors called V0 and V1.
5400 /// At first, each vector is split into two separate 128-bit vectors.
5401 /// Then, the resulting 128-bit vectors are used to implement two
5402 /// horizontal binary operations.
5403 ///
5404 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5405 ///
5406 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5407 /// the two new horizontal binop.
5408 /// When Mode is set, the first horizontal binop dag node would take as input
5409 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5410 /// horizontal binop dag node would take as input the lower 128-bit of V1
5411 /// and the upper 128-bit of V1.
5412 ///   Example:
5413 ///     HADD V0_LO, V0_HI
5414 ///     HADD V1_LO, V1_HI
5415 ///
5416 /// Otherwise, the first horizontal binop dag node takes as input the lower
5417 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5418 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5419 ///   Example:
5420 ///     HADD V0_LO, V1_LO
5421 ///     HADD V0_HI, V1_HI
5422 ///
5423 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5424 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5425 /// the upper 128-bits of the result.
5426 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5427                                      SDLoc DL, SelectionDAG &DAG,
5428                                      unsigned X86Opcode, bool Mode,
5429                                      bool isUndefLO, bool isUndefHI) {
5430   EVT VT = V0.getValueType();
5431   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5432          "Invalid nodes in input!");
5433
5434   unsigned NumElts = VT.getVectorNumElements();
5435   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5436   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5437   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5438   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5439   EVT NewVT = V0_LO.getValueType();
5440
5441   SDValue LO = DAG.getUNDEF(NewVT);
5442   SDValue HI = DAG.getUNDEF(NewVT);
5443
5444   if (Mode) {
5445     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5446     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5447       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5448     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5449       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5450   } else {
5451     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5452     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5453                        V1_LO->getOpcode() != ISD::UNDEF))
5454       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5455
5456     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5457                        V1_HI->getOpcode() != ISD::UNDEF))
5458       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5459   }
5460
5461   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5462 }
5463
5464 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5465 /// node.
5466 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5467                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5468   EVT VT = BV->getValueType(0);
5469   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5470       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5471     return SDValue();
5472
5473   SDLoc DL(BV);
5474   unsigned NumElts = VT.getVectorNumElements();
5475   SDValue InVec0 = DAG.getUNDEF(VT);
5476   SDValue InVec1 = DAG.getUNDEF(VT);
5477
5478   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5479           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5480
5481   // Odd-numbered elements in the input build vector are obtained from
5482   // adding two integer/float elements.
5483   // Even-numbered elements in the input build vector are obtained from
5484   // subtracting two integer/float elements.
5485   unsigned ExpectedOpcode = ISD::FSUB;
5486   unsigned NextExpectedOpcode = ISD::FADD;
5487   bool AddFound = false;
5488   bool SubFound = false;
5489
5490   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5491     SDValue Op = BV->getOperand(i);
5492
5493     // Skip 'undef' values.
5494     unsigned Opcode = Op.getOpcode();
5495     if (Opcode == ISD::UNDEF) {
5496       std::swap(ExpectedOpcode, NextExpectedOpcode);
5497       continue;
5498     }
5499
5500     // Early exit if we found an unexpected opcode.
5501     if (Opcode != ExpectedOpcode)
5502       return SDValue();
5503
5504     SDValue Op0 = Op.getOperand(0);
5505     SDValue Op1 = Op.getOperand(1);
5506
5507     // Try to match the following pattern:
5508     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5509     // Early exit if we cannot match that sequence.
5510     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5511         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5512         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5513         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5514         Op0.getOperand(1) != Op1.getOperand(1))
5515       return SDValue();
5516
5517     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5518     if (I0 != i)
5519       return SDValue();
5520
5521     // We found a valid add/sub node. Update the information accordingly.
5522     if (i & 1)
5523       AddFound = true;
5524     else
5525       SubFound = true;
5526
5527     // Update InVec0 and InVec1.
5528     if (InVec0.getOpcode() == ISD::UNDEF) {
5529       InVec0 = Op0.getOperand(0);
5530       if (InVec0.getValueType() != VT)
5531         return SDValue();
5532     }
5533     if (InVec1.getOpcode() == ISD::UNDEF) {
5534       InVec1 = Op1.getOperand(0);
5535       if (InVec1.getValueType() != VT)
5536         return SDValue();
5537     }
5538
5539     // Make sure that operands in input to each add/sub node always
5540     // come from a same pair of vectors.
5541     if (InVec0 != Op0.getOperand(0)) {
5542       if (ExpectedOpcode == ISD::FSUB)
5543         return SDValue();
5544
5545       // FADD is commutable. Try to commute the operands
5546       // and then test again.
5547       std::swap(Op0, Op1);
5548       if (InVec0 != Op0.getOperand(0))
5549         return SDValue();
5550     }
5551
5552     if (InVec1 != Op1.getOperand(0))
5553       return SDValue();
5554
5555     // Update the pair of expected opcodes.
5556     std::swap(ExpectedOpcode, NextExpectedOpcode);
5557   }
5558
5559   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5560   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5561       InVec1.getOpcode() != ISD::UNDEF)
5562     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5563
5564   return SDValue();
5565 }
5566
5567 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5568 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5569                                    const X86Subtarget *Subtarget,
5570                                    SelectionDAG &DAG) {
5571   EVT VT = BV->getValueType(0);
5572   unsigned NumElts = VT.getVectorNumElements();
5573   unsigned NumUndefsLO = 0;
5574   unsigned NumUndefsHI = 0;
5575   unsigned Half = NumElts/2;
5576
5577   // Count the number of UNDEF operands in the build_vector in input.
5578   for (unsigned i = 0, e = Half; i != e; ++i)
5579     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5580       NumUndefsLO++;
5581
5582   for (unsigned i = Half, e = NumElts; i != e; ++i)
5583     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5584       NumUndefsHI++;
5585
5586   // Early exit if this is either a build_vector of all UNDEFs or all the
5587   // operands but one are UNDEF.
5588   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5589     return SDValue();
5590
5591   SDLoc DL(BV);
5592   SDValue InVec0, InVec1;
5593   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5594     // Try to match an SSE3 float HADD/HSUB.
5595     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5596       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5597
5598     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5599       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5600   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5601     // Try to match an SSSE3 integer HADD/HSUB.
5602     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5603       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5604
5605     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5606       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5607   }
5608
5609   if (!Subtarget->hasAVX())
5610     return SDValue();
5611
5612   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5613     // Try to match an AVX horizontal add/sub of packed single/double
5614     // precision floating point values from 256-bit vectors.
5615     SDValue InVec2, InVec3;
5616     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5617         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5618         ((InVec0.getOpcode() == ISD::UNDEF ||
5619           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5620         ((InVec1.getOpcode() == ISD::UNDEF ||
5621           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5622       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5623
5624     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5625         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5626         ((InVec0.getOpcode() == ISD::UNDEF ||
5627           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5628         ((InVec1.getOpcode() == ISD::UNDEF ||
5629           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5630       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5631   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5632     // Try to match an AVX2 horizontal add/sub of signed integers.
5633     SDValue InVec2, InVec3;
5634     unsigned X86Opcode;
5635     bool CanFold = true;
5636
5637     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5638         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5639         ((InVec0.getOpcode() == ISD::UNDEF ||
5640           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5641         ((InVec1.getOpcode() == ISD::UNDEF ||
5642           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5643       X86Opcode = X86ISD::HADD;
5644     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5645         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5646         ((InVec0.getOpcode() == ISD::UNDEF ||
5647           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5648         ((InVec1.getOpcode() == ISD::UNDEF ||
5649           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5650       X86Opcode = X86ISD::HSUB;
5651     else
5652       CanFold = false;
5653
5654     if (CanFold) {
5655       // Fold this build_vector into a single horizontal add/sub.
5656       // Do this only if the target has AVX2.
5657       if (Subtarget->hasAVX2())
5658         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5659
5660       // Do not try to expand this build_vector into a pair of horizontal
5661       // add/sub if we can emit a pair of scalar add/sub.
5662       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5663         return SDValue();
5664
5665       // Convert this build_vector into a pair of horizontal binop followed by
5666       // a concat vector.
5667       bool isUndefLO = NumUndefsLO == Half;
5668       bool isUndefHI = NumUndefsHI == Half;
5669       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5670                                    isUndefLO, isUndefHI);
5671     }
5672   }
5673
5674   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5675        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5676     unsigned X86Opcode;
5677     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5678       X86Opcode = X86ISD::HADD;
5679     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5680       X86Opcode = X86ISD::HSUB;
5681     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5682       X86Opcode = X86ISD::FHADD;
5683     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5684       X86Opcode = X86ISD::FHSUB;
5685     else
5686       return SDValue();
5687
5688     // Don't try to expand this build_vector into a pair of horizontal add/sub
5689     // if we can simply emit a pair of scalar add/sub.
5690     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5691       return SDValue();
5692
5693     // Convert this build_vector into two horizontal add/sub followed by
5694     // a concat vector.
5695     bool isUndefLO = NumUndefsLO == Half;
5696     bool isUndefHI = NumUndefsHI == Half;
5697     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5698                                  isUndefLO, isUndefHI);
5699   }
5700
5701   return SDValue();
5702 }
5703
5704 SDValue
5705 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5706   SDLoc dl(Op);
5707
5708   MVT VT = Op.getSimpleValueType();
5709   MVT ExtVT = VT.getVectorElementType();
5710   unsigned NumElems = Op.getNumOperands();
5711
5712   // Generate vectors for predicate vectors.
5713   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5714     return LowerBUILD_VECTORvXi1(Op, DAG);
5715
5716   // Vectors containing all zeros can be matched by pxor and xorps later
5717   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5718     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5719     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5720     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5721       return Op;
5722
5723     return getZeroVector(VT, Subtarget, DAG, dl);
5724   }
5725
5726   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5727   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5728   // vpcmpeqd on 256-bit vectors.
5729   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5730     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5731       return Op;
5732
5733     if (!VT.is512BitVector())
5734       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5735   }
5736
5737   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5738   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5739     return AddSub;
5740   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5741     return HorizontalOp;
5742   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5743     return Broadcast;
5744
5745   unsigned EVTBits = ExtVT.getSizeInBits();
5746
5747   unsigned NumZero  = 0;
5748   unsigned NumNonZero = 0;
5749   unsigned NonZeros = 0;
5750   bool IsAllConstants = true;
5751   SmallSet<SDValue, 8> Values;
5752   for (unsigned i = 0; i < NumElems; ++i) {
5753     SDValue Elt = Op.getOperand(i);
5754     if (Elt.getOpcode() == ISD::UNDEF)
5755       continue;
5756     Values.insert(Elt);
5757     if (Elt.getOpcode() != ISD::Constant &&
5758         Elt.getOpcode() != ISD::ConstantFP)
5759       IsAllConstants = false;
5760     if (X86::isZeroNode(Elt))
5761       NumZero++;
5762     else {
5763       NonZeros |= (1 << i);
5764       NumNonZero++;
5765     }
5766   }
5767
5768   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5769   if (NumNonZero == 0)
5770     return DAG.getUNDEF(VT);
5771
5772   // Special case for single non-zero, non-undef, element.
5773   if (NumNonZero == 1) {
5774     unsigned Idx = countTrailingZeros(NonZeros);
5775     SDValue Item = Op.getOperand(Idx);
5776
5777     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5778     // the value are obviously zero, truncate the value to i32 and do the
5779     // insertion that way.  Only do this if the value is non-constant or if the
5780     // value is a constant being inserted into element 0.  It is cheaper to do
5781     // a constant pool load than it is to do a movd + shuffle.
5782     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5783         (!IsAllConstants || Idx == 0)) {
5784       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5785         // Handle SSE only.
5786         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5787         EVT VecVT = MVT::v4i32;
5788
5789         // Truncate the value (which may itself be a constant) to i32, and
5790         // convert it to a vector with movd (S2V+shuffle to zero extend).
5791         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5792         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5793         return DAG.getNode(
5794             ISD::BITCAST, dl, VT,
5795             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5796       }
5797     }
5798
5799     // If we have a constant or non-constant insertion into the low element of
5800     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5801     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5802     // depending on what the source datatype is.
5803     if (Idx == 0) {
5804       if (NumZero == 0)
5805         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5806
5807       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5808           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5809         if (VT.is512BitVector()) {
5810           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5811           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5812                              Item, DAG.getIntPtrConstant(0, dl));
5813         }
5814         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5815                "Expected an SSE value type!");
5816         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5817         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5818         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5819       }
5820
5821       // We can't directly insert an i8 or i16 into a vector, so zero extend
5822       // it to i32 first.
5823       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5824         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5825         if (VT.is256BitVector()) {
5826           if (Subtarget->hasAVX()) {
5827             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5828             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5829           } else {
5830             // Without AVX, we need to extend to a 128-bit vector and then
5831             // insert into the 256-bit vector.
5832             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5833             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5834             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5835           }
5836         } else {
5837           assert(VT.is128BitVector() && "Expected an SSE value type!");
5838           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5839           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5840         }
5841         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5842       }
5843     }
5844
5845     // Is it a vector logical left shift?
5846     if (NumElems == 2 && Idx == 1 &&
5847         X86::isZeroNode(Op.getOperand(0)) &&
5848         !X86::isZeroNode(Op.getOperand(1))) {
5849       unsigned NumBits = VT.getSizeInBits();
5850       return getVShift(true, VT,
5851                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5852                                    VT, Op.getOperand(1)),
5853                        NumBits/2, DAG, *this, dl);
5854     }
5855
5856     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5857       return SDValue();
5858
5859     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5860     // is a non-constant being inserted into an element other than the low one,
5861     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5862     // movd/movss) to move this into the low element, then shuffle it into
5863     // place.
5864     if (EVTBits == 32) {
5865       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5866       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5867     }
5868   }
5869
5870   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5871   if (Values.size() == 1) {
5872     if (EVTBits == 32) {
5873       // Instead of a shuffle like this:
5874       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5875       // Check if it's possible to issue this instead.
5876       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5877       unsigned Idx = countTrailingZeros(NonZeros);
5878       SDValue Item = Op.getOperand(Idx);
5879       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5880         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5881     }
5882     return SDValue();
5883   }
5884
5885   // A vector full of immediates; various special cases are already
5886   // handled, so this is best done with a single constant-pool load.
5887   if (IsAllConstants)
5888     return SDValue();
5889
5890   // For AVX-length vectors, see if we can use a vector load to get all of the
5891   // elements, otherwise build the individual 128-bit pieces and use
5892   // shuffles to put them in place.
5893   if (VT.is256BitVector() || VT.is512BitVector()) {
5894     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5895
5896     // Check for a build vector of consecutive loads.
5897     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5898       return LD;
5899
5900     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5901
5902     // Build both the lower and upper subvector.
5903     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5904                                 makeArrayRef(&V[0], NumElems/2));
5905     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5906                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5907
5908     // Recreate the wider vector with the lower and upper part.
5909     if (VT.is256BitVector())
5910       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5911     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5912   }
5913
5914   // Let legalizer expand 2-wide build_vectors.
5915   if (EVTBits == 64) {
5916     if (NumNonZero == 1) {
5917       // One half is zero or undef.
5918       unsigned Idx = countTrailingZeros(NonZeros);
5919       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5920                                  Op.getOperand(Idx));
5921       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5922     }
5923     return SDValue();
5924   }
5925
5926   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5927   if (EVTBits == 8 && NumElems == 16)
5928     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5929                                         Subtarget, *this))
5930       return V;
5931
5932   if (EVTBits == 16 && NumElems == 8)
5933     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5934                                       Subtarget, *this))
5935       return V;
5936
5937   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5938   if (EVTBits == 32 && NumElems == 4)
5939     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5940       return V;
5941
5942   // If element VT is == 32 bits, turn it into a number of shuffles.
5943   SmallVector<SDValue, 8> V(NumElems);
5944   if (NumElems == 4 && NumZero > 0) {
5945     for (unsigned i = 0; i < 4; ++i) {
5946       bool isZero = !(NonZeros & (1 << i));
5947       if (isZero)
5948         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5949       else
5950         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5951     }
5952
5953     for (unsigned i = 0; i < 2; ++i) {
5954       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5955         default: break;
5956         case 0:
5957           V[i] = V[i*2];  // Must be a zero vector.
5958           break;
5959         case 1:
5960           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5961           break;
5962         case 2:
5963           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5964           break;
5965         case 3:
5966           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5967           break;
5968       }
5969     }
5970
5971     bool Reverse1 = (NonZeros & 0x3) == 2;
5972     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5973     int MaskVec[] = {
5974       Reverse1 ? 1 : 0,
5975       Reverse1 ? 0 : 1,
5976       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5977       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5978     };
5979     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5980   }
5981
5982   if (Values.size() > 1 && VT.is128BitVector()) {
5983     // Check for a build vector of consecutive loads.
5984     for (unsigned i = 0; i < NumElems; ++i)
5985       V[i] = Op.getOperand(i);
5986
5987     // Check for elements which are consecutive loads.
5988     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5989       return LD;
5990
5991     // Check for a build vector from mostly shuffle plus few inserting.
5992     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5993       return Sh;
5994
5995     // For SSE 4.1, use insertps to put the high elements into the low element.
5996     if (Subtarget->hasSSE41()) {
5997       SDValue Result;
5998       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5999         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6000       else
6001         Result = DAG.getUNDEF(VT);
6002
6003       for (unsigned i = 1; i < NumElems; ++i) {
6004         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6005         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6006                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6007       }
6008       return Result;
6009     }
6010
6011     // Otherwise, expand into a number of unpckl*, start by extending each of
6012     // our (non-undef) elements to the full vector width with the element in the
6013     // bottom slot of the vector (which generates no code for SSE).
6014     for (unsigned i = 0; i < NumElems; ++i) {
6015       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6016         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6017       else
6018         V[i] = DAG.getUNDEF(VT);
6019     }
6020
6021     // Next, we iteratively mix elements, e.g. for v4f32:
6022     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6023     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6024     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6025     unsigned EltStride = NumElems >> 1;
6026     while (EltStride != 0) {
6027       for (unsigned i = 0; i < EltStride; ++i) {
6028         // If V[i+EltStride] is undef and this is the first round of mixing,
6029         // then it is safe to just drop this shuffle: V[i] is already in the
6030         // right place, the one element (since it's the first round) being
6031         // inserted as undef can be dropped.  This isn't safe for successive
6032         // rounds because they will permute elements within both vectors.
6033         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6034             EltStride == NumElems/2)
6035           continue;
6036
6037         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6038       }
6039       EltStride >>= 1;
6040     }
6041     return V[0];
6042   }
6043   return SDValue();
6044 }
6045
6046 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6047 // to create 256-bit vectors from two other 128-bit ones.
6048 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6049   SDLoc dl(Op);
6050   MVT ResVT = Op.getSimpleValueType();
6051
6052   assert((ResVT.is256BitVector() ||
6053           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6054
6055   SDValue V1 = Op.getOperand(0);
6056   SDValue V2 = Op.getOperand(1);
6057   unsigned NumElems = ResVT.getVectorNumElements();
6058   if (ResVT.is256BitVector())
6059     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6060
6061   if (Op.getNumOperands() == 4) {
6062     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6063                                 ResVT.getVectorNumElements()/2);
6064     SDValue V3 = Op.getOperand(2);
6065     SDValue V4 = Op.getOperand(3);
6066     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6067       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6068   }
6069   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6070 }
6071
6072 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6073                                        const X86Subtarget *Subtarget,
6074                                        SelectionDAG & DAG) {
6075   SDLoc dl(Op);
6076   MVT ResVT = Op.getSimpleValueType();
6077   unsigned NumOfOperands = Op.getNumOperands();
6078
6079   assert(isPowerOf2_32(NumOfOperands) &&
6080          "Unexpected number of operands in CONCAT_VECTORS");
6081
6082   if (NumOfOperands > 2) {
6083     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6084                                   ResVT.getVectorNumElements()/2);
6085     SmallVector<SDValue, 2> Ops;
6086     for (unsigned i = 0; i < NumOfOperands/2; i++)
6087       Ops.push_back(Op.getOperand(i));
6088     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6089     Ops.clear();
6090     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6091       Ops.push_back(Op.getOperand(i));
6092     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6093     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6094   }
6095
6096   SDValue V1 = Op.getOperand(0);
6097   SDValue V2 = Op.getOperand(1);
6098   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6099   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6100
6101   if (IsZeroV1 && IsZeroV2)
6102     return getZeroVector(ResVT, Subtarget, DAG, dl);
6103
6104   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6105   SDValue Undef = DAG.getUNDEF(ResVT);
6106   unsigned NumElems = ResVT.getVectorNumElements();
6107   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6108
6109   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6110   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6111   if (IsZeroV1)
6112     return V2;
6113
6114   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6115   // Zero the upper bits of V1
6116   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6117   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6118   if (IsZeroV2)
6119     return V1;
6120   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6121 }
6122
6123 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6124                                    const X86Subtarget *Subtarget,
6125                                    SelectionDAG &DAG) {
6126   MVT VT = Op.getSimpleValueType();
6127   if (VT.getVectorElementType() == MVT::i1)
6128     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6129
6130   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6131          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6132           Op.getNumOperands() == 4)));
6133
6134   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6135   // from two other 128-bit ones.
6136
6137   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6138   return LowerAVXCONCAT_VECTORS(Op, DAG);
6139 }
6140
6141
6142 //===----------------------------------------------------------------------===//
6143 // Vector shuffle lowering
6144 //
6145 // This is an experimental code path for lowering vector shuffles on x86. It is
6146 // designed to handle arbitrary vector shuffles and blends, gracefully
6147 // degrading performance as necessary. It works hard to recognize idiomatic
6148 // shuffles and lower them to optimal instruction patterns without leaving
6149 // a framework that allows reasonably efficient handling of all vector shuffle
6150 // patterns.
6151 //===----------------------------------------------------------------------===//
6152
6153 /// \brief Tiny helper function to identify a no-op mask.
6154 ///
6155 /// This is a somewhat boring predicate function. It checks whether the mask
6156 /// array input, which is assumed to be a single-input shuffle mask of the kind
6157 /// used by the X86 shuffle instructions (not a fully general
6158 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6159 /// in-place shuffle are 'no-op's.
6160 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6161   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6162     if (Mask[i] != -1 && Mask[i] != i)
6163       return false;
6164   return true;
6165 }
6166
6167 /// \brief Helper function to classify a mask as a single-input mask.
6168 ///
6169 /// This isn't a generic single-input test because in the vector shuffle
6170 /// lowering we canonicalize single inputs to be the first input operand. This
6171 /// means we can more quickly test for a single input by only checking whether
6172 /// an input from the second operand exists. We also assume that the size of
6173 /// mask corresponds to the size of the input vectors which isn't true in the
6174 /// fully general case.
6175 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6176   for (int M : Mask)
6177     if (M >= (int)Mask.size())
6178       return false;
6179   return true;
6180 }
6181
6182 /// \brief Test whether there are elements crossing 128-bit lanes in this
6183 /// shuffle mask.
6184 ///
6185 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6186 /// and we routinely test for these.
6187 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6188   int LaneSize = 128 / VT.getScalarSizeInBits();
6189   int Size = Mask.size();
6190   for (int i = 0; i < Size; ++i)
6191     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6192       return true;
6193   return false;
6194 }
6195
6196 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6197 ///
6198 /// This checks a shuffle mask to see if it is performing the same
6199 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6200 /// that it is also not lane-crossing. It may however involve a blend from the
6201 /// same lane of a second vector.
6202 ///
6203 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6204 /// non-trivial to compute in the face of undef lanes. The representation is
6205 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6206 /// entries from both V1 and V2 inputs to the wider mask.
6207 static bool
6208 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6209                                 SmallVectorImpl<int> &RepeatedMask) {
6210   int LaneSize = 128 / VT.getScalarSizeInBits();
6211   RepeatedMask.resize(LaneSize, -1);
6212   int Size = Mask.size();
6213   for (int i = 0; i < Size; ++i) {
6214     if (Mask[i] < 0)
6215       continue;
6216     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6217       // This entry crosses lanes, so there is no way to model this shuffle.
6218       return false;
6219
6220     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6221     if (RepeatedMask[i % LaneSize] == -1)
6222       // This is the first non-undef entry in this slot of a 128-bit lane.
6223       RepeatedMask[i % LaneSize] =
6224           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6225     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6226       // Found a mismatch with the repeated mask.
6227       return false;
6228   }
6229   return true;
6230 }
6231
6232 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6233 /// arguments.
6234 ///
6235 /// This is a fast way to test a shuffle mask against a fixed pattern:
6236 ///
6237 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6238 ///
6239 /// It returns true if the mask is exactly as wide as the argument list, and
6240 /// each element of the mask is either -1 (signifying undef) or the value given
6241 /// in the argument.
6242 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6243                                 ArrayRef<int> ExpectedMask) {
6244   if (Mask.size() != ExpectedMask.size())
6245     return false;
6246
6247   int Size = Mask.size();
6248
6249   // If the values are build vectors, we can look through them to find
6250   // equivalent inputs that make the shuffles equivalent.
6251   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6252   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6253
6254   for (int i = 0; i < Size; ++i)
6255     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6256       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6257       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6258       if (!MaskBV || !ExpectedBV ||
6259           MaskBV->getOperand(Mask[i] % Size) !=
6260               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6261         return false;
6262     }
6263
6264   return true;
6265 }
6266
6267 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6268 ///
6269 /// This helper function produces an 8-bit shuffle immediate corresponding to
6270 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6271 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6272 /// example.
6273 ///
6274 /// NB: We rely heavily on "undef" masks preserving the input lane.
6275 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6276                                           SelectionDAG &DAG) {
6277   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6278   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6279   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6280   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6281   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6282
6283   unsigned Imm = 0;
6284   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6285   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6286   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6287   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6288   return DAG.getConstant(Imm, DL, MVT::i8);
6289 }
6290
6291 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6292 ///
6293 /// This is used as a fallback approach when first class blend instructions are
6294 /// unavailable. Currently it is only suitable for integer vectors, but could
6295 /// be generalized for floating point vectors if desirable.
6296 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6297                                             SDValue V2, ArrayRef<int> Mask,
6298                                             SelectionDAG &DAG) {
6299   assert(VT.isInteger() && "Only supports integer vector types!");
6300   MVT EltVT = VT.getScalarType();
6301   int NumEltBits = EltVT.getSizeInBits();
6302   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6303   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6304                                     EltVT);
6305   SmallVector<SDValue, 16> MaskOps;
6306   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6307     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6308       return SDValue(); // Shuffled input!
6309     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6310   }
6311
6312   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6313   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6314   // We have to cast V2 around.
6315   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6316   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6317                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6318                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6319                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6320   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6321 }
6322
6323 /// \brief Try to emit a blend instruction for a shuffle.
6324 ///
6325 /// This doesn't do any checks for the availability of instructions for blending
6326 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6327 /// be matched in the backend with the type given. What it does check for is
6328 /// that the shuffle mask is in fact a blend.
6329 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6330                                          SDValue V2, ArrayRef<int> Mask,
6331                                          const X86Subtarget *Subtarget,
6332                                          SelectionDAG &DAG) {
6333   unsigned BlendMask = 0;
6334   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6335     if (Mask[i] >= Size) {
6336       if (Mask[i] != i + Size)
6337         return SDValue(); // Shuffled V2 input!
6338       BlendMask |= 1u << i;
6339       continue;
6340     }
6341     if (Mask[i] >= 0 && Mask[i] != i)
6342       return SDValue(); // Shuffled V1 input!
6343   }
6344   switch (VT.SimpleTy) {
6345   case MVT::v2f64:
6346   case MVT::v4f32:
6347   case MVT::v4f64:
6348   case MVT::v8f32:
6349     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6350                        DAG.getConstant(BlendMask, DL, MVT::i8));
6351
6352   case MVT::v4i64:
6353   case MVT::v8i32:
6354     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6355     // FALLTHROUGH
6356   case MVT::v2i64:
6357   case MVT::v4i32:
6358     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6359     // that instruction.
6360     if (Subtarget->hasAVX2()) {
6361       // Scale the blend by the number of 32-bit dwords per element.
6362       int Scale =  VT.getScalarSizeInBits() / 32;
6363       BlendMask = 0;
6364       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6365         if (Mask[i] >= Size)
6366           for (int j = 0; j < Scale; ++j)
6367             BlendMask |= 1u << (i * Scale + j);
6368
6369       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6370       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6371       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6372       return DAG.getNode(ISD::BITCAST, DL, VT,
6373                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6374                                      DAG.getConstant(BlendMask, DL, MVT::i8)));
6375     }
6376     // FALLTHROUGH
6377   case MVT::v8i16: {
6378     // For integer shuffles we need to expand the mask and cast the inputs to
6379     // v8i16s prior to blending.
6380     int Scale = 8 / VT.getVectorNumElements();
6381     BlendMask = 0;
6382     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6383       if (Mask[i] >= Size)
6384         for (int j = 0; j < Scale; ++j)
6385           BlendMask |= 1u << (i * Scale + j);
6386
6387     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6388     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6389     return DAG.getNode(ISD::BITCAST, DL, VT,
6390                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6391                                    DAG.getConstant(BlendMask, DL, MVT::i8)));
6392   }
6393
6394   case MVT::v16i16: {
6395     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6396     SmallVector<int, 8> RepeatedMask;
6397     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6398       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6399       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6400       BlendMask = 0;
6401       for (int i = 0; i < 8; ++i)
6402         if (RepeatedMask[i] >= 16)
6403           BlendMask |= 1u << i;
6404       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6405                          DAG.getConstant(BlendMask, DL, MVT::i8));
6406     }
6407   }
6408     // FALLTHROUGH
6409   case MVT::v16i8:
6410   case MVT::v32i8: {
6411     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6412            "256-bit byte-blends require AVX2 support!");
6413
6414     // Scale the blend by the number of bytes per element.
6415     int Scale = VT.getScalarSizeInBits() / 8;
6416
6417     // This form of blend is always done on bytes. Compute the byte vector
6418     // type.
6419     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6420
6421     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6422     // mix of LLVM's code generator and the x86 backend. We tell the code
6423     // generator that boolean values in the elements of an x86 vector register
6424     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6425     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6426     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6427     // of the element (the remaining are ignored) and 0 in that high bit would
6428     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6429     // the LLVM model for boolean values in vector elements gets the relevant
6430     // bit set, it is set backwards and over constrained relative to x86's
6431     // actual model.
6432     SmallVector<SDValue, 32> VSELECTMask;
6433     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6434       for (int j = 0; j < Scale; ++j)
6435         VSELECTMask.push_back(
6436             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6437                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6438                                           MVT::i8));
6439
6440     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6441     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6442     return DAG.getNode(
6443         ISD::BITCAST, DL, VT,
6444         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6445                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6446                     V1, V2));
6447   }
6448
6449   default:
6450     llvm_unreachable("Not a supported integer vector type!");
6451   }
6452 }
6453
6454 /// \brief Try to lower as a blend of elements from two inputs followed by
6455 /// a single-input permutation.
6456 ///
6457 /// This matches the pattern where we can blend elements from two inputs and
6458 /// then reduce the shuffle to a single-input permutation.
6459 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6460                                                    SDValue V2,
6461                                                    ArrayRef<int> Mask,
6462                                                    SelectionDAG &DAG) {
6463   // We build up the blend mask while checking whether a blend is a viable way
6464   // to reduce the shuffle.
6465   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6466   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6467
6468   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6469     if (Mask[i] < 0)
6470       continue;
6471
6472     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6473
6474     if (BlendMask[Mask[i] % Size] == -1)
6475       BlendMask[Mask[i] % Size] = Mask[i];
6476     else if (BlendMask[Mask[i] % Size] != Mask[i])
6477       return SDValue(); // Can't blend in the needed input!
6478
6479     PermuteMask[i] = Mask[i] % Size;
6480   }
6481
6482   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6483   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6484 }
6485
6486 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6487 /// blends and permutes.
6488 ///
6489 /// This matches the extremely common pattern for handling combined
6490 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6491 /// operations. It will try to pick the best arrangement of shuffles and
6492 /// blends.
6493 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6494                                                           SDValue V1,
6495                                                           SDValue V2,
6496                                                           ArrayRef<int> Mask,
6497                                                           SelectionDAG &DAG) {
6498   // Shuffle the input elements into the desired positions in V1 and V2 and
6499   // blend them together.
6500   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6501   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6502   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6503   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6504     if (Mask[i] >= 0 && Mask[i] < Size) {
6505       V1Mask[i] = Mask[i];
6506       BlendMask[i] = i;
6507     } else if (Mask[i] >= Size) {
6508       V2Mask[i] = Mask[i] - Size;
6509       BlendMask[i] = i + Size;
6510     }
6511
6512   // Try to lower with the simpler initial blend strategy unless one of the
6513   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6514   // shuffle may be able to fold with a load or other benefit. However, when
6515   // we'll have to do 2x as many shuffles in order to achieve this, blending
6516   // first is a better strategy.
6517   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6518     if (SDValue BlendPerm =
6519             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6520       return BlendPerm;
6521
6522   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6523   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6524   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6525 }
6526
6527 /// \brief Try to lower a vector shuffle as a byte rotation.
6528 ///
6529 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6530 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6531 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6532 /// try to generically lower a vector shuffle through such an pattern. It
6533 /// does not check for the profitability of lowering either as PALIGNR or
6534 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6535 /// This matches shuffle vectors that look like:
6536 ///
6537 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6538 ///
6539 /// Essentially it concatenates V1 and V2, shifts right by some number of
6540 /// elements, and takes the low elements as the result. Note that while this is
6541 /// specified as a *right shift* because x86 is little-endian, it is a *left
6542 /// rotate* of the vector lanes.
6543 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6544                                               SDValue V2,
6545                                               ArrayRef<int> Mask,
6546                                               const X86Subtarget *Subtarget,
6547                                               SelectionDAG &DAG) {
6548   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6549
6550   int NumElts = Mask.size();
6551   int NumLanes = VT.getSizeInBits() / 128;
6552   int NumLaneElts = NumElts / NumLanes;
6553
6554   // We need to detect various ways of spelling a rotation:
6555   //   [11, 12, 13, 14, 15,  0,  1,  2]
6556   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6557   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6558   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6559   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6560   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6561   int Rotation = 0;
6562   SDValue Lo, Hi;
6563   for (int l = 0; l < NumElts; l += NumLaneElts) {
6564     for (int i = 0; i < NumLaneElts; ++i) {
6565       if (Mask[l + i] == -1)
6566         continue;
6567       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6568
6569       // Get the mod-Size index and lane correct it.
6570       int LaneIdx = (Mask[l + i] % NumElts) - l;
6571       // Make sure it was in this lane.
6572       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6573         return SDValue();
6574
6575       // Determine where a rotated vector would have started.
6576       int StartIdx = i - LaneIdx;
6577       if (StartIdx == 0)
6578         // The identity rotation isn't interesting, stop.
6579         return SDValue();
6580
6581       // If we found the tail of a vector the rotation must be the missing
6582       // front. If we found the head of a vector, it must be how much of the
6583       // head.
6584       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6585
6586       if (Rotation == 0)
6587         Rotation = CandidateRotation;
6588       else if (Rotation != CandidateRotation)
6589         // The rotations don't match, so we can't match this mask.
6590         return SDValue();
6591
6592       // Compute which value this mask is pointing at.
6593       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6594
6595       // Compute which of the two target values this index should be assigned
6596       // to. This reflects whether the high elements are remaining or the low
6597       // elements are remaining.
6598       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6599
6600       // Either set up this value if we've not encountered it before, or check
6601       // that it remains consistent.
6602       if (!TargetV)
6603         TargetV = MaskV;
6604       else if (TargetV != MaskV)
6605         // This may be a rotation, but it pulls from the inputs in some
6606         // unsupported interleaving.
6607         return SDValue();
6608     }
6609   }
6610
6611   // Check that we successfully analyzed the mask, and normalize the results.
6612   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6613   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6614   if (!Lo)
6615     Lo = Hi;
6616   else if (!Hi)
6617     Hi = Lo;
6618
6619   // The actual rotate instruction rotates bytes, so we need to scale the
6620   // rotation based on how many bytes are in the vector lane.
6621   int Scale = 16 / NumLaneElts;
6622
6623   // SSSE3 targets can use the palignr instruction.
6624   if (Subtarget->hasSSSE3()) {
6625     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6626     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6627     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6628     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6629
6630     return DAG.getNode(ISD::BITCAST, DL, VT,
6631                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6632                                    DAG.getConstant(Rotation * Scale, DL,
6633                                                    MVT::i8)));
6634   }
6635
6636   assert(VT.getSizeInBits() == 128 &&
6637          "Rotate-based lowering only supports 128-bit lowering!");
6638   assert(Mask.size() <= 16 &&
6639          "Can shuffle at most 16 bytes in a 128-bit vector!");
6640
6641   // Default SSE2 implementation
6642   int LoByteShift = 16 - Rotation * Scale;
6643   int HiByteShift = Rotation * Scale;
6644
6645   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6646   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6647   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6648
6649   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6650                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6651   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6652                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6653   return DAG.getNode(ISD::BITCAST, DL, VT,
6654                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6655 }
6656
6657 /// \brief Compute whether each element of a shuffle is zeroable.
6658 ///
6659 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6660 /// Either it is an undef element in the shuffle mask, the element of the input
6661 /// referenced is undef, or the element of the input referenced is known to be
6662 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6663 /// as many lanes with this technique as possible to simplify the remaining
6664 /// shuffle.
6665 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6666                                                      SDValue V1, SDValue V2) {
6667   SmallBitVector Zeroable(Mask.size(), false);
6668
6669   while (V1.getOpcode() == ISD::BITCAST)
6670     V1 = V1->getOperand(0);
6671   while (V2.getOpcode() == ISD::BITCAST)
6672     V2 = V2->getOperand(0);
6673
6674   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6675   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6676
6677   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6678     int M = Mask[i];
6679     // Handle the easy cases.
6680     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6681       Zeroable[i] = true;
6682       continue;
6683     }
6684
6685     // If this is an index into a build_vector node (which has the same number
6686     // of elements), dig out the input value and use it.
6687     SDValue V = M < Size ? V1 : V2;
6688     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6689       continue;
6690
6691     SDValue Input = V.getOperand(M % Size);
6692     // The UNDEF opcode check really should be dead code here, but not quite
6693     // worth asserting on (it isn't invalid, just unexpected).
6694     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6695       Zeroable[i] = true;
6696   }
6697
6698   return Zeroable;
6699 }
6700
6701 /// \brief Try to emit a bitmask instruction for a shuffle.
6702 ///
6703 /// This handles cases where we can model a blend exactly as a bitmask due to
6704 /// one of the inputs being zeroable.
6705 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6706                                            SDValue V2, ArrayRef<int> Mask,
6707                                            SelectionDAG &DAG) {
6708   MVT EltVT = VT.getScalarType();
6709   int NumEltBits = EltVT.getSizeInBits();
6710   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6711   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6712   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6713                                     IntEltVT);
6714   if (EltVT.isFloatingPoint()) {
6715     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6716     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6717   }
6718   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6719   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6720   SDValue V;
6721   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6722     if (Zeroable[i])
6723       continue;
6724     if (Mask[i] % Size != i)
6725       return SDValue(); // Not a blend.
6726     if (!V)
6727       V = Mask[i] < Size ? V1 : V2;
6728     else if (V != (Mask[i] < Size ? V1 : V2))
6729       return SDValue(); // Can only let one input through the mask.
6730
6731     VMaskOps[i] = AllOnes;
6732   }
6733   if (!V)
6734     return SDValue(); // No non-zeroable elements!
6735
6736   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6737   V = DAG.getNode(VT.isFloatingPoint()
6738                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6739                   DL, VT, V, VMask);
6740   return V;
6741 }
6742
6743 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6744 ///
6745 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6746 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6747 /// matches elements from one of the input vectors shuffled to the left or
6748 /// right with zeroable elements 'shifted in'. It handles both the strictly
6749 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6750 /// quad word lane.
6751 ///
6752 /// PSHL : (little-endian) left bit shift.
6753 /// [ zz, 0, zz,  2 ]
6754 /// [ -1, 4, zz, -1 ]
6755 /// PSRL : (little-endian) right bit shift.
6756 /// [  1, zz,  3, zz]
6757 /// [ -1, -1,  7, zz]
6758 /// PSLLDQ : (little-endian) left byte shift
6759 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6760 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6761 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6762 /// PSRLDQ : (little-endian) right byte shift
6763 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6764 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6765 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6766 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6767                                          SDValue V2, ArrayRef<int> Mask,
6768                                          SelectionDAG &DAG) {
6769   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6770
6771   int Size = Mask.size();
6772   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6773
6774   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6775     for (int i = 0; i < Size; i += Scale)
6776       for (int j = 0; j < Shift; ++j)
6777         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6778           return false;
6779
6780     return true;
6781   };
6782
6783   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6784     for (int i = 0; i != Size; i += Scale) {
6785       unsigned Pos = Left ? i + Shift : i;
6786       unsigned Low = Left ? i : i + Shift;
6787       unsigned Len = Scale - Shift;
6788       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6789                                       Low + (V == V1 ? 0 : Size)))
6790         return SDValue();
6791     }
6792
6793     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6794     bool ByteShift = ShiftEltBits > 64;
6795     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6796                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6797     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6798
6799     // Normalize the scale for byte shifts to still produce an i64 element
6800     // type.
6801     Scale = ByteShift ? Scale / 2 : Scale;
6802
6803     // We need to round trip through the appropriate type for the shift.
6804     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6805     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6806     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6807            "Illegal integer vector type");
6808     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6809
6810     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6811                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6812     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6813   };
6814
6815   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6816   // keep doubling the size of the integer elements up to that. We can
6817   // then shift the elements of the integer vector by whole multiples of
6818   // their width within the elements of the larger integer vector. Test each
6819   // multiple to see if we can find a match with the moved element indices
6820   // and that the shifted in elements are all zeroable.
6821   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6822     for (int Shift = 1; Shift != Scale; ++Shift)
6823       for (bool Left : {true, false})
6824         if (CheckZeros(Shift, Scale, Left))
6825           for (SDValue V : {V1, V2})
6826             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6827               return Match;
6828
6829   // no match
6830   return SDValue();
6831 }
6832
6833 /// \brief Lower a vector shuffle as a zero or any extension.
6834 ///
6835 /// Given a specific number of elements, element bit width, and extension
6836 /// stride, produce either a zero or any extension based on the available
6837 /// features of the subtarget.
6838 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6839     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6840     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6841   assert(Scale > 1 && "Need a scale to extend.");
6842   int NumElements = VT.getVectorNumElements();
6843   int EltBits = VT.getScalarSizeInBits();
6844   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6845          "Only 8, 16, and 32 bit elements can be extended.");
6846   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6847
6848   // Found a valid zext mask! Try various lowering strategies based on the
6849   // input type and available ISA extensions.
6850   if (Subtarget->hasSSE41()) {
6851     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6852                                  NumElements / Scale);
6853     return DAG.getNode(ISD::BITCAST, DL, VT,
6854                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6855   }
6856
6857   // For any extends we can cheat for larger element sizes and use shuffle
6858   // instructions that can fold with a load and/or copy.
6859   if (AnyExt && EltBits == 32) {
6860     int PSHUFDMask[4] = {0, -1, 1, -1};
6861     return DAG.getNode(
6862         ISD::BITCAST, DL, VT,
6863         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6864                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6865                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6866   }
6867   if (AnyExt && EltBits == 16 && Scale > 2) {
6868     int PSHUFDMask[4] = {0, -1, 0, -1};
6869     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6870                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6871                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6872     int PSHUFHWMask[4] = {1, -1, -1, -1};
6873     return DAG.getNode(
6874         ISD::BITCAST, DL, VT,
6875         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6876                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6877                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6878   }
6879
6880   // If this would require more than 2 unpack instructions to expand, use
6881   // pshufb when available. We can only use more than 2 unpack instructions
6882   // when zero extending i8 elements which also makes it easier to use pshufb.
6883   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6884     assert(NumElements == 16 && "Unexpected byte vector width!");
6885     SDValue PSHUFBMask[16];
6886     for (int i = 0; i < 16; ++i)
6887       PSHUFBMask[i] =
6888           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6889     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6890     return DAG.getNode(ISD::BITCAST, DL, VT,
6891                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6892                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6893                                                MVT::v16i8, PSHUFBMask)));
6894   }
6895
6896   // Otherwise emit a sequence of unpacks.
6897   do {
6898     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6899     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6900                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6901     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6902     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6903     Scale /= 2;
6904     EltBits *= 2;
6905     NumElements /= 2;
6906   } while (Scale > 1);
6907   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6908 }
6909
6910 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6911 ///
6912 /// This routine will try to do everything in its power to cleverly lower
6913 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6914 /// check for the profitability of this lowering,  it tries to aggressively
6915 /// match this pattern. It will use all of the micro-architectural details it
6916 /// can to emit an efficient lowering. It handles both blends with all-zero
6917 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6918 /// masking out later).
6919 ///
6920 /// The reason we have dedicated lowering for zext-style shuffles is that they
6921 /// are both incredibly common and often quite performance sensitive.
6922 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6923     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6924     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6925   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6926
6927   int Bits = VT.getSizeInBits();
6928   int NumElements = VT.getVectorNumElements();
6929   assert(VT.getScalarSizeInBits() <= 32 &&
6930          "Exceeds 32-bit integer zero extension limit");
6931   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6932
6933   // Define a helper function to check a particular ext-scale and lower to it if
6934   // valid.
6935   auto Lower = [&](int Scale) -> SDValue {
6936     SDValue InputV;
6937     bool AnyExt = true;
6938     for (int i = 0; i < NumElements; ++i) {
6939       if (Mask[i] == -1)
6940         continue; // Valid anywhere but doesn't tell us anything.
6941       if (i % Scale != 0) {
6942         // Each of the extended elements need to be zeroable.
6943         if (!Zeroable[i])
6944           return SDValue();
6945
6946         // We no longer are in the anyext case.
6947         AnyExt = false;
6948         continue;
6949       }
6950
6951       // Each of the base elements needs to be consecutive indices into the
6952       // same input vector.
6953       SDValue V = Mask[i] < NumElements ? V1 : V2;
6954       if (!InputV)
6955         InputV = V;
6956       else if (InputV != V)
6957         return SDValue(); // Flip-flopping inputs.
6958
6959       if (Mask[i] % NumElements != i / Scale)
6960         return SDValue(); // Non-consecutive strided elements.
6961     }
6962
6963     // If we fail to find an input, we have a zero-shuffle which should always
6964     // have already been handled.
6965     // FIXME: Maybe handle this here in case during blending we end up with one?
6966     if (!InputV)
6967       return SDValue();
6968
6969     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6970         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6971   };
6972
6973   // The widest scale possible for extending is to a 64-bit integer.
6974   assert(Bits % 64 == 0 &&
6975          "The number of bits in a vector must be divisible by 64 on x86!");
6976   int NumExtElements = Bits / 64;
6977
6978   // Each iteration, try extending the elements half as much, but into twice as
6979   // many elements.
6980   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6981     assert(NumElements % NumExtElements == 0 &&
6982            "The input vector size must be divisible by the extended size.");
6983     if (SDValue V = Lower(NumElements / NumExtElements))
6984       return V;
6985   }
6986
6987   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6988   if (Bits != 128)
6989     return SDValue();
6990
6991   // Returns one of the source operands if the shuffle can be reduced to a
6992   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6993   auto CanZExtLowHalf = [&]() {
6994     for (int i = NumElements / 2; i != NumElements; ++i)
6995       if (!Zeroable[i])
6996         return SDValue();
6997     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6998       return V1;
6999     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7000       return V2;
7001     return SDValue();
7002   };
7003
7004   if (SDValue V = CanZExtLowHalf()) {
7005     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
7006     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7007     return DAG.getNode(ISD::BITCAST, DL, VT, V);
7008   }
7009
7010   // No viable ext lowering found.
7011   return SDValue();
7012 }
7013
7014 /// \brief Try to get a scalar value for a specific element of a vector.
7015 ///
7016 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7017 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7018                                               SelectionDAG &DAG) {
7019   MVT VT = V.getSimpleValueType();
7020   MVT EltVT = VT.getVectorElementType();
7021   while (V.getOpcode() == ISD::BITCAST)
7022     V = V.getOperand(0);
7023   // If the bitcasts shift the element size, we can't extract an equivalent
7024   // element from it.
7025   MVT NewVT = V.getSimpleValueType();
7026   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7027     return SDValue();
7028
7029   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7030       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7031     // Ensure the scalar operand is the same size as the destination.
7032     // FIXME: Add support for scalar truncation where possible.
7033     SDValue S = V.getOperand(Idx);
7034     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7035       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7036   }
7037
7038   return SDValue();
7039 }
7040
7041 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7042 ///
7043 /// This is particularly important because the set of instructions varies
7044 /// significantly based on whether the operand is a load or not.
7045 static bool isShuffleFoldableLoad(SDValue V) {
7046   while (V.getOpcode() == ISD::BITCAST)
7047     V = V.getOperand(0);
7048
7049   return ISD::isNON_EXTLoad(V.getNode());
7050 }
7051
7052 /// \brief Try to lower insertion of a single element into a zero vector.
7053 ///
7054 /// This is a common pattern that we have especially efficient patterns to lower
7055 /// across all subtarget feature sets.
7056 static SDValue lowerVectorShuffleAsElementInsertion(
7057     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7058     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7059   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7060   MVT ExtVT = VT;
7061   MVT EltVT = VT.getVectorElementType();
7062
7063   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7064                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7065                 Mask.begin();
7066   bool IsV1Zeroable = true;
7067   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7068     if (i != V2Index && !Zeroable[i]) {
7069       IsV1Zeroable = false;
7070       break;
7071     }
7072
7073   // Check for a single input from a SCALAR_TO_VECTOR node.
7074   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7075   // all the smarts here sunk into that routine. However, the current
7076   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7077   // vector shuffle lowering is dead.
7078   if (SDValue V2S = getScalarValueForVectorElement(
7079           V2, Mask[V2Index] - Mask.size(), DAG)) {
7080     // We need to zext the scalar if it is smaller than an i32.
7081     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7082     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7083       // Using zext to expand a narrow element won't work for non-zero
7084       // insertions.
7085       if (!IsV1Zeroable)
7086         return SDValue();
7087
7088       // Zero-extend directly to i32.
7089       ExtVT = MVT::v4i32;
7090       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7091     }
7092     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7093   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7094              EltVT == MVT::i16) {
7095     // Either not inserting from the low element of the input or the input
7096     // element size is too small to use VZEXT_MOVL to clear the high bits.
7097     return SDValue();
7098   }
7099
7100   if (!IsV1Zeroable) {
7101     // If V1 can't be treated as a zero vector we have fewer options to lower
7102     // this. We can't support integer vectors or non-zero targets cheaply, and
7103     // the V1 elements can't be permuted in any way.
7104     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7105     if (!VT.isFloatingPoint() || V2Index != 0)
7106       return SDValue();
7107     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7108     V1Mask[V2Index] = -1;
7109     if (!isNoopShuffleMask(V1Mask))
7110       return SDValue();
7111     // This is essentially a special case blend operation, but if we have
7112     // general purpose blend operations, they are always faster. Bail and let
7113     // the rest of the lowering handle these as blends.
7114     if (Subtarget->hasSSE41())
7115       return SDValue();
7116
7117     // Otherwise, use MOVSD or MOVSS.
7118     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7119            "Only two types of floating point element types to handle!");
7120     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7121                        ExtVT, V1, V2);
7122   }
7123
7124   // This lowering only works for the low element with floating point vectors.
7125   if (VT.isFloatingPoint() && V2Index != 0)
7126     return SDValue();
7127
7128   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7129   if (ExtVT != VT)
7130     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7131
7132   if (V2Index != 0) {
7133     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7134     // the desired position. Otherwise it is more efficient to do a vector
7135     // shift left. We know that we can do a vector shift left because all
7136     // the inputs are zero.
7137     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7138       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7139       V2Shuffle[V2Index] = 0;
7140       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7141     } else {
7142       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7143       V2 = DAG.getNode(
7144           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7145           DAG.getConstant(
7146               V2Index * EltVT.getSizeInBits()/8, DL,
7147               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7148       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7149     }
7150   }
7151   return V2;
7152 }
7153
7154 /// \brief Try to lower broadcast of a single element.
7155 ///
7156 /// For convenience, this code also bundles all of the subtarget feature set
7157 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7158 /// a convenient way to factor it out.
7159 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7160                                              ArrayRef<int> Mask,
7161                                              const X86Subtarget *Subtarget,
7162                                              SelectionDAG &DAG) {
7163   if (!Subtarget->hasAVX())
7164     return SDValue();
7165   if (VT.isInteger() && !Subtarget->hasAVX2())
7166     return SDValue();
7167
7168   // Check that the mask is a broadcast.
7169   int BroadcastIdx = -1;
7170   for (int M : Mask)
7171     if (M >= 0 && BroadcastIdx == -1)
7172       BroadcastIdx = M;
7173     else if (M >= 0 && M != BroadcastIdx)
7174       return SDValue();
7175
7176   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7177                                             "a sorted mask where the broadcast "
7178                                             "comes from V1.");
7179
7180   // Go up the chain of (vector) values to find a scalar load that we can
7181   // combine with the broadcast.
7182   for (;;) {
7183     switch (V.getOpcode()) {
7184     case ISD::CONCAT_VECTORS: {
7185       int OperandSize = Mask.size() / V.getNumOperands();
7186       V = V.getOperand(BroadcastIdx / OperandSize);
7187       BroadcastIdx %= OperandSize;
7188       continue;
7189     }
7190
7191     case ISD::INSERT_SUBVECTOR: {
7192       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7193       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7194       if (!ConstantIdx)
7195         break;
7196
7197       int BeginIdx = (int)ConstantIdx->getZExtValue();
7198       int EndIdx =
7199           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7200       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7201         BroadcastIdx -= BeginIdx;
7202         V = VInner;
7203       } else {
7204         V = VOuter;
7205       }
7206       continue;
7207     }
7208     }
7209     break;
7210   }
7211
7212   // Check if this is a broadcast of a scalar. We special case lowering
7213   // for scalars so that we can more effectively fold with loads.
7214   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7215       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7216     V = V.getOperand(BroadcastIdx);
7217
7218     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7219     // Only AVX2 has register broadcasts.
7220     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7221       return SDValue();
7222   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7223     // We can't broadcast from a vector register without AVX2, and we can only
7224     // broadcast from the zero-element of a vector register.
7225     return SDValue();
7226   }
7227
7228   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7229 }
7230
7231 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7232 // INSERTPS when the V1 elements are already in the correct locations
7233 // because otherwise we can just always use two SHUFPS instructions which
7234 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7235 // perform INSERTPS if a single V1 element is out of place and all V2
7236 // elements are zeroable.
7237 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7238                                             ArrayRef<int> Mask,
7239                                             SelectionDAG &DAG) {
7240   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7241   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7242   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7243   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7244
7245   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7246
7247   unsigned ZMask = 0;
7248   int V1DstIndex = -1;
7249   int V2DstIndex = -1;
7250   bool V1UsedInPlace = false;
7251
7252   for (int i = 0; i < 4; ++i) {
7253     // Synthesize a zero mask from the zeroable elements (includes undefs).
7254     if (Zeroable[i]) {
7255       ZMask |= 1 << i;
7256       continue;
7257     }
7258
7259     // Flag if we use any V1 inputs in place.
7260     if (i == Mask[i]) {
7261       V1UsedInPlace = true;
7262       continue;
7263     }
7264
7265     // We can only insert a single non-zeroable element.
7266     if (V1DstIndex != -1 || V2DstIndex != -1)
7267       return SDValue();
7268
7269     if (Mask[i] < 4) {
7270       // V1 input out of place for insertion.
7271       V1DstIndex = i;
7272     } else {
7273       // V2 input for insertion.
7274       V2DstIndex = i;
7275     }
7276   }
7277
7278   // Don't bother if we have no (non-zeroable) element for insertion.
7279   if (V1DstIndex == -1 && V2DstIndex == -1)
7280     return SDValue();
7281
7282   // Determine element insertion src/dst indices. The src index is from the
7283   // start of the inserted vector, not the start of the concatenated vector.
7284   unsigned V2SrcIndex = 0;
7285   if (V1DstIndex != -1) {
7286     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7287     // and don't use the original V2 at all.
7288     V2SrcIndex = Mask[V1DstIndex];
7289     V2DstIndex = V1DstIndex;
7290     V2 = V1;
7291   } else {
7292     V2SrcIndex = Mask[V2DstIndex] - 4;
7293   }
7294
7295   // If no V1 inputs are used in place, then the result is created only from
7296   // the zero mask and the V2 insertion - so remove V1 dependency.
7297   if (!V1UsedInPlace)
7298     V1 = DAG.getUNDEF(MVT::v4f32);
7299
7300   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7301   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7302
7303   // Insert the V2 element into the desired position.
7304   SDLoc DL(Op);
7305   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7306                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7307 }
7308
7309 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7310 /// UNPCK instruction.
7311 ///
7312 /// This specifically targets cases where we end up with alternating between
7313 /// the two inputs, and so can permute them into something that feeds a single
7314 /// UNPCK instruction. Note that this routine only targets integer vectors
7315 /// because for floating point vectors we have a generalized SHUFPS lowering
7316 /// strategy that handles everything that doesn't *exactly* match an unpack,
7317 /// making this clever lowering unnecessary.
7318 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7319                                           SDValue V2, ArrayRef<int> Mask,
7320                                           SelectionDAG &DAG) {
7321   assert(!VT.isFloatingPoint() &&
7322          "This routine only supports integer vectors.");
7323   assert(!isSingleInputShuffleMask(Mask) &&
7324          "This routine should only be used when blending two inputs.");
7325   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7326
7327   int Size = Mask.size();
7328
7329   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7330     return M >= 0 && M % Size < Size / 2;
7331   });
7332   int NumHiInputs = std::count_if(
7333       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7334
7335   bool UnpackLo = NumLoInputs >= NumHiInputs;
7336
7337   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7338     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7339     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7340
7341     for (int i = 0; i < Size; ++i) {
7342       if (Mask[i] < 0)
7343         continue;
7344
7345       // Each element of the unpack contains Scale elements from this mask.
7346       int UnpackIdx = i / Scale;
7347
7348       // We only handle the case where V1 feeds the first slots of the unpack.
7349       // We rely on canonicalization to ensure this is the case.
7350       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7351         return SDValue();
7352
7353       // Setup the mask for this input. The indexing is tricky as we have to
7354       // handle the unpack stride.
7355       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7356       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7357           Mask[i] % Size;
7358     }
7359
7360     // If we will have to shuffle both inputs to use the unpack, check whether
7361     // we can just unpack first and shuffle the result. If so, skip this unpack.
7362     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7363         !isNoopShuffleMask(V2Mask))
7364       return SDValue();
7365
7366     // Shuffle the inputs into place.
7367     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7368     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7369
7370     // Cast the inputs to the type we will use to unpack them.
7371     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7372     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7373
7374     // Unpack the inputs and cast the result back to the desired type.
7375     return DAG.getNode(ISD::BITCAST, DL, VT,
7376                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7377                                    DL, UnpackVT, V1, V2));
7378   };
7379
7380   // We try each unpack from the largest to the smallest to try and find one
7381   // that fits this mask.
7382   int OrigNumElements = VT.getVectorNumElements();
7383   int OrigScalarSize = VT.getScalarSizeInBits();
7384   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7385     int Scale = ScalarSize / OrigScalarSize;
7386     int NumElements = OrigNumElements / Scale;
7387     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7388     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7389       return Unpack;
7390   }
7391
7392   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7393   // initial unpack.
7394   if (NumLoInputs == 0 || NumHiInputs == 0) {
7395     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7396            "We have to have *some* inputs!");
7397     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7398
7399     // FIXME: We could consider the total complexity of the permute of each
7400     // possible unpacking. Or at the least we should consider how many
7401     // half-crossings are created.
7402     // FIXME: We could consider commuting the unpacks.
7403
7404     SmallVector<int, 32> PermMask;
7405     PermMask.assign(Size, -1);
7406     for (int i = 0; i < Size; ++i) {
7407       if (Mask[i] < 0)
7408         continue;
7409
7410       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7411
7412       PermMask[i] =
7413           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7414     }
7415     return DAG.getVectorShuffle(
7416         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7417                             DL, VT, V1, V2),
7418         DAG.getUNDEF(VT), PermMask);
7419   }
7420
7421   return SDValue();
7422 }
7423
7424 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7425 ///
7426 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7427 /// support for floating point shuffles but not integer shuffles. These
7428 /// instructions will incur a domain crossing penalty on some chips though so
7429 /// it is better to avoid lowering through this for integer vectors where
7430 /// possible.
7431 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7432                                        const X86Subtarget *Subtarget,
7433                                        SelectionDAG &DAG) {
7434   SDLoc DL(Op);
7435   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7436   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7437   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7438   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7439   ArrayRef<int> Mask = SVOp->getMask();
7440   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7441
7442   if (isSingleInputShuffleMask(Mask)) {
7443     // Use low duplicate instructions for masks that match their pattern.
7444     if (Subtarget->hasSSE3())
7445       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7446         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7447
7448     // Straight shuffle of a single input vector. Simulate this by using the
7449     // single input as both of the "inputs" to this instruction..
7450     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7451
7452     if (Subtarget->hasAVX()) {
7453       // If we have AVX, we can use VPERMILPS which will allow folding a load
7454       // into the shuffle.
7455       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7456                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7457     }
7458
7459     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7460                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7461   }
7462   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7463   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7464
7465   // If we have a single input, insert that into V1 if we can do so cheaply.
7466   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7467     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7468             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7469       return Insertion;
7470     // Try inverting the insertion since for v2 masks it is easy to do and we
7471     // can't reliably sort the mask one way or the other.
7472     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7473                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7474     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7475             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7476       return Insertion;
7477   }
7478
7479   // Try to use one of the special instruction patterns to handle two common
7480   // blend patterns if a zero-blend above didn't work.
7481   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7482       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7483     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7484       // We can either use a special instruction to load over the low double or
7485       // to move just the low double.
7486       return DAG.getNode(
7487           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7488           DL, MVT::v2f64, V2,
7489           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7490
7491   if (Subtarget->hasSSE41())
7492     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7493                                                   Subtarget, DAG))
7494       return Blend;
7495
7496   // Use dedicated unpack instructions for masks that match their pattern.
7497   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7498     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7499   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7500     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7501
7502   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7503   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7504                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7505 }
7506
7507 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7508 ///
7509 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7510 /// the integer unit to minimize domain crossing penalties. However, for blends
7511 /// it falls back to the floating point shuffle operation with appropriate bit
7512 /// casting.
7513 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7514                                        const X86Subtarget *Subtarget,
7515                                        SelectionDAG &DAG) {
7516   SDLoc DL(Op);
7517   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7518   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7519   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7520   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7521   ArrayRef<int> Mask = SVOp->getMask();
7522   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7523
7524   if (isSingleInputShuffleMask(Mask)) {
7525     // Check for being able to broadcast a single element.
7526     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7527                                                           Mask, Subtarget, DAG))
7528       return Broadcast;
7529
7530     // Straight shuffle of a single input vector. For everything from SSE2
7531     // onward this has a single fast instruction with no scary immediates.
7532     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7533     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7534     int WidenedMask[4] = {
7535         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7536         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7537     return DAG.getNode(
7538         ISD::BITCAST, DL, MVT::v2i64,
7539         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7540                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7541   }
7542   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7543   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7544   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7545   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7546
7547   // If we have a blend of two PACKUS operations an the blend aligns with the
7548   // low and half halves, we can just merge the PACKUS operations. This is
7549   // particularly important as it lets us merge shuffles that this routine itself
7550   // creates.
7551   auto GetPackNode = [](SDValue V) {
7552     while (V.getOpcode() == ISD::BITCAST)
7553       V = V.getOperand(0);
7554
7555     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7556   };
7557   if (SDValue V1Pack = GetPackNode(V1))
7558     if (SDValue V2Pack = GetPackNode(V2))
7559       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7560                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7561                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7562                                                   : V1Pack.getOperand(1),
7563                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7564                                                   : V2Pack.getOperand(1)));
7565
7566   // Try to use shift instructions.
7567   if (SDValue Shift =
7568           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7569     return Shift;
7570
7571   // When loading a scalar and then shuffling it into a vector we can often do
7572   // the insertion cheaply.
7573   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7574           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7575     return Insertion;
7576   // Try inverting the insertion since for v2 masks it is easy to do and we
7577   // can't reliably sort the mask one way or the other.
7578   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7579   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7580           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7581     return Insertion;
7582
7583   // We have different paths for blend lowering, but they all must use the
7584   // *exact* same predicate.
7585   bool IsBlendSupported = Subtarget->hasSSE41();
7586   if (IsBlendSupported)
7587     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7588                                                   Subtarget, DAG))
7589       return Blend;
7590
7591   // Use dedicated unpack instructions for masks that match their pattern.
7592   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7593     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7594   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7595     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7596
7597   // Try to use byte rotation instructions.
7598   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7599   if (Subtarget->hasSSSE3())
7600     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7601             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7602       return Rotate;
7603
7604   // If we have direct support for blends, we should lower by decomposing into
7605   // a permute. That will be faster than the domain cross.
7606   if (IsBlendSupported)
7607     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7608                                                       Mask, DAG);
7609
7610   // We implement this with SHUFPD which is pretty lame because it will likely
7611   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7612   // However, all the alternatives are still more cycles and newer chips don't
7613   // have this problem. It would be really nice if x86 had better shuffles here.
7614   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7615   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7616   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7617                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7618 }
7619
7620 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7621 ///
7622 /// This is used to disable more specialized lowerings when the shufps lowering
7623 /// will happen to be efficient.
7624 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7625   // This routine only handles 128-bit shufps.
7626   assert(Mask.size() == 4 && "Unsupported mask size!");
7627
7628   // To lower with a single SHUFPS we need to have the low half and high half
7629   // each requiring a single input.
7630   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7631     return false;
7632   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7633     return false;
7634
7635   return true;
7636 }
7637
7638 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7639 ///
7640 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7641 /// It makes no assumptions about whether this is the *best* lowering, it simply
7642 /// uses it.
7643 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7644                                             ArrayRef<int> Mask, SDValue V1,
7645                                             SDValue V2, SelectionDAG &DAG) {
7646   SDValue LowV = V1, HighV = V2;
7647   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7648
7649   int NumV2Elements =
7650       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7651
7652   if (NumV2Elements == 1) {
7653     int V2Index =
7654         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7655         Mask.begin();
7656
7657     // Compute the index adjacent to V2Index and in the same half by toggling
7658     // the low bit.
7659     int V2AdjIndex = V2Index ^ 1;
7660
7661     if (Mask[V2AdjIndex] == -1) {
7662       // Handles all the cases where we have a single V2 element and an undef.
7663       // This will only ever happen in the high lanes because we commute the
7664       // vector otherwise.
7665       if (V2Index < 2)
7666         std::swap(LowV, HighV);
7667       NewMask[V2Index] -= 4;
7668     } else {
7669       // Handle the case where the V2 element ends up adjacent to a V1 element.
7670       // To make this work, blend them together as the first step.
7671       int V1Index = V2AdjIndex;
7672       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7673       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7674                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7675
7676       // Now proceed to reconstruct the final blend as we have the necessary
7677       // high or low half formed.
7678       if (V2Index < 2) {
7679         LowV = V2;
7680         HighV = V1;
7681       } else {
7682         HighV = V2;
7683       }
7684       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7685       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7686     }
7687   } else if (NumV2Elements == 2) {
7688     if (Mask[0] < 4 && Mask[1] < 4) {
7689       // Handle the easy case where we have V1 in the low lanes and V2 in the
7690       // high lanes.
7691       NewMask[2] -= 4;
7692       NewMask[3] -= 4;
7693     } else if (Mask[2] < 4 && Mask[3] < 4) {
7694       // We also handle the reversed case because this utility may get called
7695       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7696       // arrange things in the right direction.
7697       NewMask[0] -= 4;
7698       NewMask[1] -= 4;
7699       HighV = V1;
7700       LowV = V2;
7701     } else {
7702       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7703       // trying to place elements directly, just blend them and set up the final
7704       // shuffle to place them.
7705
7706       // The first two blend mask elements are for V1, the second two are for
7707       // V2.
7708       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7709                           Mask[2] < 4 ? Mask[2] : Mask[3],
7710                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7711                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7712       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7713                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7714
7715       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7716       // a blend.
7717       LowV = HighV = V1;
7718       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7719       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7720       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7721       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7722     }
7723   }
7724   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7725                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7726 }
7727
7728 /// \brief Lower 4-lane 32-bit floating point shuffles.
7729 ///
7730 /// Uses instructions exclusively from the floating point unit to minimize
7731 /// domain crossing penalties, as these are sufficient to implement all v4f32
7732 /// shuffles.
7733 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7734                                        const X86Subtarget *Subtarget,
7735                                        SelectionDAG &DAG) {
7736   SDLoc DL(Op);
7737   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7738   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7739   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7740   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7741   ArrayRef<int> Mask = SVOp->getMask();
7742   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7743
7744   int NumV2Elements =
7745       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7746
7747   if (NumV2Elements == 0) {
7748     // Check for being able to broadcast a single element.
7749     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7750                                                           Mask, Subtarget, DAG))
7751       return Broadcast;
7752
7753     // Use even/odd duplicate instructions for masks that match their pattern.
7754     if (Subtarget->hasSSE3()) {
7755       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7756         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7757       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7758         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7759     }
7760
7761     if (Subtarget->hasAVX()) {
7762       // If we have AVX, we can use VPERMILPS which will allow folding a load
7763       // into the shuffle.
7764       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7765                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7766     }
7767
7768     // Otherwise, use a straight shuffle of a single input vector. We pass the
7769     // input vector to both operands to simulate this with a SHUFPS.
7770     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7771                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7772   }
7773
7774   // There are special ways we can lower some single-element blends. However, we
7775   // have custom ways we can lower more complex single-element blends below that
7776   // we defer to if both this and BLENDPS fail to match, so restrict this to
7777   // when the V2 input is targeting element 0 of the mask -- that is the fast
7778   // case here.
7779   if (NumV2Elements == 1 && Mask[0] >= 4)
7780     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7781                                                          Mask, Subtarget, DAG))
7782       return V;
7783
7784   if (Subtarget->hasSSE41()) {
7785     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7786                                                   Subtarget, DAG))
7787       return Blend;
7788
7789     // Use INSERTPS if we can complete the shuffle efficiently.
7790     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7791       return V;
7792
7793     if (!isSingleSHUFPSMask(Mask))
7794       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7795               DL, MVT::v4f32, V1, V2, Mask, DAG))
7796         return BlendPerm;
7797   }
7798
7799   // Use dedicated unpack instructions for masks that match their pattern.
7800   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7801     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7802   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7803     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7804   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7805     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7806   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7807     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7808
7809   // Otherwise fall back to a SHUFPS lowering strategy.
7810   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7811 }
7812
7813 /// \brief Lower 4-lane i32 vector shuffles.
7814 ///
7815 /// We try to handle these with integer-domain shuffles where we can, but for
7816 /// blends we use the floating point domain blend instructions.
7817 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7818                                        const X86Subtarget *Subtarget,
7819                                        SelectionDAG &DAG) {
7820   SDLoc DL(Op);
7821   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7822   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7823   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7824   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7825   ArrayRef<int> Mask = SVOp->getMask();
7826   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7827
7828   // Whenever we can lower this as a zext, that instruction is strictly faster
7829   // than any alternative. It also allows us to fold memory operands into the
7830   // shuffle in many cases.
7831   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7832                                                          Mask, Subtarget, DAG))
7833     return ZExt;
7834
7835   int NumV2Elements =
7836       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7837
7838   if (NumV2Elements == 0) {
7839     // Check for being able to broadcast a single element.
7840     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7841                                                           Mask, Subtarget, DAG))
7842       return Broadcast;
7843
7844     // Straight shuffle of a single input vector. For everything from SSE2
7845     // onward this has a single fast instruction with no scary immediates.
7846     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7847     // but we aren't actually going to use the UNPCK instruction because doing
7848     // so prevents folding a load into this instruction or making a copy.
7849     const int UnpackLoMask[] = {0, 0, 1, 1};
7850     const int UnpackHiMask[] = {2, 2, 3, 3};
7851     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7852       Mask = UnpackLoMask;
7853     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7854       Mask = UnpackHiMask;
7855
7856     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7857                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7858   }
7859
7860   // Try to use shift instructions.
7861   if (SDValue Shift =
7862           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7863     return Shift;
7864
7865   // There are special ways we can lower some single-element blends.
7866   if (NumV2Elements == 1)
7867     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7868                                                          Mask, Subtarget, DAG))
7869       return V;
7870
7871   // We have different paths for blend lowering, but they all must use the
7872   // *exact* same predicate.
7873   bool IsBlendSupported = Subtarget->hasSSE41();
7874   if (IsBlendSupported)
7875     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7876                                                   Subtarget, DAG))
7877       return Blend;
7878
7879   if (SDValue Masked =
7880           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7881     return Masked;
7882
7883   // Use dedicated unpack instructions for masks that match their pattern.
7884   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7885     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7886   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7887     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7888   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7889     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7890   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7891     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7892
7893   // Try to use byte rotation instructions.
7894   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7895   if (Subtarget->hasSSSE3())
7896     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7897             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7898       return Rotate;
7899
7900   // If we have direct support for blends, we should lower by decomposing into
7901   // a permute. That will be faster than the domain cross.
7902   if (IsBlendSupported)
7903     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7904                                                       Mask, DAG);
7905
7906   // Try to lower by permuting the inputs into an unpack instruction.
7907   if (SDValue Unpack =
7908           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7909     return Unpack;
7910
7911   // We implement this with SHUFPS because it can blend from two vectors.
7912   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7913   // up the inputs, bypassing domain shift penalties that we would encur if we
7914   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7915   // relevant.
7916   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7917                      DAG.getVectorShuffle(
7918                          MVT::v4f32, DL,
7919                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7920                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7921 }
7922
7923 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7924 /// shuffle lowering, and the most complex part.
7925 ///
7926 /// The lowering strategy is to try to form pairs of input lanes which are
7927 /// targeted at the same half of the final vector, and then use a dword shuffle
7928 /// to place them onto the right half, and finally unpack the paired lanes into
7929 /// their final position.
7930 ///
7931 /// The exact breakdown of how to form these dword pairs and align them on the
7932 /// correct sides is really tricky. See the comments within the function for
7933 /// more of the details.
7934 ///
7935 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7936 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7937 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7938 /// vector, form the analogous 128-bit 8-element Mask.
7939 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7940     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7941     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7942   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7943   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7944
7945   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7946   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7947   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7948
7949   SmallVector<int, 4> LoInputs;
7950   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7951                [](int M) { return M >= 0; });
7952   std::sort(LoInputs.begin(), LoInputs.end());
7953   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7954   SmallVector<int, 4> HiInputs;
7955   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7956                [](int M) { return M >= 0; });
7957   std::sort(HiInputs.begin(), HiInputs.end());
7958   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7959   int NumLToL =
7960       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7961   int NumHToL = LoInputs.size() - NumLToL;
7962   int NumLToH =
7963       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7964   int NumHToH = HiInputs.size() - NumLToH;
7965   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7966   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7967   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7968   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7969
7970   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7971   // such inputs we can swap two of the dwords across the half mark and end up
7972   // with <=2 inputs to each half in each half. Once there, we can fall through
7973   // to the generic code below. For example:
7974   //
7975   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7976   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7977   //
7978   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7979   // and an existing 2-into-2 on the other half. In this case we may have to
7980   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7981   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7982   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7983   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7984   // half than the one we target for fixing) will be fixed when we re-enter this
7985   // path. We will also combine away any sequence of PSHUFD instructions that
7986   // result into a single instruction. Here is an example of the tricky case:
7987   //
7988   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7989   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7990   //
7991   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7992   //
7993   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7994   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7995   //
7996   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7997   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7998   //
7999   // The result is fine to be handled by the generic logic.
8000   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8001                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8002                           int AOffset, int BOffset) {
8003     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8004            "Must call this with A having 3 or 1 inputs from the A half.");
8005     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8006            "Must call this with B having 1 or 3 inputs from the B half.");
8007     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8008            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8009
8010     // Compute the index of dword with only one word among the three inputs in
8011     // a half by taking the sum of the half with three inputs and subtracting
8012     // the sum of the actual three inputs. The difference is the remaining
8013     // slot.
8014     int ADWord, BDWord;
8015     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8016     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8017     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8018     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8019     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8020     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8021     int TripleNonInputIdx =
8022         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8023     TripleDWord = TripleNonInputIdx / 2;
8024
8025     // We use xor with one to compute the adjacent DWord to whichever one the
8026     // OneInput is in.
8027     OneInputDWord = (OneInput / 2) ^ 1;
8028
8029     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8030     // and BToA inputs. If there is also such a problem with the BToB and AToB
8031     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8032     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8033     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8034     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8035       // Compute how many inputs will be flipped by swapping these DWords. We
8036       // need
8037       // to balance this to ensure we don't form a 3-1 shuffle in the other
8038       // half.
8039       int NumFlippedAToBInputs =
8040           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8041           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8042       int NumFlippedBToBInputs =
8043           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8044           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8045       if ((NumFlippedAToBInputs == 1 &&
8046            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8047           (NumFlippedBToBInputs == 1 &&
8048            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8049         // We choose whether to fix the A half or B half based on whether that
8050         // half has zero flipped inputs. At zero, we may not be able to fix it
8051         // with that half. We also bias towards fixing the B half because that
8052         // will more commonly be the high half, and we have to bias one way.
8053         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8054                                                        ArrayRef<int> Inputs) {
8055           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8056           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8057                                          PinnedIdx ^ 1) != Inputs.end();
8058           // Determine whether the free index is in the flipped dword or the
8059           // unflipped dword based on where the pinned index is. We use this bit
8060           // in an xor to conditionally select the adjacent dword.
8061           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8062           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8063                                              FixFreeIdx) != Inputs.end();
8064           if (IsFixIdxInput == IsFixFreeIdxInput)
8065             FixFreeIdx += 1;
8066           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8067                                         FixFreeIdx) != Inputs.end();
8068           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8069                  "We need to be changing the number of flipped inputs!");
8070           int PSHUFHalfMask[] = {0, 1, 2, 3};
8071           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8072           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8073                           MVT::v8i16, V,
8074                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8075
8076           for (int &M : Mask)
8077             if (M != -1 && M == FixIdx)
8078               M = FixFreeIdx;
8079             else if (M != -1 && M == FixFreeIdx)
8080               M = FixIdx;
8081         };
8082         if (NumFlippedBToBInputs != 0) {
8083           int BPinnedIdx =
8084               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8085           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8086         } else {
8087           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8088           int APinnedIdx =
8089               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8090           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8091         }
8092       }
8093     }
8094
8095     int PSHUFDMask[] = {0, 1, 2, 3};
8096     PSHUFDMask[ADWord] = BDWord;
8097     PSHUFDMask[BDWord] = ADWord;
8098     V = DAG.getNode(ISD::BITCAST, DL, VT,
8099                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8100                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8101                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8102                                                            DAG)));
8103
8104     // Adjust the mask to match the new locations of A and B.
8105     for (int &M : Mask)
8106       if (M != -1 && M/2 == ADWord)
8107         M = 2 * BDWord + M % 2;
8108       else if (M != -1 && M/2 == BDWord)
8109         M = 2 * ADWord + M % 2;
8110
8111     // Recurse back into this routine to re-compute state now that this isn't
8112     // a 3 and 1 problem.
8113     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8114                                                      DAG);
8115   };
8116   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8117     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8118   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8119     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8120
8121   // At this point there are at most two inputs to the low and high halves from
8122   // each half. That means the inputs can always be grouped into dwords and
8123   // those dwords can then be moved to the correct half with a dword shuffle.
8124   // We use at most one low and one high word shuffle to collect these paired
8125   // inputs into dwords, and finally a dword shuffle to place them.
8126   int PSHUFLMask[4] = {-1, -1, -1, -1};
8127   int PSHUFHMask[4] = {-1, -1, -1, -1};
8128   int PSHUFDMask[4] = {-1, -1, -1, -1};
8129
8130   // First fix the masks for all the inputs that are staying in their
8131   // original halves. This will then dictate the targets of the cross-half
8132   // shuffles.
8133   auto fixInPlaceInputs =
8134       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8135                     MutableArrayRef<int> SourceHalfMask,
8136                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8137     if (InPlaceInputs.empty())
8138       return;
8139     if (InPlaceInputs.size() == 1) {
8140       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8141           InPlaceInputs[0] - HalfOffset;
8142       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8143       return;
8144     }
8145     if (IncomingInputs.empty()) {
8146       // Just fix all of the in place inputs.
8147       for (int Input : InPlaceInputs) {
8148         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8149         PSHUFDMask[Input / 2] = Input / 2;
8150       }
8151       return;
8152     }
8153
8154     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8155     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8156         InPlaceInputs[0] - HalfOffset;
8157     // Put the second input next to the first so that they are packed into
8158     // a dword. We find the adjacent index by toggling the low bit.
8159     int AdjIndex = InPlaceInputs[0] ^ 1;
8160     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8161     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8162     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8163   };
8164   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8165   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8166
8167   // Now gather the cross-half inputs and place them into a free dword of
8168   // their target half.
8169   // FIXME: This operation could almost certainly be simplified dramatically to
8170   // look more like the 3-1 fixing operation.
8171   auto moveInputsToRightHalf = [&PSHUFDMask](
8172       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8173       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8174       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8175       int DestOffset) {
8176     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8177       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8178     };
8179     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8180                                                int Word) {
8181       int LowWord = Word & ~1;
8182       int HighWord = Word | 1;
8183       return isWordClobbered(SourceHalfMask, LowWord) ||
8184              isWordClobbered(SourceHalfMask, HighWord);
8185     };
8186
8187     if (IncomingInputs.empty())
8188       return;
8189
8190     if (ExistingInputs.empty()) {
8191       // Map any dwords with inputs from them into the right half.
8192       for (int Input : IncomingInputs) {
8193         // If the source half mask maps over the inputs, turn those into
8194         // swaps and use the swapped lane.
8195         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8196           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8197             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8198                 Input - SourceOffset;
8199             // We have to swap the uses in our half mask in one sweep.
8200             for (int &M : HalfMask)
8201               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8202                 M = Input;
8203               else if (M == Input)
8204                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8205           } else {
8206             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8207                        Input - SourceOffset &&
8208                    "Previous placement doesn't match!");
8209           }
8210           // Note that this correctly re-maps both when we do a swap and when
8211           // we observe the other side of the swap above. We rely on that to
8212           // avoid swapping the members of the input list directly.
8213           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8214         }
8215
8216         // Map the input's dword into the correct half.
8217         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8218           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8219         else
8220           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8221                      Input / 2 &&
8222                  "Previous placement doesn't match!");
8223       }
8224
8225       // And just directly shift any other-half mask elements to be same-half
8226       // as we will have mirrored the dword containing the element into the
8227       // same position within that half.
8228       for (int &M : HalfMask)
8229         if (M >= SourceOffset && M < SourceOffset + 4) {
8230           M = M - SourceOffset + DestOffset;
8231           assert(M >= 0 && "This should never wrap below zero!");
8232         }
8233       return;
8234     }
8235
8236     // Ensure we have the input in a viable dword of its current half. This
8237     // is particularly tricky because the original position may be clobbered
8238     // by inputs being moved and *staying* in that half.
8239     if (IncomingInputs.size() == 1) {
8240       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8241         int InputFixed = std::find(std::begin(SourceHalfMask),
8242                                    std::end(SourceHalfMask), -1) -
8243                          std::begin(SourceHalfMask) + SourceOffset;
8244         SourceHalfMask[InputFixed - SourceOffset] =
8245             IncomingInputs[0] - SourceOffset;
8246         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8247                      InputFixed);
8248         IncomingInputs[0] = InputFixed;
8249       }
8250     } else if (IncomingInputs.size() == 2) {
8251       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8252           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8253         // We have two non-adjacent or clobbered inputs we need to extract from
8254         // the source half. To do this, we need to map them into some adjacent
8255         // dword slot in the source mask.
8256         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8257                               IncomingInputs[1] - SourceOffset};
8258
8259         // If there is a free slot in the source half mask adjacent to one of
8260         // the inputs, place the other input in it. We use (Index XOR 1) to
8261         // compute an adjacent index.
8262         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8263             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8264           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8265           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8266           InputsFixed[1] = InputsFixed[0] ^ 1;
8267         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8268                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8269           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8270           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8271           InputsFixed[0] = InputsFixed[1] ^ 1;
8272         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8273                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8274           // The two inputs are in the same DWord but it is clobbered and the
8275           // adjacent DWord isn't used at all. Move both inputs to the free
8276           // slot.
8277           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8278           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8279           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8280           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8281         } else {
8282           // The only way we hit this point is if there is no clobbering
8283           // (because there are no off-half inputs to this half) and there is no
8284           // free slot adjacent to one of the inputs. In this case, we have to
8285           // swap an input with a non-input.
8286           for (int i = 0; i < 4; ++i)
8287             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8288                    "We can't handle any clobbers here!");
8289           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8290                  "Cannot have adjacent inputs here!");
8291
8292           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8293           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8294
8295           // We also have to update the final source mask in this case because
8296           // it may need to undo the above swap.
8297           for (int &M : FinalSourceHalfMask)
8298             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8299               M = InputsFixed[1] + SourceOffset;
8300             else if (M == InputsFixed[1] + SourceOffset)
8301               M = (InputsFixed[0] ^ 1) + SourceOffset;
8302
8303           InputsFixed[1] = InputsFixed[0] ^ 1;
8304         }
8305
8306         // Point everything at the fixed inputs.
8307         for (int &M : HalfMask)
8308           if (M == IncomingInputs[0])
8309             M = InputsFixed[0] + SourceOffset;
8310           else if (M == IncomingInputs[1])
8311             M = InputsFixed[1] + SourceOffset;
8312
8313         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8314         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8315       }
8316     } else {
8317       llvm_unreachable("Unhandled input size!");
8318     }
8319
8320     // Now hoist the DWord down to the right half.
8321     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8322     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8323     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8324     for (int &M : HalfMask)
8325       for (int Input : IncomingInputs)
8326         if (M == Input)
8327           M = FreeDWord * 2 + Input % 2;
8328   };
8329   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8330                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8331   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8332                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8333
8334   // Now enact all the shuffles we've computed to move the inputs into their
8335   // target half.
8336   if (!isNoopShuffleMask(PSHUFLMask))
8337     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8338                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8339   if (!isNoopShuffleMask(PSHUFHMask))
8340     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8341                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8342   if (!isNoopShuffleMask(PSHUFDMask))
8343     V = DAG.getNode(ISD::BITCAST, DL, VT,
8344                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8345                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8346                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8347                                                            DAG)));
8348
8349   // At this point, each half should contain all its inputs, and we can then
8350   // just shuffle them into their final position.
8351   assert(std::count_if(LoMask.begin(), LoMask.end(),
8352                        [](int M) { return M >= 4; }) == 0 &&
8353          "Failed to lift all the high half inputs to the low mask!");
8354   assert(std::count_if(HiMask.begin(), HiMask.end(),
8355                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8356          "Failed to lift all the low half inputs to the high mask!");
8357
8358   // Do a half shuffle for the low mask.
8359   if (!isNoopShuffleMask(LoMask))
8360     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8361                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8362
8363   // Do a half shuffle with the high mask after shifting its values down.
8364   for (int &M : HiMask)
8365     if (M >= 0)
8366       M -= 4;
8367   if (!isNoopShuffleMask(HiMask))
8368     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8369                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8370
8371   return V;
8372 }
8373
8374 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8375 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8376                                           SDValue V2, ArrayRef<int> Mask,
8377                                           SelectionDAG &DAG, bool &V1InUse,
8378                                           bool &V2InUse) {
8379   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8380   SDValue V1Mask[16];
8381   SDValue V2Mask[16];
8382   V1InUse = false;
8383   V2InUse = false;
8384
8385   int Size = Mask.size();
8386   int Scale = 16 / Size;
8387   for (int i = 0; i < 16; ++i) {
8388     if (Mask[i / Scale] == -1) {
8389       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8390     } else {
8391       const int ZeroMask = 0x80;
8392       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8393                                           : ZeroMask;
8394       int V2Idx = Mask[i / Scale] < Size
8395                       ? ZeroMask
8396                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8397       if (Zeroable[i / Scale])
8398         V1Idx = V2Idx = ZeroMask;
8399       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8400       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8401       V1InUse |= (ZeroMask != V1Idx);
8402       V2InUse |= (ZeroMask != V2Idx);
8403     }
8404   }
8405
8406   if (V1InUse)
8407     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8408                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8409                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8410   if (V2InUse)
8411     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8412                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8413                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8414
8415   // If we need shuffled inputs from both, blend the two.
8416   SDValue V;
8417   if (V1InUse && V2InUse)
8418     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8419   else
8420     V = V1InUse ? V1 : V2;
8421
8422   // Cast the result back to the correct type.
8423   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8424 }
8425
8426 /// \brief Generic lowering of 8-lane i16 shuffles.
8427 ///
8428 /// This handles both single-input shuffles and combined shuffle/blends with
8429 /// two inputs. The single input shuffles are immediately delegated to
8430 /// a dedicated lowering routine.
8431 ///
8432 /// The blends are lowered in one of three fundamental ways. If there are few
8433 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8434 /// of the input is significantly cheaper when lowered as an interleaving of
8435 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8436 /// halves of the inputs separately (making them have relatively few inputs)
8437 /// and then concatenate them.
8438 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8439                                        const X86Subtarget *Subtarget,
8440                                        SelectionDAG &DAG) {
8441   SDLoc DL(Op);
8442   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8443   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8444   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8445   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8446   ArrayRef<int> OrigMask = SVOp->getMask();
8447   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8448                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8449   MutableArrayRef<int> Mask(MaskStorage);
8450
8451   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8452
8453   // Whenever we can lower this as a zext, that instruction is strictly faster
8454   // than any alternative.
8455   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8456           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8457     return ZExt;
8458
8459   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8460   (void)isV1;
8461   auto isV2 = [](int M) { return M >= 8; };
8462
8463   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8464
8465   if (NumV2Inputs == 0) {
8466     // Check for being able to broadcast a single element.
8467     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8468                                                           Mask, Subtarget, DAG))
8469       return Broadcast;
8470
8471     // Try to use shift instructions.
8472     if (SDValue Shift =
8473             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8474       return Shift;
8475
8476     // Use dedicated unpack instructions for masks that match their pattern.
8477     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8478       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8479     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8480       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8481
8482     // Try to use byte rotation instructions.
8483     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8484                                                         Mask, Subtarget, DAG))
8485       return Rotate;
8486
8487     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8488                                                      Subtarget, DAG);
8489   }
8490
8491   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8492          "All single-input shuffles should be canonicalized to be V1-input "
8493          "shuffles.");
8494
8495   // Try to use shift instructions.
8496   if (SDValue Shift =
8497           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8498     return Shift;
8499
8500   // There are special ways we can lower some single-element blends.
8501   if (NumV2Inputs == 1)
8502     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8503                                                          Mask, Subtarget, DAG))
8504       return V;
8505
8506   // We have different paths for blend lowering, but they all must use the
8507   // *exact* same predicate.
8508   bool IsBlendSupported = Subtarget->hasSSE41();
8509   if (IsBlendSupported)
8510     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8511                                                   Subtarget, DAG))
8512       return Blend;
8513
8514   if (SDValue Masked =
8515           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8516     return Masked;
8517
8518   // Use dedicated unpack instructions for masks that match their pattern.
8519   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8520     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8521   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8522     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8523
8524   // Try to use byte rotation instructions.
8525   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8526           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8527     return Rotate;
8528
8529   if (SDValue BitBlend =
8530           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8531     return BitBlend;
8532
8533   if (SDValue Unpack =
8534           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8535     return Unpack;
8536
8537   // If we can't directly blend but can use PSHUFB, that will be better as it
8538   // can both shuffle and set up the inefficient blend.
8539   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8540     bool V1InUse, V2InUse;
8541     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8542                                       V1InUse, V2InUse);
8543   }
8544
8545   // We can always bit-blend if we have to so the fallback strategy is to
8546   // decompose into single-input permutes and blends.
8547   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8548                                                       Mask, DAG);
8549 }
8550
8551 /// \brief Check whether a compaction lowering can be done by dropping even
8552 /// elements and compute how many times even elements must be dropped.
8553 ///
8554 /// This handles shuffles which take every Nth element where N is a power of
8555 /// two. Example shuffle masks:
8556 ///
8557 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8558 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8559 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8560 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8561 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8562 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8563 ///
8564 /// Any of these lanes can of course be undef.
8565 ///
8566 /// This routine only supports N <= 3.
8567 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8568 /// for larger N.
8569 ///
8570 /// \returns N above, or the number of times even elements must be dropped if
8571 /// there is such a number. Otherwise returns zero.
8572 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8573   // Figure out whether we're looping over two inputs or just one.
8574   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8575
8576   // The modulus for the shuffle vector entries is based on whether this is
8577   // a single input or not.
8578   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8579   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8580          "We should only be called with masks with a power-of-2 size!");
8581
8582   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8583
8584   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8585   // and 2^3 simultaneously. This is because we may have ambiguity with
8586   // partially undef inputs.
8587   bool ViableForN[3] = {true, true, true};
8588
8589   for (int i = 0, e = Mask.size(); i < e; ++i) {
8590     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8591     // want.
8592     if (Mask[i] == -1)
8593       continue;
8594
8595     bool IsAnyViable = false;
8596     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8597       if (ViableForN[j]) {
8598         uint64_t N = j + 1;
8599
8600         // The shuffle mask must be equal to (i * 2^N) % M.
8601         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8602           IsAnyViable = true;
8603         else
8604           ViableForN[j] = false;
8605       }
8606     // Early exit if we exhaust the possible powers of two.
8607     if (!IsAnyViable)
8608       break;
8609   }
8610
8611   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8612     if (ViableForN[j])
8613       return j + 1;
8614
8615   // Return 0 as there is no viable power of two.
8616   return 0;
8617 }
8618
8619 /// \brief Generic lowering of v16i8 shuffles.
8620 ///
8621 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8622 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8623 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8624 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8625 /// back together.
8626 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8627                                        const X86Subtarget *Subtarget,
8628                                        SelectionDAG &DAG) {
8629   SDLoc DL(Op);
8630   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8631   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8632   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8633   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8634   ArrayRef<int> Mask = SVOp->getMask();
8635   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8636
8637   // Try to use shift instructions.
8638   if (SDValue Shift =
8639           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8640     return Shift;
8641
8642   // Try to use byte rotation instructions.
8643   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8644           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8645     return Rotate;
8646
8647   // Try to use a zext lowering.
8648   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8649           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8650     return ZExt;
8651
8652   int NumV2Elements =
8653       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8654
8655   // For single-input shuffles, there are some nicer lowering tricks we can use.
8656   if (NumV2Elements == 0) {
8657     // Check for being able to broadcast a single element.
8658     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8659                                                           Mask, Subtarget, DAG))
8660       return Broadcast;
8661
8662     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8663     // Notably, this handles splat and partial-splat shuffles more efficiently.
8664     // However, it only makes sense if the pre-duplication shuffle simplifies
8665     // things significantly. Currently, this means we need to be able to
8666     // express the pre-duplication shuffle as an i16 shuffle.
8667     //
8668     // FIXME: We should check for other patterns which can be widened into an
8669     // i16 shuffle as well.
8670     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8671       for (int i = 0; i < 16; i += 2)
8672         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8673           return false;
8674
8675       return true;
8676     };
8677     auto tryToWidenViaDuplication = [&]() -> SDValue {
8678       if (!canWidenViaDuplication(Mask))
8679         return SDValue();
8680       SmallVector<int, 4> LoInputs;
8681       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8682                    [](int M) { return M >= 0 && M < 8; });
8683       std::sort(LoInputs.begin(), LoInputs.end());
8684       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8685                      LoInputs.end());
8686       SmallVector<int, 4> HiInputs;
8687       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8688                    [](int M) { return M >= 8; });
8689       std::sort(HiInputs.begin(), HiInputs.end());
8690       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8691                      HiInputs.end());
8692
8693       bool TargetLo = LoInputs.size() >= HiInputs.size();
8694       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8695       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8696
8697       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8698       SmallDenseMap<int, int, 8> LaneMap;
8699       for (int I : InPlaceInputs) {
8700         PreDupI16Shuffle[I/2] = I/2;
8701         LaneMap[I] = I;
8702       }
8703       int j = TargetLo ? 0 : 4, je = j + 4;
8704       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8705         // Check if j is already a shuffle of this input. This happens when
8706         // there are two adjacent bytes after we move the low one.
8707         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8708           // If we haven't yet mapped the input, search for a slot into which
8709           // we can map it.
8710           while (j < je && PreDupI16Shuffle[j] != -1)
8711             ++j;
8712
8713           if (j == je)
8714             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8715             return SDValue();
8716
8717           // Map this input with the i16 shuffle.
8718           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8719         }
8720
8721         // Update the lane map based on the mapping we ended up with.
8722         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8723       }
8724       V1 = DAG.getNode(
8725           ISD::BITCAST, DL, MVT::v16i8,
8726           DAG.getVectorShuffle(MVT::v8i16, DL,
8727                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8728                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8729
8730       // Unpack the bytes to form the i16s that will be shuffled into place.
8731       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8732                        MVT::v16i8, V1, V1);
8733
8734       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8735       for (int i = 0; i < 16; ++i)
8736         if (Mask[i] != -1) {
8737           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8738           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8739           if (PostDupI16Shuffle[i / 2] == -1)
8740             PostDupI16Shuffle[i / 2] = MappedMask;
8741           else
8742             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8743                    "Conflicting entrties in the original shuffle!");
8744         }
8745       return DAG.getNode(
8746           ISD::BITCAST, DL, MVT::v16i8,
8747           DAG.getVectorShuffle(MVT::v8i16, DL,
8748                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8749                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8750     };
8751     if (SDValue V = tryToWidenViaDuplication())
8752       return V;
8753   }
8754
8755   // Use dedicated unpack instructions for masks that match their pattern.
8756   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8757                                          0, 16, 1, 17, 2, 18, 3, 19,
8758                                          // High half.
8759                                          4, 20, 5, 21, 6, 22, 7, 23}))
8760     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8761   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8762                                          8, 24, 9, 25, 10, 26, 11, 27,
8763                                          // High half.
8764                                          12, 28, 13, 29, 14, 30, 15, 31}))
8765     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8766
8767   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8768   // with PSHUFB. It is important to do this before we attempt to generate any
8769   // blends but after all of the single-input lowerings. If the single input
8770   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8771   // want to preserve that and we can DAG combine any longer sequences into
8772   // a PSHUFB in the end. But once we start blending from multiple inputs,
8773   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8774   // and there are *very* few patterns that would actually be faster than the
8775   // PSHUFB approach because of its ability to zero lanes.
8776   //
8777   // FIXME: The only exceptions to the above are blends which are exact
8778   // interleavings with direct instructions supporting them. We currently don't
8779   // handle those well here.
8780   if (Subtarget->hasSSSE3()) {
8781     bool V1InUse = false;
8782     bool V2InUse = false;
8783
8784     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8785                                                 DAG, V1InUse, V2InUse);
8786
8787     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8788     // do so. This avoids using them to handle blends-with-zero which is
8789     // important as a single pshufb is significantly faster for that.
8790     if (V1InUse && V2InUse) {
8791       if (Subtarget->hasSSE41())
8792         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8793                                                       Mask, Subtarget, DAG))
8794           return Blend;
8795
8796       // We can use an unpack to do the blending rather than an or in some
8797       // cases. Even though the or may be (very minorly) more efficient, we
8798       // preference this lowering because there are common cases where part of
8799       // the complexity of the shuffles goes away when we do the final blend as
8800       // an unpack.
8801       // FIXME: It might be worth trying to detect if the unpack-feeding
8802       // shuffles will both be pshufb, in which case we shouldn't bother with
8803       // this.
8804       if (SDValue Unpack =
8805               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8806         return Unpack;
8807     }
8808
8809     return PSHUFB;
8810   }
8811
8812   // There are special ways we can lower some single-element blends.
8813   if (NumV2Elements == 1)
8814     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8815                                                          Mask, Subtarget, DAG))
8816       return V;
8817
8818   if (SDValue BitBlend =
8819           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8820     return BitBlend;
8821
8822   // Check whether a compaction lowering can be done. This handles shuffles
8823   // which take every Nth element for some even N. See the helper function for
8824   // details.
8825   //
8826   // We special case these as they can be particularly efficiently handled with
8827   // the PACKUSB instruction on x86 and they show up in common patterns of
8828   // rearranging bytes to truncate wide elements.
8829   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8830     // NumEvenDrops is the power of two stride of the elements. Another way of
8831     // thinking about it is that we need to drop the even elements this many
8832     // times to get the original input.
8833     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8834
8835     // First we need to zero all the dropped bytes.
8836     assert(NumEvenDrops <= 3 &&
8837            "No support for dropping even elements more than 3 times.");
8838     // We use the mask type to pick which bytes are preserved based on how many
8839     // elements are dropped.
8840     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8841     SDValue ByteClearMask =
8842         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8843                     DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8844     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8845     if (!IsSingleInput)
8846       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8847
8848     // Now pack things back together.
8849     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8850     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8851     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8852     for (int i = 1; i < NumEvenDrops; ++i) {
8853       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8854       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8855     }
8856
8857     return Result;
8858   }
8859
8860   // Handle multi-input cases by blending single-input shuffles.
8861   if (NumV2Elements > 0)
8862     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8863                                                       Mask, DAG);
8864
8865   // The fallback path for single-input shuffles widens this into two v8i16
8866   // vectors with unpacks, shuffles those, and then pulls them back together
8867   // with a pack.
8868   SDValue V = V1;
8869
8870   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8871   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8872   for (int i = 0; i < 16; ++i)
8873     if (Mask[i] >= 0)
8874       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8875
8876   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8877
8878   SDValue VLoHalf, VHiHalf;
8879   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8880   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8881   // i16s.
8882   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8883                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8884       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8885                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8886     // Use a mask to drop the high bytes.
8887     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8888     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8889                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8890
8891     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8892     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8893
8894     // Squash the masks to point directly into VLoHalf.
8895     for (int &M : LoBlendMask)
8896       if (M >= 0)
8897         M /= 2;
8898     for (int &M : HiBlendMask)
8899       if (M >= 0)
8900         M /= 2;
8901   } else {
8902     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8903     // VHiHalf so that we can blend them as i16s.
8904     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8905                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8906     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8907                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8908   }
8909
8910   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8911   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8912
8913   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8914 }
8915
8916 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8917 ///
8918 /// This routine breaks down the specific type of 128-bit shuffle and
8919 /// dispatches to the lowering routines accordingly.
8920 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8921                                         MVT VT, const X86Subtarget *Subtarget,
8922                                         SelectionDAG &DAG) {
8923   switch (VT.SimpleTy) {
8924   case MVT::v2i64:
8925     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8926   case MVT::v2f64:
8927     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8928   case MVT::v4i32:
8929     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8930   case MVT::v4f32:
8931     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8932   case MVT::v8i16:
8933     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8934   case MVT::v16i8:
8935     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8936
8937   default:
8938     llvm_unreachable("Unimplemented!");
8939   }
8940 }
8941
8942 /// \brief Helper function to test whether a shuffle mask could be
8943 /// simplified by widening the elements being shuffled.
8944 ///
8945 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8946 /// leaves it in an unspecified state.
8947 ///
8948 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8949 /// shuffle masks. The latter have the special property of a '-2' representing
8950 /// a zero-ed lane of a vector.
8951 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8952                                     SmallVectorImpl<int> &WidenedMask) {
8953   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8954     // If both elements are undef, its trivial.
8955     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8956       WidenedMask.push_back(SM_SentinelUndef);
8957       continue;
8958     }
8959
8960     // Check for an undef mask and a mask value properly aligned to fit with
8961     // a pair of values. If we find such a case, use the non-undef mask's value.
8962     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8963       WidenedMask.push_back(Mask[i + 1] / 2);
8964       continue;
8965     }
8966     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8967       WidenedMask.push_back(Mask[i] / 2);
8968       continue;
8969     }
8970
8971     // When zeroing, we need to spread the zeroing across both lanes to widen.
8972     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8973       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8974           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8975         WidenedMask.push_back(SM_SentinelZero);
8976         continue;
8977       }
8978       return false;
8979     }
8980
8981     // Finally check if the two mask values are adjacent and aligned with
8982     // a pair.
8983     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8984       WidenedMask.push_back(Mask[i] / 2);
8985       continue;
8986     }
8987
8988     // Otherwise we can't safely widen the elements used in this shuffle.
8989     return false;
8990   }
8991   assert(WidenedMask.size() == Mask.size() / 2 &&
8992          "Incorrect size of mask after widening the elements!");
8993
8994   return true;
8995 }
8996
8997 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8998 ///
8999 /// This routine just extracts two subvectors, shuffles them independently, and
9000 /// then concatenates them back together. This should work effectively with all
9001 /// AVX vector shuffle types.
9002 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9003                                           SDValue V2, ArrayRef<int> Mask,
9004                                           SelectionDAG &DAG) {
9005   assert(VT.getSizeInBits() >= 256 &&
9006          "Only for 256-bit or wider vector shuffles!");
9007   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9008   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9009
9010   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9011   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9012
9013   int NumElements = VT.getVectorNumElements();
9014   int SplitNumElements = NumElements / 2;
9015   MVT ScalarVT = VT.getScalarType();
9016   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9017
9018   // Rather than splitting build-vectors, just build two narrower build
9019   // vectors. This helps shuffling with splats and zeros.
9020   auto SplitVector = [&](SDValue V) {
9021     while (V.getOpcode() == ISD::BITCAST)
9022       V = V->getOperand(0);
9023
9024     MVT OrigVT = V.getSimpleValueType();
9025     int OrigNumElements = OrigVT.getVectorNumElements();
9026     int OrigSplitNumElements = OrigNumElements / 2;
9027     MVT OrigScalarVT = OrigVT.getScalarType();
9028     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9029
9030     SDValue LoV, HiV;
9031
9032     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9033     if (!BV) {
9034       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9035                         DAG.getIntPtrConstant(0, DL));
9036       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9037                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9038     } else {
9039
9040       SmallVector<SDValue, 16> LoOps, HiOps;
9041       for (int i = 0; i < OrigSplitNumElements; ++i) {
9042         LoOps.push_back(BV->getOperand(i));
9043         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9044       }
9045       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9046       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9047     }
9048     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9049                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9050   };
9051
9052   SDValue LoV1, HiV1, LoV2, HiV2;
9053   std::tie(LoV1, HiV1) = SplitVector(V1);
9054   std::tie(LoV2, HiV2) = SplitVector(V2);
9055
9056   // Now create two 4-way blends of these half-width vectors.
9057   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9058     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9059     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9060     for (int i = 0; i < SplitNumElements; ++i) {
9061       int M = HalfMask[i];
9062       if (M >= NumElements) {
9063         if (M >= NumElements + SplitNumElements)
9064           UseHiV2 = true;
9065         else
9066           UseLoV2 = true;
9067         V2BlendMask.push_back(M - NumElements);
9068         V1BlendMask.push_back(-1);
9069         BlendMask.push_back(SplitNumElements + i);
9070       } else if (M >= 0) {
9071         if (M >= SplitNumElements)
9072           UseHiV1 = true;
9073         else
9074           UseLoV1 = true;
9075         V2BlendMask.push_back(-1);
9076         V1BlendMask.push_back(M);
9077         BlendMask.push_back(i);
9078       } else {
9079         V2BlendMask.push_back(-1);
9080         V1BlendMask.push_back(-1);
9081         BlendMask.push_back(-1);
9082       }
9083     }
9084
9085     // Because the lowering happens after all combining takes place, we need to
9086     // manually combine these blend masks as much as possible so that we create
9087     // a minimal number of high-level vector shuffle nodes.
9088
9089     // First try just blending the halves of V1 or V2.
9090     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9091       return DAG.getUNDEF(SplitVT);
9092     if (!UseLoV2 && !UseHiV2)
9093       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9094     if (!UseLoV1 && !UseHiV1)
9095       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9096
9097     SDValue V1Blend, V2Blend;
9098     if (UseLoV1 && UseHiV1) {
9099       V1Blend =
9100         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9101     } else {
9102       // We only use half of V1 so map the usage down into the final blend mask.
9103       V1Blend = UseLoV1 ? LoV1 : HiV1;
9104       for (int i = 0; i < SplitNumElements; ++i)
9105         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9106           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9107     }
9108     if (UseLoV2 && UseHiV2) {
9109       V2Blend =
9110         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9111     } else {
9112       // We only use half of V2 so map the usage down into the final blend mask.
9113       V2Blend = UseLoV2 ? LoV2 : HiV2;
9114       for (int i = 0; i < SplitNumElements; ++i)
9115         if (BlendMask[i] >= SplitNumElements)
9116           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9117     }
9118     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9119   };
9120   SDValue Lo = HalfBlend(LoMask);
9121   SDValue Hi = HalfBlend(HiMask);
9122   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9123 }
9124
9125 /// \brief Either split a vector in halves or decompose the shuffles and the
9126 /// blend.
9127 ///
9128 /// This is provided as a good fallback for many lowerings of non-single-input
9129 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9130 /// between splitting the shuffle into 128-bit components and stitching those
9131 /// back together vs. extracting the single-input shuffles and blending those
9132 /// results.
9133 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9134                                                 SDValue V2, ArrayRef<int> Mask,
9135                                                 SelectionDAG &DAG) {
9136   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9137                                             "lower single-input shuffles as it "
9138                                             "could then recurse on itself.");
9139   int Size = Mask.size();
9140
9141   // If this can be modeled as a broadcast of two elements followed by a blend,
9142   // prefer that lowering. This is especially important because broadcasts can
9143   // often fold with memory operands.
9144   auto DoBothBroadcast = [&] {
9145     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9146     for (int M : Mask)
9147       if (M >= Size) {
9148         if (V2BroadcastIdx == -1)
9149           V2BroadcastIdx = M - Size;
9150         else if (M - Size != V2BroadcastIdx)
9151           return false;
9152       } else if (M >= 0) {
9153         if (V1BroadcastIdx == -1)
9154           V1BroadcastIdx = M;
9155         else if (M != V1BroadcastIdx)
9156           return false;
9157       }
9158     return true;
9159   };
9160   if (DoBothBroadcast())
9161     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9162                                                       DAG);
9163
9164   // If the inputs all stem from a single 128-bit lane of each input, then we
9165   // split them rather than blending because the split will decompose to
9166   // unusually few instructions.
9167   int LaneCount = VT.getSizeInBits() / 128;
9168   int LaneSize = Size / LaneCount;
9169   SmallBitVector LaneInputs[2];
9170   LaneInputs[0].resize(LaneCount, false);
9171   LaneInputs[1].resize(LaneCount, false);
9172   for (int i = 0; i < Size; ++i)
9173     if (Mask[i] >= 0)
9174       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9175   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9176     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9177
9178   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9179   // that the decomposed single-input shuffles don't end up here.
9180   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9181 }
9182
9183 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9184 /// a permutation and blend of those lanes.
9185 ///
9186 /// This essentially blends the out-of-lane inputs to each lane into the lane
9187 /// from a permuted copy of the vector. This lowering strategy results in four
9188 /// instructions in the worst case for a single-input cross lane shuffle which
9189 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9190 /// of. Special cases for each particular shuffle pattern should be handled
9191 /// prior to trying this lowering.
9192 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9193                                                        SDValue V1, SDValue V2,
9194                                                        ArrayRef<int> Mask,
9195                                                        SelectionDAG &DAG) {
9196   // FIXME: This should probably be generalized for 512-bit vectors as well.
9197   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9198   int LaneSize = Mask.size() / 2;
9199
9200   // If there are only inputs from one 128-bit lane, splitting will in fact be
9201   // less expensive. The flags track whether the given lane contains an element
9202   // that crosses to another lane.
9203   bool LaneCrossing[2] = {false, false};
9204   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9205     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9206       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9207   if (!LaneCrossing[0] || !LaneCrossing[1])
9208     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9209
9210   if (isSingleInputShuffleMask(Mask)) {
9211     SmallVector<int, 32> FlippedBlendMask;
9212     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9213       FlippedBlendMask.push_back(
9214           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9215                                   ? Mask[i]
9216                                   : Mask[i] % LaneSize +
9217                                         (i / LaneSize) * LaneSize + Size));
9218
9219     // Flip the vector, and blend the results which should now be in-lane. The
9220     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9221     // 5 for the high source. The value 3 selects the high half of source 2 and
9222     // the value 2 selects the low half of source 2. We only use source 2 to
9223     // allow folding it into a memory operand.
9224     unsigned PERMMask = 3 | 2 << 4;
9225     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9226                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9227     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9228   }
9229
9230   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9231   // will be handled by the above logic and a blend of the results, much like
9232   // other patterns in AVX.
9233   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9234 }
9235
9236 /// \brief Handle lowering 2-lane 128-bit shuffles.
9237 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9238                                         SDValue V2, ArrayRef<int> Mask,
9239                                         const X86Subtarget *Subtarget,
9240                                         SelectionDAG &DAG) {
9241   // TODO: If minimizing size and one of the inputs is a zero vector and the
9242   // the zero vector has only one use, we could use a VPERM2X128 to save the
9243   // instruction bytes needed to explicitly generate the zero vector.
9244
9245   // Blends are faster and handle all the non-lane-crossing cases.
9246   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9247                                                 Subtarget, DAG))
9248     return Blend;
9249
9250   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9251   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9252
9253   // If either input operand is a zero vector, use VPERM2X128 because its mask
9254   // allows us to replace the zero input with an implicit zero.
9255   if (!IsV1Zero && !IsV2Zero) {
9256     // Check for patterns which can be matched with a single insert of a 128-bit
9257     // subvector.
9258     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9259     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9260       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9261                                    VT.getVectorNumElements() / 2);
9262       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9263                                 DAG.getIntPtrConstant(0, DL));
9264       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9265                                 OnlyUsesV1 ? V1 : V2,
9266                                 DAG.getIntPtrConstant(0, DL));
9267       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9268     }
9269   }
9270
9271   // Otherwise form a 128-bit permutation. After accounting for undefs,
9272   // convert the 64-bit shuffle mask selection values into 128-bit
9273   // selection bits by dividing the indexes by 2 and shifting into positions
9274   // defined by a vperm2*128 instruction's immediate control byte.
9275
9276   // The immediate permute control byte looks like this:
9277   //    [1:0] - select 128 bits from sources for low half of destination
9278   //    [2]   - ignore
9279   //    [3]   - zero low half of destination
9280   //    [5:4] - select 128 bits from sources for high half of destination
9281   //    [6]   - ignore
9282   //    [7]   - zero high half of destination
9283
9284   int MaskLO = Mask[0];
9285   if (MaskLO == SM_SentinelUndef)
9286     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9287
9288   int MaskHI = Mask[2];
9289   if (MaskHI == SM_SentinelUndef)
9290     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9291
9292   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9293
9294   // If either input is a zero vector, replace it with an undef input.
9295   // Shuffle mask values <  4 are selecting elements of V1.
9296   // Shuffle mask values >= 4 are selecting elements of V2.
9297   // Adjust each half of the permute mask by clearing the half that was
9298   // selecting the zero vector and setting the zero mask bit.
9299   if (IsV1Zero) {
9300     V1 = DAG.getUNDEF(VT);
9301     if (MaskLO < 4)
9302       PermMask = (PermMask & 0xf0) | 0x08;
9303     if (MaskHI < 4)
9304       PermMask = (PermMask & 0x0f) | 0x80;
9305   }
9306   if (IsV2Zero) {
9307     V2 = DAG.getUNDEF(VT);
9308     if (MaskLO >= 4)
9309       PermMask = (PermMask & 0xf0) | 0x08;
9310     if (MaskHI >= 4)
9311       PermMask = (PermMask & 0x0f) | 0x80;
9312   }
9313
9314   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9315                      DAG.getConstant(PermMask, DL, MVT::i8));
9316 }
9317
9318 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9319 /// shuffling each lane.
9320 ///
9321 /// This will only succeed when the result of fixing the 128-bit lanes results
9322 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9323 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9324 /// the lane crosses early and then use simpler shuffles within each lane.
9325 ///
9326 /// FIXME: It might be worthwhile at some point to support this without
9327 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9328 /// in x86 only floating point has interesting non-repeating shuffles, and even
9329 /// those are still *marginally* more expensive.
9330 static SDValue lowerVectorShuffleByMerging128BitLanes(
9331     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9332     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9333   assert(!isSingleInputShuffleMask(Mask) &&
9334          "This is only useful with multiple inputs.");
9335
9336   int Size = Mask.size();
9337   int LaneSize = 128 / VT.getScalarSizeInBits();
9338   int NumLanes = Size / LaneSize;
9339   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9340
9341   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9342   // check whether the in-128-bit lane shuffles share a repeating pattern.
9343   SmallVector<int, 4> Lanes;
9344   Lanes.resize(NumLanes, -1);
9345   SmallVector<int, 4> InLaneMask;
9346   InLaneMask.resize(LaneSize, -1);
9347   for (int i = 0; i < Size; ++i) {
9348     if (Mask[i] < 0)
9349       continue;
9350
9351     int j = i / LaneSize;
9352
9353     if (Lanes[j] < 0) {
9354       // First entry we've seen for this lane.
9355       Lanes[j] = Mask[i] / LaneSize;
9356     } else if (Lanes[j] != Mask[i] / LaneSize) {
9357       // This doesn't match the lane selected previously!
9358       return SDValue();
9359     }
9360
9361     // Check that within each lane we have a consistent shuffle mask.
9362     int k = i % LaneSize;
9363     if (InLaneMask[k] < 0) {
9364       InLaneMask[k] = Mask[i] % LaneSize;
9365     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9366       // This doesn't fit a repeating in-lane mask.
9367       return SDValue();
9368     }
9369   }
9370
9371   // First shuffle the lanes into place.
9372   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9373                                 VT.getSizeInBits() / 64);
9374   SmallVector<int, 8> LaneMask;
9375   LaneMask.resize(NumLanes * 2, -1);
9376   for (int i = 0; i < NumLanes; ++i)
9377     if (Lanes[i] >= 0) {
9378       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9379       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9380     }
9381
9382   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9383   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9384   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9385
9386   // Cast it back to the type we actually want.
9387   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9388
9389   // Now do a simple shuffle that isn't lane crossing.
9390   SmallVector<int, 8> NewMask;
9391   NewMask.resize(Size, -1);
9392   for (int i = 0; i < Size; ++i)
9393     if (Mask[i] >= 0)
9394       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9395   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9396          "Must not introduce lane crosses at this point!");
9397
9398   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9399 }
9400
9401 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9402 /// given mask.
9403 ///
9404 /// This returns true if the elements from a particular input are already in the
9405 /// slot required by the given mask and require no permutation.
9406 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9407   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9408   int Size = Mask.size();
9409   for (int i = 0; i < Size; ++i)
9410     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9411       return false;
9412
9413   return true;
9414 }
9415
9416 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9417 ///
9418 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9419 /// isn't available.
9420 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9421                                        const X86Subtarget *Subtarget,
9422                                        SelectionDAG &DAG) {
9423   SDLoc DL(Op);
9424   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9425   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9426   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9427   ArrayRef<int> Mask = SVOp->getMask();
9428   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9429
9430   SmallVector<int, 4> WidenedMask;
9431   if (canWidenShuffleElements(Mask, WidenedMask))
9432     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9433                                     DAG);
9434
9435   if (isSingleInputShuffleMask(Mask)) {
9436     // Check for being able to broadcast a single element.
9437     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9438                                                           Mask, Subtarget, DAG))
9439       return Broadcast;
9440
9441     // Use low duplicate instructions for masks that match their pattern.
9442     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9443       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9444
9445     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9446       // Non-half-crossing single input shuffles can be lowerid with an
9447       // interleaved permutation.
9448       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9449                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9450       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9451                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9452     }
9453
9454     // With AVX2 we have direct support for this permutation.
9455     if (Subtarget->hasAVX2())
9456       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9457                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9458
9459     // Otherwise, fall back.
9460     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9461                                                    DAG);
9462   }
9463
9464   // X86 has dedicated unpack instructions that can handle specific blend
9465   // operations: UNPCKH and UNPCKL.
9466   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9467     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9468   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9469     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9470   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9471     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9472   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9473     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9474
9475   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9476                                                 Subtarget, DAG))
9477     return Blend;
9478
9479   // Check if the blend happens to exactly fit that of SHUFPD.
9480   if ((Mask[0] == -1 || Mask[0] < 2) &&
9481       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9482       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9483       (Mask[3] == -1 || Mask[3] >= 6)) {
9484     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9485                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9486     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9487                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9488   }
9489   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9490       (Mask[1] == -1 || Mask[1] < 2) &&
9491       (Mask[2] == -1 || Mask[2] >= 6) &&
9492       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9493     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9494                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9495     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9496                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9497   }
9498
9499   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9500   // shuffle. However, if we have AVX2 and either inputs are already in place,
9501   // we will be able to shuffle even across lanes the other input in a single
9502   // instruction so skip this pattern.
9503   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9504                                  isShuffleMaskInputInPlace(1, Mask))))
9505     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9506             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9507       return Result;
9508
9509   // If we have AVX2 then we always want to lower with a blend because an v4 we
9510   // can fully permute the elements.
9511   if (Subtarget->hasAVX2())
9512     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9513                                                       Mask, DAG);
9514
9515   // Otherwise fall back on generic lowering.
9516   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9517 }
9518
9519 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9520 ///
9521 /// This routine is only called when we have AVX2 and thus a reasonable
9522 /// instruction set for v4i64 shuffling..
9523 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9524                                        const X86Subtarget *Subtarget,
9525                                        SelectionDAG &DAG) {
9526   SDLoc DL(Op);
9527   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9528   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9529   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9530   ArrayRef<int> Mask = SVOp->getMask();
9531   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9532   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9533
9534   SmallVector<int, 4> WidenedMask;
9535   if (canWidenShuffleElements(Mask, WidenedMask))
9536     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9537                                     DAG);
9538
9539   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9540                                                 Subtarget, DAG))
9541     return Blend;
9542
9543   // Check for being able to broadcast a single element.
9544   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9545                                                         Mask, Subtarget, DAG))
9546     return Broadcast;
9547
9548   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9549   // use lower latency instructions that will operate on both 128-bit lanes.
9550   SmallVector<int, 2> RepeatedMask;
9551   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9552     if (isSingleInputShuffleMask(Mask)) {
9553       int PSHUFDMask[] = {-1, -1, -1, -1};
9554       for (int i = 0; i < 2; ++i)
9555         if (RepeatedMask[i] >= 0) {
9556           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9557           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9558         }
9559       return DAG.getNode(
9560           ISD::BITCAST, DL, MVT::v4i64,
9561           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9562                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9563                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9564     }
9565   }
9566
9567   // AVX2 provides a direct instruction for permuting a single input across
9568   // lanes.
9569   if (isSingleInputShuffleMask(Mask))
9570     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9571                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9572
9573   // Try to use shift instructions.
9574   if (SDValue Shift =
9575           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9576     return Shift;
9577
9578   // Use dedicated unpack instructions for masks that match their pattern.
9579   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9580     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9581   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9582     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9583   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9584     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9585   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9586     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9587
9588   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9589   // shuffle. However, if we have AVX2 and either inputs are already in place,
9590   // we will be able to shuffle even across lanes the other input in a single
9591   // instruction so skip this pattern.
9592   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9593                                  isShuffleMaskInputInPlace(1, Mask))))
9594     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9595             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9596       return Result;
9597
9598   // Otherwise fall back on generic blend lowering.
9599   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9600                                                     Mask, DAG);
9601 }
9602
9603 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9604 ///
9605 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9606 /// isn't available.
9607 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9608                                        const X86Subtarget *Subtarget,
9609                                        SelectionDAG &DAG) {
9610   SDLoc DL(Op);
9611   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9612   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9613   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9614   ArrayRef<int> Mask = SVOp->getMask();
9615   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9616
9617   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9618                                                 Subtarget, DAG))
9619     return Blend;
9620
9621   // Check for being able to broadcast a single element.
9622   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9623                                                         Mask, Subtarget, DAG))
9624     return Broadcast;
9625
9626   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9627   // options to efficiently lower the shuffle.
9628   SmallVector<int, 4> RepeatedMask;
9629   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9630     assert(RepeatedMask.size() == 4 &&
9631            "Repeated masks must be half the mask width!");
9632
9633     // Use even/odd duplicate instructions for masks that match their pattern.
9634     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9635       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9636     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9637       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9638
9639     if (isSingleInputShuffleMask(Mask))
9640       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9641                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9642
9643     // Use dedicated unpack instructions for masks that match their pattern.
9644     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9645       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9646     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9647       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9648     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9649       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9650     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9651       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9652
9653     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9654     // have already handled any direct blends. We also need to squash the
9655     // repeated mask into a simulated v4f32 mask.
9656     for (int i = 0; i < 4; ++i)
9657       if (RepeatedMask[i] >= 8)
9658         RepeatedMask[i] -= 4;
9659     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9660   }
9661
9662   // If we have a single input shuffle with different shuffle patterns in the
9663   // two 128-bit lanes use the variable mask to VPERMILPS.
9664   if (isSingleInputShuffleMask(Mask)) {
9665     SDValue VPermMask[8];
9666     for (int i = 0; i < 8; ++i)
9667       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9668                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9669     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9670       return DAG.getNode(
9671           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9672           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9673
9674     if (Subtarget->hasAVX2())
9675       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9676                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9677                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9678                                                  MVT::v8i32, VPermMask)),
9679                          V1);
9680
9681     // Otherwise, fall back.
9682     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9683                                                    DAG);
9684   }
9685
9686   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9687   // shuffle.
9688   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9689           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9690     return Result;
9691
9692   // If we have AVX2 then we always want to lower with a blend because at v8 we
9693   // can fully permute the elements.
9694   if (Subtarget->hasAVX2())
9695     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9696                                                       Mask, DAG);
9697
9698   // Otherwise fall back on generic lowering.
9699   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9700 }
9701
9702 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9703 ///
9704 /// This routine is only called when we have AVX2 and thus a reasonable
9705 /// instruction set for v8i32 shuffling..
9706 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9707                                        const X86Subtarget *Subtarget,
9708                                        SelectionDAG &DAG) {
9709   SDLoc DL(Op);
9710   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9711   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9712   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9713   ArrayRef<int> Mask = SVOp->getMask();
9714   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9715   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9716
9717   // Whenever we can lower this as a zext, that instruction is strictly faster
9718   // than any alternative. It also allows us to fold memory operands into the
9719   // shuffle in many cases.
9720   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9721                                                          Mask, Subtarget, DAG))
9722     return ZExt;
9723
9724   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9725                                                 Subtarget, DAG))
9726     return Blend;
9727
9728   // Check for being able to broadcast a single element.
9729   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9730                                                         Mask, Subtarget, DAG))
9731     return Broadcast;
9732
9733   // If the shuffle mask is repeated in each 128-bit lane we can use more
9734   // efficient instructions that mirror the shuffles across the two 128-bit
9735   // lanes.
9736   SmallVector<int, 4> RepeatedMask;
9737   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9738     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9739     if (isSingleInputShuffleMask(Mask))
9740       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9741                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9742
9743     // Use dedicated unpack instructions for masks that match their pattern.
9744     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9745       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9746     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9747       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9748     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9749       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9750     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9751       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9752   }
9753
9754   // Try to use shift instructions.
9755   if (SDValue Shift =
9756           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9757     return Shift;
9758
9759   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9760           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9761     return Rotate;
9762
9763   // If the shuffle patterns aren't repeated but it is a single input, directly
9764   // generate a cross-lane VPERMD instruction.
9765   if (isSingleInputShuffleMask(Mask)) {
9766     SDValue VPermMask[8];
9767     for (int i = 0; i < 8; ++i)
9768       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9769                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9770     return DAG.getNode(
9771         X86ISD::VPERMV, DL, MVT::v8i32,
9772         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9773   }
9774
9775   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9776   // shuffle.
9777   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9778           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9779     return Result;
9780
9781   // Otherwise fall back on generic blend lowering.
9782   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9783                                                     Mask, DAG);
9784 }
9785
9786 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9787 ///
9788 /// This routine is only called when we have AVX2 and thus a reasonable
9789 /// instruction set for v16i16 shuffling..
9790 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9791                                         const X86Subtarget *Subtarget,
9792                                         SelectionDAG &DAG) {
9793   SDLoc DL(Op);
9794   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9795   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9796   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9797   ArrayRef<int> Mask = SVOp->getMask();
9798   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9799   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9800
9801   // Whenever we can lower this as a zext, that instruction is strictly faster
9802   // than any alternative. It also allows us to fold memory operands into the
9803   // shuffle in many cases.
9804   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9805                                                          Mask, Subtarget, DAG))
9806     return ZExt;
9807
9808   // Check for being able to broadcast a single element.
9809   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9810                                                         Mask, Subtarget, DAG))
9811     return Broadcast;
9812
9813   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9814                                                 Subtarget, DAG))
9815     return Blend;
9816
9817   // Use dedicated unpack instructions for masks that match their pattern.
9818   if (isShuffleEquivalent(V1, V2, Mask,
9819                           {// First 128-bit lane:
9820                            0, 16, 1, 17, 2, 18, 3, 19,
9821                            // Second 128-bit lane:
9822                            8, 24, 9, 25, 10, 26, 11, 27}))
9823     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9824   if (isShuffleEquivalent(V1, V2, Mask,
9825                           {// First 128-bit lane:
9826                            4, 20, 5, 21, 6, 22, 7, 23,
9827                            // Second 128-bit lane:
9828                            12, 28, 13, 29, 14, 30, 15, 31}))
9829     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9830
9831   // Try to use shift instructions.
9832   if (SDValue Shift =
9833           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9834     return Shift;
9835
9836   // Try to use byte rotation instructions.
9837   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9838           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9839     return Rotate;
9840
9841   if (isSingleInputShuffleMask(Mask)) {
9842     // There are no generalized cross-lane shuffle operations available on i16
9843     // element types.
9844     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9845       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9846                                                      Mask, DAG);
9847
9848     SmallVector<int, 8> RepeatedMask;
9849     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9850       // As this is a single-input shuffle, the repeated mask should be
9851       // a strictly valid v8i16 mask that we can pass through to the v8i16
9852       // lowering to handle even the v16 case.
9853       return lowerV8I16GeneralSingleInputVectorShuffle(
9854           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9855     }
9856
9857     SDValue PSHUFBMask[32];
9858     for (int i = 0; i < 16; ++i) {
9859       if (Mask[i] == -1) {
9860         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9861         continue;
9862       }
9863
9864       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9865       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9866       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9867       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9868     }
9869     return DAG.getNode(
9870         ISD::BITCAST, DL, MVT::v16i16,
9871         DAG.getNode(
9872             X86ISD::PSHUFB, DL, MVT::v32i8,
9873             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9874             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9875   }
9876
9877   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9878   // shuffle.
9879   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9880           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9881     return Result;
9882
9883   // Otherwise fall back on generic lowering.
9884   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9885 }
9886
9887 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9888 ///
9889 /// This routine is only called when we have AVX2 and thus a reasonable
9890 /// instruction set for v32i8 shuffling..
9891 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9892                                        const X86Subtarget *Subtarget,
9893                                        SelectionDAG &DAG) {
9894   SDLoc DL(Op);
9895   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9896   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9897   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9898   ArrayRef<int> Mask = SVOp->getMask();
9899   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9900   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9901
9902   // Whenever we can lower this as a zext, that instruction is strictly faster
9903   // than any alternative. It also allows us to fold memory operands into the
9904   // shuffle in many cases.
9905   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9906                                                          Mask, Subtarget, DAG))
9907     return ZExt;
9908
9909   // Check for being able to broadcast a single element.
9910   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9911                                                         Mask, Subtarget, DAG))
9912     return Broadcast;
9913
9914   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9915                                                 Subtarget, DAG))
9916     return Blend;
9917
9918   // Use dedicated unpack instructions for masks that match their pattern.
9919   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9920   // 256-bit lanes.
9921   if (isShuffleEquivalent(
9922           V1, V2, Mask,
9923           {// First 128-bit lane:
9924            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9925            // Second 128-bit lane:
9926            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9927     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9928   if (isShuffleEquivalent(
9929           V1, V2, Mask,
9930           {// First 128-bit lane:
9931            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9932            // Second 128-bit lane:
9933            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9934     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9935
9936   // Try to use shift instructions.
9937   if (SDValue Shift =
9938           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9939     return Shift;
9940
9941   // Try to use byte rotation instructions.
9942   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9943           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9944     return Rotate;
9945
9946   if (isSingleInputShuffleMask(Mask)) {
9947     // There are no generalized cross-lane shuffle operations available on i8
9948     // element types.
9949     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9950       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9951                                                      Mask, DAG);
9952
9953     SDValue PSHUFBMask[32];
9954     for (int i = 0; i < 32; ++i)
9955       PSHUFBMask[i] =
9956           Mask[i] < 0
9957               ? DAG.getUNDEF(MVT::i8)
9958               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9959                                 MVT::i8);
9960
9961     return DAG.getNode(
9962         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9963         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9964   }
9965
9966   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9967   // shuffle.
9968   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9969           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9970     return Result;
9971
9972   // Otherwise fall back on generic lowering.
9973   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9974 }
9975
9976 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9977 ///
9978 /// This routine either breaks down the specific type of a 256-bit x86 vector
9979 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9980 /// together based on the available instructions.
9981 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9982                                         MVT VT, const X86Subtarget *Subtarget,
9983                                         SelectionDAG &DAG) {
9984   SDLoc DL(Op);
9985   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9986   ArrayRef<int> Mask = SVOp->getMask();
9987
9988   // If we have a single input to the zero element, insert that into V1 if we
9989   // can do so cheaply.
9990   int NumElts = VT.getVectorNumElements();
9991   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9992     return M >= NumElts;
9993   });
9994
9995   if (NumV2Elements == 1 && Mask[0] >= NumElts)
9996     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9997                               DL, VT, V1, V2, Mask, Subtarget, DAG))
9998       return Insertion;
9999
10000   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10001   // check for those subtargets here and avoid much of the subtarget querying in
10002   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10003   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10004   // floating point types there eventually, just immediately cast everything to
10005   // a float and operate entirely in that domain.
10006   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10007     int ElementBits = VT.getScalarSizeInBits();
10008     if (ElementBits < 32)
10009       // No floating point type available, decompose into 128-bit vectors.
10010       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10011
10012     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10013                                 VT.getVectorNumElements());
10014     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10015     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10016     return DAG.getNode(ISD::BITCAST, DL, VT,
10017                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10018   }
10019
10020   switch (VT.SimpleTy) {
10021   case MVT::v4f64:
10022     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10023   case MVT::v4i64:
10024     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10025   case MVT::v8f32:
10026     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10027   case MVT::v8i32:
10028     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10029   case MVT::v16i16:
10030     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10031   case MVT::v32i8:
10032     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10033
10034   default:
10035     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10036   }
10037 }
10038
10039 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10040 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10041                                        const X86Subtarget *Subtarget,
10042                                        SelectionDAG &DAG) {
10043   SDLoc DL(Op);
10044   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10045   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10046   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10047   ArrayRef<int> Mask = SVOp->getMask();
10048   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10049
10050   // X86 has dedicated unpack instructions that can handle specific blend
10051   // operations: UNPCKH and UNPCKL.
10052   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10053     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10054   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10055     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10056
10057   // FIXME: Implement direct support for this type!
10058   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10059 }
10060
10061 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10062 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10063                                        const X86Subtarget *Subtarget,
10064                                        SelectionDAG &DAG) {
10065   SDLoc DL(Op);
10066   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10067   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10068   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10069   ArrayRef<int> Mask = SVOp->getMask();
10070   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10071
10072   // Use dedicated unpack instructions for masks that match their pattern.
10073   if (isShuffleEquivalent(V1, V2, Mask,
10074                           {// First 128-bit lane.
10075                            0, 16, 1, 17, 4, 20, 5, 21,
10076                            // Second 128-bit lane.
10077                            8, 24, 9, 25, 12, 28, 13, 29}))
10078     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10079   if (isShuffleEquivalent(V1, V2, Mask,
10080                           {// First 128-bit lane.
10081                            2, 18, 3, 19, 6, 22, 7, 23,
10082                            // Second 128-bit lane.
10083                            10, 26, 11, 27, 14, 30, 15, 31}))
10084     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10085
10086   // FIXME: Implement direct support for this type!
10087   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10088 }
10089
10090 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10091 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10092                                        const X86Subtarget *Subtarget,
10093                                        SelectionDAG &DAG) {
10094   SDLoc DL(Op);
10095   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10096   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10097   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10098   ArrayRef<int> Mask = SVOp->getMask();
10099   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10100
10101   // X86 has dedicated unpack instructions that can handle specific blend
10102   // operations: UNPCKH and UNPCKL.
10103   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10104     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10105   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10106     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10107
10108   // FIXME: Implement direct support for this type!
10109   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10110 }
10111
10112 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10113 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10114                                        const X86Subtarget *Subtarget,
10115                                        SelectionDAG &DAG) {
10116   SDLoc DL(Op);
10117   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10118   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10119   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10120   ArrayRef<int> Mask = SVOp->getMask();
10121   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10122
10123   // Use dedicated unpack instructions for masks that match their pattern.
10124   if (isShuffleEquivalent(V1, V2, Mask,
10125                           {// First 128-bit lane.
10126                            0, 16, 1, 17, 4, 20, 5, 21,
10127                            // Second 128-bit lane.
10128                            8, 24, 9, 25, 12, 28, 13, 29}))
10129     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10130   if (isShuffleEquivalent(V1, V2, Mask,
10131                           {// First 128-bit lane.
10132                            2, 18, 3, 19, 6, 22, 7, 23,
10133                            // Second 128-bit lane.
10134                            10, 26, 11, 27, 14, 30, 15, 31}))
10135     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10136
10137   // FIXME: Implement direct support for this type!
10138   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10139 }
10140
10141 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10142 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10143                                         const X86Subtarget *Subtarget,
10144                                         SelectionDAG &DAG) {
10145   SDLoc DL(Op);
10146   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10147   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10148   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10149   ArrayRef<int> Mask = SVOp->getMask();
10150   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10151   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10152
10153   // FIXME: Implement direct support for this type!
10154   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10155 }
10156
10157 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10158 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10159                                        const X86Subtarget *Subtarget,
10160                                        SelectionDAG &DAG) {
10161   SDLoc DL(Op);
10162   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10163   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10164   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10165   ArrayRef<int> Mask = SVOp->getMask();
10166   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10167   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10168
10169   // FIXME: Implement direct support for this type!
10170   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10171 }
10172
10173 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10174 ///
10175 /// This routine either breaks down the specific type of a 512-bit x86 vector
10176 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10177 /// together based on the available instructions.
10178 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10179                                         MVT VT, const X86Subtarget *Subtarget,
10180                                         SelectionDAG &DAG) {
10181   SDLoc DL(Op);
10182   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10183   ArrayRef<int> Mask = SVOp->getMask();
10184   assert(Subtarget->hasAVX512() &&
10185          "Cannot lower 512-bit vectors w/ basic ISA!");
10186
10187   // Check for being able to broadcast a single element.
10188   if (SDValue Broadcast =
10189           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10190     return Broadcast;
10191
10192   // Dispatch to each element type for lowering. If we don't have supprot for
10193   // specific element type shuffles at 512 bits, immediately split them and
10194   // lower them. Each lowering routine of a given type is allowed to assume that
10195   // the requisite ISA extensions for that element type are available.
10196   switch (VT.SimpleTy) {
10197   case MVT::v8f64:
10198     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10199   case MVT::v16f32:
10200     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10201   case MVT::v8i64:
10202     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10203   case MVT::v16i32:
10204     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10205   case MVT::v32i16:
10206     if (Subtarget->hasBWI())
10207       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10208     break;
10209   case MVT::v64i8:
10210     if (Subtarget->hasBWI())
10211       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10212     break;
10213
10214   default:
10215     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10216   }
10217
10218   // Otherwise fall back on splitting.
10219   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10220 }
10221
10222 /// \brief Top-level lowering for x86 vector shuffles.
10223 ///
10224 /// This handles decomposition, canonicalization, and lowering of all x86
10225 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10226 /// above in helper routines. The canonicalization attempts to widen shuffles
10227 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10228 /// s.t. only one of the two inputs needs to be tested, etc.
10229 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10230                                   SelectionDAG &DAG) {
10231   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10232   ArrayRef<int> Mask = SVOp->getMask();
10233   SDValue V1 = Op.getOperand(0);
10234   SDValue V2 = Op.getOperand(1);
10235   MVT VT = Op.getSimpleValueType();
10236   int NumElements = VT.getVectorNumElements();
10237   SDLoc dl(Op);
10238
10239   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10240
10241   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10242   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10243   if (V1IsUndef && V2IsUndef)
10244     return DAG.getUNDEF(VT);
10245
10246   // When we create a shuffle node we put the UNDEF node to second operand,
10247   // but in some cases the first operand may be transformed to UNDEF.
10248   // In this case we should just commute the node.
10249   if (V1IsUndef)
10250     return DAG.getCommutedVectorShuffle(*SVOp);
10251
10252   // Check for non-undef masks pointing at an undef vector and make the masks
10253   // undef as well. This makes it easier to match the shuffle based solely on
10254   // the mask.
10255   if (V2IsUndef)
10256     for (int M : Mask)
10257       if (M >= NumElements) {
10258         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10259         for (int &M : NewMask)
10260           if (M >= NumElements)
10261             M = -1;
10262         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10263       }
10264
10265   // We actually see shuffles that are entirely re-arrangements of a set of
10266   // zero inputs. This mostly happens while decomposing complex shuffles into
10267   // simple ones. Directly lower these as a buildvector of zeros.
10268   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10269   if (Zeroable.all())
10270     return getZeroVector(VT, Subtarget, DAG, dl);
10271
10272   // Try to collapse shuffles into using a vector type with fewer elements but
10273   // wider element types. We cap this to not form integers or floating point
10274   // elements wider than 64 bits, but it might be interesting to form i128
10275   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10276   SmallVector<int, 16> WidenedMask;
10277   if (VT.getScalarSizeInBits() < 64 &&
10278       canWidenShuffleElements(Mask, WidenedMask)) {
10279     MVT NewEltVT = VT.isFloatingPoint()
10280                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10281                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10282     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10283     // Make sure that the new vector type is legal. For example, v2f64 isn't
10284     // legal on SSE1.
10285     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10286       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10287       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10288       return DAG.getNode(ISD::BITCAST, dl, VT,
10289                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10290     }
10291   }
10292
10293   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10294   for (int M : SVOp->getMask())
10295     if (M < 0)
10296       ++NumUndefElements;
10297     else if (M < NumElements)
10298       ++NumV1Elements;
10299     else
10300       ++NumV2Elements;
10301
10302   // Commute the shuffle as needed such that more elements come from V1 than
10303   // V2. This allows us to match the shuffle pattern strictly on how many
10304   // elements come from V1 without handling the symmetric cases.
10305   if (NumV2Elements > NumV1Elements)
10306     return DAG.getCommutedVectorShuffle(*SVOp);
10307
10308   // When the number of V1 and V2 elements are the same, try to minimize the
10309   // number of uses of V2 in the low half of the vector. When that is tied,
10310   // ensure that the sum of indices for V1 is equal to or lower than the sum
10311   // indices for V2. When those are equal, try to ensure that the number of odd
10312   // indices for V1 is lower than the number of odd indices for V2.
10313   if (NumV1Elements == NumV2Elements) {
10314     int LowV1Elements = 0, LowV2Elements = 0;
10315     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10316       if (M >= NumElements)
10317         ++LowV2Elements;
10318       else if (M >= 0)
10319         ++LowV1Elements;
10320     if (LowV2Elements > LowV1Elements) {
10321       return DAG.getCommutedVectorShuffle(*SVOp);
10322     } else if (LowV2Elements == LowV1Elements) {
10323       int SumV1Indices = 0, SumV2Indices = 0;
10324       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10325         if (SVOp->getMask()[i] >= NumElements)
10326           SumV2Indices += i;
10327         else if (SVOp->getMask()[i] >= 0)
10328           SumV1Indices += i;
10329       if (SumV2Indices < SumV1Indices) {
10330         return DAG.getCommutedVectorShuffle(*SVOp);
10331       } else if (SumV2Indices == SumV1Indices) {
10332         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10333         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10334           if (SVOp->getMask()[i] >= NumElements)
10335             NumV2OddIndices += i % 2;
10336           else if (SVOp->getMask()[i] >= 0)
10337             NumV1OddIndices += i % 2;
10338         if (NumV2OddIndices < NumV1OddIndices)
10339           return DAG.getCommutedVectorShuffle(*SVOp);
10340       }
10341     }
10342   }
10343
10344   // For each vector width, delegate to a specialized lowering routine.
10345   if (VT.getSizeInBits() == 128)
10346     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10347
10348   if (VT.getSizeInBits() == 256)
10349     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10350
10351   // Force AVX-512 vectors to be scalarized for now.
10352   // FIXME: Implement AVX-512 support!
10353   if (VT.getSizeInBits() == 512)
10354     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10355
10356   llvm_unreachable("Unimplemented!");
10357 }
10358
10359 // This function assumes its argument is a BUILD_VECTOR of constants or
10360 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10361 // true.
10362 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10363                                     unsigned &MaskValue) {
10364   MaskValue = 0;
10365   unsigned NumElems = BuildVector->getNumOperands();
10366   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10367   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10368   unsigned NumElemsInLane = NumElems / NumLanes;
10369
10370   // Blend for v16i16 should be symetric for the both lanes.
10371   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10372     SDValue EltCond = BuildVector->getOperand(i);
10373     SDValue SndLaneEltCond =
10374         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10375
10376     int Lane1Cond = -1, Lane2Cond = -1;
10377     if (isa<ConstantSDNode>(EltCond))
10378       Lane1Cond = !isZero(EltCond);
10379     if (isa<ConstantSDNode>(SndLaneEltCond))
10380       Lane2Cond = !isZero(SndLaneEltCond);
10381
10382     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10383       // Lane1Cond != 0, means we want the first argument.
10384       // Lane1Cond == 0, means we want the second argument.
10385       // The encoding of this argument is 0 for the first argument, 1
10386       // for the second. Therefore, invert the condition.
10387       MaskValue |= !Lane1Cond << i;
10388     else if (Lane1Cond < 0)
10389       MaskValue |= !Lane2Cond << i;
10390     else
10391       return false;
10392   }
10393   return true;
10394 }
10395
10396 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10397 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10398                                            const X86Subtarget *Subtarget,
10399                                            SelectionDAG &DAG) {
10400   SDValue Cond = Op.getOperand(0);
10401   SDValue LHS = Op.getOperand(1);
10402   SDValue RHS = Op.getOperand(2);
10403   SDLoc dl(Op);
10404   MVT VT = Op.getSimpleValueType();
10405
10406   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10407     return SDValue();
10408   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10409
10410   // Only non-legal VSELECTs reach this lowering, convert those into generic
10411   // shuffles and re-use the shuffle lowering path for blends.
10412   SmallVector<int, 32> Mask;
10413   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10414     SDValue CondElt = CondBV->getOperand(i);
10415     Mask.push_back(
10416         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10417   }
10418   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10419 }
10420
10421 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10422   // A vselect where all conditions and data are constants can be optimized into
10423   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10424   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10425       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10426       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10427     return SDValue();
10428
10429   // Try to lower this to a blend-style vector shuffle. This can handle all
10430   // constant condition cases.
10431   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10432     return BlendOp;
10433
10434   // Variable blends are only legal from SSE4.1 onward.
10435   if (!Subtarget->hasSSE41())
10436     return SDValue();
10437
10438   // Only some types will be legal on some subtargets. If we can emit a legal
10439   // VSELECT-matching blend, return Op, and but if we need to expand, return
10440   // a null value.
10441   switch (Op.getSimpleValueType().SimpleTy) {
10442   default:
10443     // Most of the vector types have blends past SSE4.1.
10444     return Op;
10445
10446   case MVT::v32i8:
10447     // The byte blends for AVX vectors were introduced only in AVX2.
10448     if (Subtarget->hasAVX2())
10449       return Op;
10450
10451     return SDValue();
10452
10453   case MVT::v8i16:
10454   case MVT::v16i16:
10455     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10456     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10457       return Op;
10458
10459     // FIXME: We should custom lower this by fixing the condition and using i8
10460     // blends.
10461     return SDValue();
10462   }
10463 }
10464
10465 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10466   MVT VT = Op.getSimpleValueType();
10467   SDLoc dl(Op);
10468
10469   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10470     return SDValue();
10471
10472   if (VT.getSizeInBits() == 8) {
10473     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10474                                   Op.getOperand(0), Op.getOperand(1));
10475     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10476                                   DAG.getValueType(VT));
10477     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10478   }
10479
10480   if (VT.getSizeInBits() == 16) {
10481     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10482     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10483     if (Idx == 0)
10484       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10485                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10486                                      DAG.getNode(ISD::BITCAST, dl,
10487                                                  MVT::v4i32,
10488                                                  Op.getOperand(0)),
10489                                      Op.getOperand(1)));
10490     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10491                                   Op.getOperand(0), Op.getOperand(1));
10492     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10493                                   DAG.getValueType(VT));
10494     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10495   }
10496
10497   if (VT == MVT::f32) {
10498     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10499     // the result back to FR32 register. It's only worth matching if the
10500     // result has a single use which is a store or a bitcast to i32.  And in
10501     // the case of a store, it's not worth it if the index is a constant 0,
10502     // because a MOVSSmr can be used instead, which is smaller and faster.
10503     if (!Op.hasOneUse())
10504       return SDValue();
10505     SDNode *User = *Op.getNode()->use_begin();
10506     if ((User->getOpcode() != ISD::STORE ||
10507          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10508           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10509         (User->getOpcode() != ISD::BITCAST ||
10510          User->getValueType(0) != MVT::i32))
10511       return SDValue();
10512     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10513                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10514                                               Op.getOperand(0)),
10515                                               Op.getOperand(1));
10516     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10517   }
10518
10519   if (VT == MVT::i32 || VT == MVT::i64) {
10520     // ExtractPS/pextrq works with constant index.
10521     if (isa<ConstantSDNode>(Op.getOperand(1)))
10522       return Op;
10523   }
10524   return SDValue();
10525 }
10526
10527 /// Extract one bit from mask vector, like v16i1 or v8i1.
10528 /// AVX-512 feature.
10529 SDValue
10530 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10531   SDValue Vec = Op.getOperand(0);
10532   SDLoc dl(Vec);
10533   MVT VecVT = Vec.getSimpleValueType();
10534   SDValue Idx = Op.getOperand(1);
10535   MVT EltVT = Op.getSimpleValueType();
10536
10537   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10538   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10539          "Unexpected vector type in ExtractBitFromMaskVector");
10540
10541   // variable index can't be handled in mask registers,
10542   // extend vector to VR512
10543   if (!isa<ConstantSDNode>(Idx)) {
10544     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10545     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10546     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10547                               ExtVT.getVectorElementType(), Ext, Idx);
10548     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10549   }
10550
10551   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10552   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10553   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10554     rc = getRegClassFor(MVT::v16i1);
10555   unsigned MaxSift = rc->getSize()*8 - 1;
10556   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10557                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10558   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10559                     DAG.getConstant(MaxSift, dl, MVT::i8));
10560   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10561                        DAG.getIntPtrConstant(0, dl));
10562 }
10563
10564 SDValue
10565 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10566                                            SelectionDAG &DAG) const {
10567   SDLoc dl(Op);
10568   SDValue Vec = Op.getOperand(0);
10569   MVT VecVT = Vec.getSimpleValueType();
10570   SDValue Idx = Op.getOperand(1);
10571
10572   if (Op.getSimpleValueType() == MVT::i1)
10573     return ExtractBitFromMaskVector(Op, DAG);
10574
10575   if (!isa<ConstantSDNode>(Idx)) {
10576     if (VecVT.is512BitVector() ||
10577         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10578          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10579
10580       MVT MaskEltVT =
10581         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10582       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10583                                     MaskEltVT.getSizeInBits());
10584
10585       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10586       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10587                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10588                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10589       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10590       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10591                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10592     }
10593     return SDValue();
10594   }
10595
10596   // If this is a 256-bit vector result, first extract the 128-bit vector and
10597   // then extract the element from the 128-bit vector.
10598   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10599
10600     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10601     // Get the 128-bit vector.
10602     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10603     MVT EltVT = VecVT.getVectorElementType();
10604
10605     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10606
10607     //if (IdxVal >= NumElems/2)
10608     //  IdxVal -= NumElems/2;
10609     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10610     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10611                        DAG.getConstant(IdxVal, dl, MVT::i32));
10612   }
10613
10614   assert(VecVT.is128BitVector() && "Unexpected vector length");
10615
10616   if (Subtarget->hasSSE41()) {
10617     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10618     if (Res.getNode())
10619       return Res;
10620   }
10621
10622   MVT VT = Op.getSimpleValueType();
10623   // TODO: handle v16i8.
10624   if (VT.getSizeInBits() == 16) {
10625     SDValue Vec = Op.getOperand(0);
10626     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10627     if (Idx == 0)
10628       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10629                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10630                                      DAG.getNode(ISD::BITCAST, dl,
10631                                                  MVT::v4i32, Vec),
10632                                      Op.getOperand(1)));
10633     // Transform it so it match pextrw which produces a 32-bit result.
10634     MVT EltVT = MVT::i32;
10635     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10636                                   Op.getOperand(0), Op.getOperand(1));
10637     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10638                                   DAG.getValueType(VT));
10639     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10640   }
10641
10642   if (VT.getSizeInBits() == 32) {
10643     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10644     if (Idx == 0)
10645       return Op;
10646
10647     // SHUFPS the element to the lowest double word, then movss.
10648     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10649     MVT VVT = Op.getOperand(0).getSimpleValueType();
10650     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10651                                        DAG.getUNDEF(VVT), Mask);
10652     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10653                        DAG.getIntPtrConstant(0, dl));
10654   }
10655
10656   if (VT.getSizeInBits() == 64) {
10657     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10658     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10659     //        to match extract_elt for f64.
10660     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10661     if (Idx == 0)
10662       return Op;
10663
10664     // UNPCKHPD the element to the lowest double word, then movsd.
10665     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10666     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10667     int Mask[2] = { 1, -1 };
10668     MVT VVT = Op.getOperand(0).getSimpleValueType();
10669     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10670                                        DAG.getUNDEF(VVT), Mask);
10671     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10672                        DAG.getIntPtrConstant(0, dl));
10673   }
10674
10675   return SDValue();
10676 }
10677
10678 /// Insert one bit to mask vector, like v16i1 or v8i1.
10679 /// AVX-512 feature.
10680 SDValue
10681 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10682   SDLoc dl(Op);
10683   SDValue Vec = Op.getOperand(0);
10684   SDValue Elt = Op.getOperand(1);
10685   SDValue Idx = Op.getOperand(2);
10686   MVT VecVT = Vec.getSimpleValueType();
10687
10688   if (!isa<ConstantSDNode>(Idx)) {
10689     // Non constant index. Extend source and destination,
10690     // insert element and then truncate the result.
10691     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10692     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10693     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10694       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10695       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10696     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10697   }
10698
10699   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10700   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10701   if (IdxVal)
10702     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10703                            DAG.getConstant(IdxVal, dl, MVT::i8));
10704   if (Vec.getOpcode() == ISD::UNDEF)
10705     return EltInVec;
10706   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10707 }
10708
10709 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10710                                                   SelectionDAG &DAG) const {
10711   MVT VT = Op.getSimpleValueType();
10712   MVT EltVT = VT.getVectorElementType();
10713
10714   if (EltVT == MVT::i1)
10715     return InsertBitToMaskVector(Op, DAG);
10716
10717   SDLoc dl(Op);
10718   SDValue N0 = Op.getOperand(0);
10719   SDValue N1 = Op.getOperand(1);
10720   SDValue N2 = Op.getOperand(2);
10721   if (!isa<ConstantSDNode>(N2))
10722     return SDValue();
10723   auto *N2C = cast<ConstantSDNode>(N2);
10724   unsigned IdxVal = N2C->getZExtValue();
10725
10726   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10727   // into that, and then insert the subvector back into the result.
10728   if (VT.is256BitVector() || VT.is512BitVector()) {
10729     // With a 256-bit vector, we can insert into the zero element efficiently
10730     // using a blend if we have AVX or AVX2 and the right data type.
10731     if (VT.is256BitVector() && IdxVal == 0) {
10732       // TODO: It is worthwhile to cast integer to floating point and back
10733       // and incur a domain crossing penalty if that's what we'll end up
10734       // doing anyway after extracting to a 128-bit vector.
10735       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10736           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10737         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10738         N2 = DAG.getIntPtrConstant(1, dl);
10739         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10740       }
10741     }
10742
10743     // Get the desired 128-bit vector chunk.
10744     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10745
10746     // Insert the element into the desired chunk.
10747     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10748     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10749
10750     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10751                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10752
10753     // Insert the changed part back into the bigger vector
10754     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10755   }
10756   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10757
10758   if (Subtarget->hasSSE41()) {
10759     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10760       unsigned Opc;
10761       if (VT == MVT::v8i16) {
10762         Opc = X86ISD::PINSRW;
10763       } else {
10764         assert(VT == MVT::v16i8);
10765         Opc = X86ISD::PINSRB;
10766       }
10767
10768       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10769       // argument.
10770       if (N1.getValueType() != MVT::i32)
10771         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10772       if (N2.getValueType() != MVT::i32)
10773         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10774       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10775     }
10776
10777     if (EltVT == MVT::f32) {
10778       // Bits [7:6] of the constant are the source select. This will always be
10779       //   zero here. The DAG Combiner may combine an extract_elt index into
10780       //   these bits. For example (insert (extract, 3), 2) could be matched by
10781       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10782       // Bits [5:4] of the constant are the destination select. This is the
10783       //   value of the incoming immediate.
10784       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10785       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10786
10787       const Function *F = DAG.getMachineFunction().getFunction();
10788       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10789       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10790         // If this is an insertion of 32-bits into the low 32-bits of
10791         // a vector, we prefer to generate a blend with immediate rather
10792         // than an insertps. Blends are simpler operations in hardware and so
10793         // will always have equal or better performance than insertps.
10794         // But if optimizing for size and there's a load folding opportunity,
10795         // generate insertps because blendps does not have a 32-bit memory
10796         // operand form.
10797         N2 = DAG.getIntPtrConstant(1, dl);
10798         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10799         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10800       }
10801       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10802       // Create this as a scalar to vector..
10803       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10804       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10805     }
10806
10807     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10808       // PINSR* works with constant index.
10809       return Op;
10810     }
10811   }
10812
10813   if (EltVT == MVT::i8)
10814     return SDValue();
10815
10816   if (EltVT.getSizeInBits() == 16) {
10817     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10818     // as its second argument.
10819     if (N1.getValueType() != MVT::i32)
10820       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10821     if (N2.getValueType() != MVT::i32)
10822       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10823     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10824   }
10825   return SDValue();
10826 }
10827
10828 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10829   SDLoc dl(Op);
10830   MVT OpVT = Op.getSimpleValueType();
10831
10832   // If this is a 256-bit vector result, first insert into a 128-bit
10833   // vector and then insert into the 256-bit vector.
10834   if (!OpVT.is128BitVector()) {
10835     // Insert into a 128-bit vector.
10836     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10837     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10838                                  OpVT.getVectorNumElements() / SizeFactor);
10839
10840     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10841
10842     // Insert the 128-bit vector.
10843     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10844   }
10845
10846   if (OpVT == MVT::v1i64 &&
10847       Op.getOperand(0).getValueType() == MVT::i64)
10848     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10849
10850   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10851   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10852   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10853                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10854 }
10855
10856 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10857 // a simple subregister reference or explicit instructions to grab
10858 // upper bits of a vector.
10859 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10860                                       SelectionDAG &DAG) {
10861   SDLoc dl(Op);
10862   SDValue In =  Op.getOperand(0);
10863   SDValue Idx = Op.getOperand(1);
10864   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10865   MVT ResVT   = Op.getSimpleValueType();
10866   MVT InVT    = In.getSimpleValueType();
10867
10868   if (Subtarget->hasFp256()) {
10869     if (ResVT.is128BitVector() &&
10870         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10871         isa<ConstantSDNode>(Idx)) {
10872       return Extract128BitVector(In, IdxVal, DAG, dl);
10873     }
10874     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10875         isa<ConstantSDNode>(Idx)) {
10876       return Extract256BitVector(In, IdxVal, DAG, dl);
10877     }
10878   }
10879   return SDValue();
10880 }
10881
10882 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10883 // simple superregister reference or explicit instructions to insert
10884 // the upper bits of a vector.
10885 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10886                                      SelectionDAG &DAG) {
10887   if (!Subtarget->hasAVX())
10888     return SDValue();
10889
10890   SDLoc dl(Op);
10891   SDValue Vec = Op.getOperand(0);
10892   SDValue SubVec = Op.getOperand(1);
10893   SDValue Idx = Op.getOperand(2);
10894
10895   if (!isa<ConstantSDNode>(Idx))
10896     return SDValue();
10897
10898   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10899   MVT OpVT = Op.getSimpleValueType();
10900   MVT SubVecVT = SubVec.getSimpleValueType();
10901
10902   // Fold two 16-byte subvector loads into one 32-byte load:
10903   // (insert_subvector (insert_subvector undef, (load addr), 0),
10904   //                   (load addr + 16), Elts/2)
10905   // --> load32 addr
10906   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10907       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10908       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10909       !Subtarget->isUnalignedMem32Slow()) {
10910     SDValue SubVec2 = Vec.getOperand(1);
10911     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10912       if (Idx2->getZExtValue() == 0) {
10913         SDValue Ops[] = { SubVec2, SubVec };
10914         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10915         if (LD.getNode())
10916           return LD;
10917       }
10918     }
10919   }
10920
10921   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10922       SubVecVT.is128BitVector())
10923     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10924
10925   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10926     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10927
10928   if (OpVT.getVectorElementType() == MVT::i1) {
10929     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10930       return Op;
10931     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10932     SDValue Undef = DAG.getUNDEF(OpVT);
10933     unsigned NumElems = OpVT.getVectorNumElements();
10934     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10935
10936     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10937       // Zero upper bits of the Vec
10938       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10939       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10940
10941       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10942                                  SubVec, ZeroIdx);
10943       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10944       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10945     }
10946     if (IdxVal == 0) {
10947       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10948                                  SubVec, ZeroIdx);
10949       // Zero upper bits of the Vec2
10950       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10951       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10952       // Zero lower bits of the Vec
10953       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10954       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10955       // Merge them together
10956       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10957     }
10958   }
10959   return SDValue();
10960 }
10961
10962 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10963 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10964 // one of the above mentioned nodes. It has to be wrapped because otherwise
10965 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10966 // be used to form addressing mode. These wrapped nodes will be selected
10967 // into MOV32ri.
10968 SDValue
10969 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10970   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10971
10972   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10973   // global base reg.
10974   unsigned char OpFlag = 0;
10975   unsigned WrapperKind = X86ISD::Wrapper;
10976   CodeModel::Model M = DAG.getTarget().getCodeModel();
10977
10978   if (Subtarget->isPICStyleRIPRel() &&
10979       (M == CodeModel::Small || M == CodeModel::Kernel))
10980     WrapperKind = X86ISD::WrapperRIP;
10981   else if (Subtarget->isPICStyleGOT())
10982     OpFlag = X86II::MO_GOTOFF;
10983   else if (Subtarget->isPICStyleStubPIC())
10984     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10985
10986   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10987                                              CP->getAlignment(),
10988                                              CP->getOffset(), OpFlag);
10989   SDLoc DL(CP);
10990   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10991   // With PIC, the address is actually $g + Offset.
10992   if (OpFlag) {
10993     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10994                          DAG.getNode(X86ISD::GlobalBaseReg,
10995                                      SDLoc(), getPointerTy()),
10996                          Result);
10997   }
10998
10999   return Result;
11000 }
11001
11002 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11003   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11004
11005   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11006   // global base reg.
11007   unsigned char OpFlag = 0;
11008   unsigned WrapperKind = X86ISD::Wrapper;
11009   CodeModel::Model M = DAG.getTarget().getCodeModel();
11010
11011   if (Subtarget->isPICStyleRIPRel() &&
11012       (M == CodeModel::Small || M == CodeModel::Kernel))
11013     WrapperKind = X86ISD::WrapperRIP;
11014   else if (Subtarget->isPICStyleGOT())
11015     OpFlag = X86II::MO_GOTOFF;
11016   else if (Subtarget->isPICStyleStubPIC())
11017     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11018
11019   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11020                                           OpFlag);
11021   SDLoc DL(JT);
11022   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11023
11024   // With PIC, the address is actually $g + Offset.
11025   if (OpFlag)
11026     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11027                          DAG.getNode(X86ISD::GlobalBaseReg,
11028                                      SDLoc(), getPointerTy()),
11029                          Result);
11030
11031   return Result;
11032 }
11033
11034 SDValue
11035 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11036   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11037
11038   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11039   // global base reg.
11040   unsigned char OpFlag = 0;
11041   unsigned WrapperKind = X86ISD::Wrapper;
11042   CodeModel::Model M = DAG.getTarget().getCodeModel();
11043
11044   if (Subtarget->isPICStyleRIPRel() &&
11045       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11046     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11047       OpFlag = X86II::MO_GOTPCREL;
11048     WrapperKind = X86ISD::WrapperRIP;
11049   } else if (Subtarget->isPICStyleGOT()) {
11050     OpFlag = X86II::MO_GOT;
11051   } else if (Subtarget->isPICStyleStubPIC()) {
11052     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11053   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11054     OpFlag = X86II::MO_DARWIN_NONLAZY;
11055   }
11056
11057   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11058
11059   SDLoc DL(Op);
11060   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11061
11062   // With PIC, the address is actually $g + Offset.
11063   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11064       !Subtarget->is64Bit()) {
11065     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11066                          DAG.getNode(X86ISD::GlobalBaseReg,
11067                                      SDLoc(), getPointerTy()),
11068                          Result);
11069   }
11070
11071   // For symbols that require a load from a stub to get the address, emit the
11072   // load.
11073   if (isGlobalStubReference(OpFlag))
11074     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11075                          MachinePointerInfo::getGOT(), false, false, false, 0);
11076
11077   return Result;
11078 }
11079
11080 SDValue
11081 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11082   // Create the TargetBlockAddressAddress node.
11083   unsigned char OpFlags =
11084     Subtarget->ClassifyBlockAddressReference();
11085   CodeModel::Model M = DAG.getTarget().getCodeModel();
11086   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11087   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11088   SDLoc dl(Op);
11089   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11090                                              OpFlags);
11091
11092   if (Subtarget->isPICStyleRIPRel() &&
11093       (M == CodeModel::Small || M == CodeModel::Kernel))
11094     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11095   else
11096     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11097
11098   // With PIC, the address is actually $g + Offset.
11099   if (isGlobalRelativeToPICBase(OpFlags)) {
11100     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11101                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11102                          Result);
11103   }
11104
11105   return Result;
11106 }
11107
11108 SDValue
11109 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11110                                       int64_t Offset, SelectionDAG &DAG) const {
11111   // Create the TargetGlobalAddress node, folding in the constant
11112   // offset if it is legal.
11113   unsigned char OpFlags =
11114       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11115   CodeModel::Model M = DAG.getTarget().getCodeModel();
11116   SDValue Result;
11117   if (OpFlags == X86II::MO_NO_FLAG &&
11118       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11119     // A direct static reference to a global.
11120     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11121     Offset = 0;
11122   } else {
11123     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11124   }
11125
11126   if (Subtarget->isPICStyleRIPRel() &&
11127       (M == CodeModel::Small || M == CodeModel::Kernel))
11128     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11129   else
11130     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11131
11132   // With PIC, the address is actually $g + Offset.
11133   if (isGlobalRelativeToPICBase(OpFlags)) {
11134     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11135                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11136                          Result);
11137   }
11138
11139   // For globals that require a load from a stub to get the address, emit the
11140   // load.
11141   if (isGlobalStubReference(OpFlags))
11142     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11143                          MachinePointerInfo::getGOT(), false, false, false, 0);
11144
11145   // If there was a non-zero offset that we didn't fold, create an explicit
11146   // addition for it.
11147   if (Offset != 0)
11148     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11149                          DAG.getConstant(Offset, dl, getPointerTy()));
11150
11151   return Result;
11152 }
11153
11154 SDValue
11155 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11156   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11157   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11158   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11159 }
11160
11161 static SDValue
11162 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11163            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11164            unsigned char OperandFlags, bool LocalDynamic = false) {
11165   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11166   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11167   SDLoc dl(GA);
11168   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11169                                            GA->getValueType(0),
11170                                            GA->getOffset(),
11171                                            OperandFlags);
11172
11173   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11174                                            : X86ISD::TLSADDR;
11175
11176   if (InFlag) {
11177     SDValue Ops[] = { Chain,  TGA, *InFlag };
11178     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11179   } else {
11180     SDValue Ops[]  = { Chain, TGA };
11181     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11182   }
11183
11184   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11185   MFI->setAdjustsStack(true);
11186   MFI->setHasCalls(true);
11187
11188   SDValue Flag = Chain.getValue(1);
11189   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11190 }
11191
11192 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11193 static SDValue
11194 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11195                                 const EVT PtrVT) {
11196   SDValue InFlag;
11197   SDLoc dl(GA);  // ? function entry point might be better
11198   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11199                                    DAG.getNode(X86ISD::GlobalBaseReg,
11200                                                SDLoc(), PtrVT), InFlag);
11201   InFlag = Chain.getValue(1);
11202
11203   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11204 }
11205
11206 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11207 static SDValue
11208 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11209                                 const EVT PtrVT) {
11210   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11211                     X86::RAX, X86II::MO_TLSGD);
11212 }
11213
11214 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11215                                            SelectionDAG &DAG,
11216                                            const EVT PtrVT,
11217                                            bool is64Bit) {
11218   SDLoc dl(GA);
11219
11220   // Get the start address of the TLS block for this module.
11221   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11222       .getInfo<X86MachineFunctionInfo>();
11223   MFI->incNumLocalDynamicTLSAccesses();
11224
11225   SDValue Base;
11226   if (is64Bit) {
11227     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11228                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11229   } else {
11230     SDValue InFlag;
11231     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11232         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11233     InFlag = Chain.getValue(1);
11234     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11235                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11236   }
11237
11238   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11239   // of Base.
11240
11241   // Build x@dtpoff.
11242   unsigned char OperandFlags = X86II::MO_DTPOFF;
11243   unsigned WrapperKind = X86ISD::Wrapper;
11244   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11245                                            GA->getValueType(0),
11246                                            GA->getOffset(), OperandFlags);
11247   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11248
11249   // Add x@dtpoff with the base.
11250   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11251 }
11252
11253 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11254 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11255                                    const EVT PtrVT, TLSModel::Model model,
11256                                    bool is64Bit, bool isPIC) {
11257   SDLoc dl(GA);
11258
11259   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11260   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11261                                                          is64Bit ? 257 : 256));
11262
11263   SDValue ThreadPointer =
11264       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11265                   MachinePointerInfo(Ptr), false, false, false, 0);
11266
11267   unsigned char OperandFlags = 0;
11268   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11269   // initialexec.
11270   unsigned WrapperKind = X86ISD::Wrapper;
11271   if (model == TLSModel::LocalExec) {
11272     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11273   } else if (model == TLSModel::InitialExec) {
11274     if (is64Bit) {
11275       OperandFlags = X86II::MO_GOTTPOFF;
11276       WrapperKind = X86ISD::WrapperRIP;
11277     } else {
11278       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11279     }
11280   } else {
11281     llvm_unreachable("Unexpected model");
11282   }
11283
11284   // emit "addl x@ntpoff,%eax" (local exec)
11285   // or "addl x@indntpoff,%eax" (initial exec)
11286   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11287   SDValue TGA =
11288       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11289                                  GA->getOffset(), OperandFlags);
11290   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11291
11292   if (model == TLSModel::InitialExec) {
11293     if (isPIC && !is64Bit) {
11294       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11295                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11296                            Offset);
11297     }
11298
11299     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11300                          MachinePointerInfo::getGOT(), false, false, false, 0);
11301   }
11302
11303   // The address of the thread local variable is the add of the thread
11304   // pointer with the offset of the variable.
11305   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11306 }
11307
11308 SDValue
11309 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11310
11311   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11312   const GlobalValue *GV = GA->getGlobal();
11313
11314   if (Subtarget->isTargetELF()) {
11315     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11316     switch (model) {
11317       case TLSModel::GeneralDynamic:
11318         if (Subtarget->is64Bit())
11319           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11320         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11321       case TLSModel::LocalDynamic:
11322         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11323                                            Subtarget->is64Bit());
11324       case TLSModel::InitialExec:
11325       case TLSModel::LocalExec:
11326         return LowerToTLSExecModel(
11327             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11328             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11329     }
11330     llvm_unreachable("Unknown TLS model.");
11331   }
11332
11333   if (Subtarget->isTargetDarwin()) {
11334     // Darwin only has one model of TLS.  Lower to that.
11335     unsigned char OpFlag = 0;
11336     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11337                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11338
11339     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11340     // global base reg.
11341     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11342                  !Subtarget->is64Bit();
11343     if (PIC32)
11344       OpFlag = X86II::MO_TLVP_PIC_BASE;
11345     else
11346       OpFlag = X86II::MO_TLVP;
11347     SDLoc DL(Op);
11348     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11349                                                 GA->getValueType(0),
11350                                                 GA->getOffset(), OpFlag);
11351     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11352
11353     // With PIC32, the address is actually $g + Offset.
11354     if (PIC32)
11355       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11356                            DAG.getNode(X86ISD::GlobalBaseReg,
11357                                        SDLoc(), getPointerTy()),
11358                            Offset);
11359
11360     // Lowering the machine isd will make sure everything is in the right
11361     // location.
11362     SDValue Chain = DAG.getEntryNode();
11363     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11364     SDValue Args[] = { Chain, Offset };
11365     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11366
11367     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11368     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11369     MFI->setAdjustsStack(true);
11370
11371     // And our return value (tls address) is in the standard call return value
11372     // location.
11373     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11374     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11375                               Chain.getValue(1));
11376   }
11377
11378   if (Subtarget->isTargetKnownWindowsMSVC() ||
11379       Subtarget->isTargetWindowsGNU()) {
11380     // Just use the implicit TLS architecture
11381     // Need to generate someting similar to:
11382     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11383     //                                  ; from TEB
11384     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11385     //   mov     rcx, qword [rdx+rcx*8]
11386     //   mov     eax, .tls$:tlsvar
11387     //   [rax+rcx] contains the address
11388     // Windows 64bit: gs:0x58
11389     // Windows 32bit: fs:__tls_array
11390
11391     SDLoc dl(GA);
11392     SDValue Chain = DAG.getEntryNode();
11393
11394     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11395     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11396     // use its literal value of 0x2C.
11397     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11398                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11399                                                              256)
11400                                         : Type::getInt32PtrTy(*DAG.getContext(),
11401                                                               257));
11402
11403     SDValue TlsArray =
11404         Subtarget->is64Bit()
11405             ? DAG.getIntPtrConstant(0x58, dl)
11406             : (Subtarget->isTargetWindowsGNU()
11407                    ? DAG.getIntPtrConstant(0x2C, dl)
11408                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11409
11410     SDValue ThreadPointer =
11411         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11412                     MachinePointerInfo(Ptr), false, false, false, 0);
11413
11414     SDValue res;
11415     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11416       res = ThreadPointer;
11417     } else {
11418       // Load the _tls_index variable
11419       SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11420       if (Subtarget->is64Bit())
11421         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, IDX,
11422                              MachinePointerInfo(), MVT::i32, false, false,
11423                              false, 0);
11424       else
11425         IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11426                           false, false, false, 0);
11427
11428       SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11429                                       getPointerTy());
11430       IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11431
11432       res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11433     }
11434
11435     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11436                       false, false, false, 0);
11437
11438     // Get the offset of start of .tls section
11439     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11440                                              GA->getValueType(0),
11441                                              GA->getOffset(), X86II::MO_SECREL);
11442     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11443
11444     // The address of the thread local variable is the add of the thread
11445     // pointer with the offset of the variable.
11446     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11447   }
11448
11449   llvm_unreachable("TLS not implemented for this target.");
11450 }
11451
11452 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11453 /// and take a 2 x i32 value to shift plus a shift amount.
11454 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11455   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11456   MVT VT = Op.getSimpleValueType();
11457   unsigned VTBits = VT.getSizeInBits();
11458   SDLoc dl(Op);
11459   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11460   SDValue ShOpLo = Op.getOperand(0);
11461   SDValue ShOpHi = Op.getOperand(1);
11462   SDValue ShAmt  = Op.getOperand(2);
11463   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11464   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11465   // during isel.
11466   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11467                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11468   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11469                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11470                        : DAG.getConstant(0, dl, VT);
11471
11472   SDValue Tmp2, Tmp3;
11473   if (Op.getOpcode() == ISD::SHL_PARTS) {
11474     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11475     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11476   } else {
11477     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11478     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11479   }
11480
11481   // If the shift amount is larger or equal than the width of a part we can't
11482   // rely on the results of shld/shrd. Insert a test and select the appropriate
11483   // values for large shift amounts.
11484   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11485                                 DAG.getConstant(VTBits, dl, MVT::i8));
11486   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11487                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11488
11489   SDValue Hi, Lo;
11490   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11491   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11492   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11493
11494   if (Op.getOpcode() == ISD::SHL_PARTS) {
11495     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11496     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11497   } else {
11498     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11499     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11500   }
11501
11502   SDValue Ops[2] = { Lo, Hi };
11503   return DAG.getMergeValues(Ops, dl);
11504 }
11505
11506 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11507                                            SelectionDAG &DAG) const {
11508   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11509   SDLoc dl(Op);
11510
11511   if (SrcVT.isVector()) {
11512     if (SrcVT.getVectorElementType() == MVT::i1) {
11513       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11514       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11515                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11516                                      Op.getOperand(0)));
11517     }
11518     return SDValue();
11519   }
11520
11521   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11522          "Unknown SINT_TO_FP to lower!");
11523
11524   // These are really Legal; return the operand so the caller accepts it as
11525   // Legal.
11526   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11527     return Op;
11528   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11529       Subtarget->is64Bit()) {
11530     return Op;
11531   }
11532
11533   unsigned Size = SrcVT.getSizeInBits()/8;
11534   MachineFunction &MF = DAG.getMachineFunction();
11535   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11536   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11537   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11538                                StackSlot,
11539                                MachinePointerInfo::getFixedStack(SSFI),
11540                                false, false, 0);
11541   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11542 }
11543
11544 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11545                                      SDValue StackSlot,
11546                                      SelectionDAG &DAG) const {
11547   // Build the FILD
11548   SDLoc DL(Op);
11549   SDVTList Tys;
11550   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11551   if (useSSE)
11552     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11553   else
11554     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11555
11556   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11557
11558   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11559   MachineMemOperand *MMO;
11560   if (FI) {
11561     int SSFI = FI->getIndex();
11562     MMO =
11563       DAG.getMachineFunction()
11564       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11565                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11566   } else {
11567     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11568     StackSlot = StackSlot.getOperand(1);
11569   }
11570   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11571   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11572                                            X86ISD::FILD, DL,
11573                                            Tys, Ops, SrcVT, MMO);
11574
11575   if (useSSE) {
11576     Chain = Result.getValue(1);
11577     SDValue InFlag = Result.getValue(2);
11578
11579     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11580     // shouldn't be necessary except that RFP cannot be live across
11581     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11582     MachineFunction &MF = DAG.getMachineFunction();
11583     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11584     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11585     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11586     Tys = DAG.getVTList(MVT::Other);
11587     SDValue Ops[] = {
11588       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11589     };
11590     MachineMemOperand *MMO =
11591       DAG.getMachineFunction()
11592       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11593                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11594
11595     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11596                                     Ops, Op.getValueType(), MMO);
11597     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11598                          MachinePointerInfo::getFixedStack(SSFI),
11599                          false, false, false, 0);
11600   }
11601
11602   return Result;
11603 }
11604
11605 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11606 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11607                                                SelectionDAG &DAG) const {
11608   // This algorithm is not obvious. Here it is what we're trying to output:
11609   /*
11610      movq       %rax,  %xmm0
11611      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11612      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11613      #ifdef __SSE3__
11614        haddpd   %xmm0, %xmm0
11615      #else
11616        pshufd   $0x4e, %xmm0, %xmm1
11617        addpd    %xmm1, %xmm0
11618      #endif
11619   */
11620
11621   SDLoc dl(Op);
11622   LLVMContext *Context = DAG.getContext();
11623
11624   // Build some magic constants.
11625   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11626   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11627   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11628
11629   SmallVector<Constant*,2> CV1;
11630   CV1.push_back(
11631     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11632                                       APInt(64, 0x4330000000000000ULL))));
11633   CV1.push_back(
11634     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11635                                       APInt(64, 0x4530000000000000ULL))));
11636   Constant *C1 = ConstantVector::get(CV1);
11637   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11638
11639   // Load the 64-bit value into an XMM register.
11640   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11641                             Op.getOperand(0));
11642   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11643                               MachinePointerInfo::getConstantPool(),
11644                               false, false, false, 16);
11645   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11646                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11647                               CLod0);
11648
11649   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11650                               MachinePointerInfo::getConstantPool(),
11651                               false, false, false, 16);
11652   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11653   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11654   SDValue Result;
11655
11656   if (Subtarget->hasSSE3()) {
11657     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11658     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11659   } else {
11660     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11661     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11662                                            S2F, 0x4E, DAG);
11663     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11664                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11665                          Sub);
11666   }
11667
11668   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11669                      DAG.getIntPtrConstant(0, dl));
11670 }
11671
11672 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11673 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11674                                                SelectionDAG &DAG) const {
11675   SDLoc dl(Op);
11676   // FP constant to bias correct the final result.
11677   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11678                                    MVT::f64);
11679
11680   // Load the 32-bit value into an XMM register.
11681   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11682                              Op.getOperand(0));
11683
11684   // Zero out the upper parts of the register.
11685   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11686
11687   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11688                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11689                      DAG.getIntPtrConstant(0, dl));
11690
11691   // Or the load with the bias.
11692   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11693                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11694                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11695                                                    MVT::v2f64, Load)),
11696                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11697                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11698                                                    MVT::v2f64, Bias)));
11699   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11700                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11701                    DAG.getIntPtrConstant(0, dl));
11702
11703   // Subtract the bias.
11704   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11705
11706   // Handle final rounding.
11707   EVT DestVT = Op.getValueType();
11708
11709   if (DestVT.bitsLT(MVT::f64))
11710     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11711                        DAG.getIntPtrConstant(0, dl));
11712   if (DestVT.bitsGT(MVT::f64))
11713     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11714
11715   // Handle final rounding.
11716   return Sub;
11717 }
11718
11719 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11720                                      const X86Subtarget &Subtarget) {
11721   // The algorithm is the following:
11722   // #ifdef __SSE4_1__
11723   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11724   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11725   //                                 (uint4) 0x53000000, 0xaa);
11726   // #else
11727   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11728   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11729   // #endif
11730   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11731   //     return (float4) lo + fhi;
11732
11733   SDLoc DL(Op);
11734   SDValue V = Op->getOperand(0);
11735   EVT VecIntVT = V.getValueType();
11736   bool Is128 = VecIntVT == MVT::v4i32;
11737   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11738   // If we convert to something else than the supported type, e.g., to v4f64,
11739   // abort early.
11740   if (VecFloatVT != Op->getValueType(0))
11741     return SDValue();
11742
11743   unsigned NumElts = VecIntVT.getVectorNumElements();
11744   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11745          "Unsupported custom type");
11746   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11747
11748   // In the #idef/#else code, we have in common:
11749   // - The vector of constants:
11750   // -- 0x4b000000
11751   // -- 0x53000000
11752   // - A shift:
11753   // -- v >> 16
11754
11755   // Create the splat vector for 0x4b000000.
11756   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11757   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11758                            CstLow, CstLow, CstLow, CstLow};
11759   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11760                                   makeArrayRef(&CstLowArray[0], NumElts));
11761   // Create the splat vector for 0x53000000.
11762   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11763   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11764                             CstHigh, CstHigh, CstHigh, CstHigh};
11765   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11766                                    makeArrayRef(&CstHighArray[0], NumElts));
11767
11768   // Create the right shift.
11769   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11770   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11771                              CstShift, CstShift, CstShift, CstShift};
11772   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11773                                     makeArrayRef(&CstShiftArray[0], NumElts));
11774   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11775
11776   SDValue Low, High;
11777   if (Subtarget.hasSSE41()) {
11778     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11779     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11780     SDValue VecCstLowBitcast =
11781         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11782     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11783     // Low will be bitcasted right away, so do not bother bitcasting back to its
11784     // original type.
11785     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11786                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11787     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11788     //                                 (uint4) 0x53000000, 0xaa);
11789     SDValue VecCstHighBitcast =
11790         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11791     SDValue VecShiftBitcast =
11792         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11793     // High will be bitcasted right away, so do not bother bitcasting back to
11794     // its original type.
11795     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11796                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11797   } else {
11798     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11799     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11800                                      CstMask, CstMask, CstMask);
11801     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11802     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11803     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11804
11805     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11806     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11807   }
11808
11809   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11810   SDValue CstFAdd = DAG.getConstantFP(
11811       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11812   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11813                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11814   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11815                                    makeArrayRef(&CstFAddArray[0], NumElts));
11816
11817   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11818   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11819   SDValue FHigh =
11820       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11821   //     return (float4) lo + fhi;
11822   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11823   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11824 }
11825
11826 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11827                                                SelectionDAG &DAG) const {
11828   SDValue N0 = Op.getOperand(0);
11829   MVT SVT = N0.getSimpleValueType();
11830   SDLoc dl(Op);
11831
11832   switch (SVT.SimpleTy) {
11833   default:
11834     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11835   case MVT::v4i8:
11836   case MVT::v4i16:
11837   case MVT::v8i8:
11838   case MVT::v8i16: {
11839     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11840     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11841                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11842   }
11843   case MVT::v4i32:
11844   case MVT::v8i32:
11845     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11846   case MVT::v16i8:
11847   case MVT::v16i16:
11848     if (Subtarget->hasAVX512())
11849       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11850                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11851   }
11852   llvm_unreachable(nullptr);
11853 }
11854
11855 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11856                                            SelectionDAG &DAG) const {
11857   SDValue N0 = Op.getOperand(0);
11858   SDLoc dl(Op);
11859
11860   if (Op.getValueType().isVector())
11861     return lowerUINT_TO_FP_vec(Op, DAG);
11862
11863   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11864   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11865   // the optimization here.
11866   if (DAG.SignBitIsZero(N0))
11867     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11868
11869   MVT SrcVT = N0.getSimpleValueType();
11870   MVT DstVT = Op.getSimpleValueType();
11871   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11872     return LowerUINT_TO_FP_i64(Op, DAG);
11873   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11874     return LowerUINT_TO_FP_i32(Op, DAG);
11875   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11876     return SDValue();
11877
11878   // Make a 64-bit buffer, and use it to build an FILD.
11879   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11880   if (SrcVT == MVT::i32) {
11881     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11882     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11883                                      getPointerTy(), StackSlot, WordOff);
11884     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11885                                   StackSlot, MachinePointerInfo(),
11886                                   false, false, 0);
11887     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11888                                   OffsetSlot, MachinePointerInfo(),
11889                                   false, false, 0);
11890     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11891     return Fild;
11892   }
11893
11894   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11895   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11896                                StackSlot, MachinePointerInfo(),
11897                                false, false, 0);
11898   // For i64 source, we need to add the appropriate power of 2 if the input
11899   // was negative.  This is the same as the optimization in
11900   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11901   // we must be careful to do the computation in x87 extended precision, not
11902   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11903   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11904   MachineMemOperand *MMO =
11905     DAG.getMachineFunction()
11906     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11907                           MachineMemOperand::MOLoad, 8, 8);
11908
11909   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11910   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11911   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11912                                          MVT::i64, MMO);
11913
11914   APInt FF(32, 0x5F800000ULL);
11915
11916   // Check whether the sign bit is set.
11917   SDValue SignSet = DAG.getSetCC(dl,
11918                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11919                                  Op.getOperand(0),
11920                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11921
11922   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11923   SDValue FudgePtr = DAG.getConstantPool(
11924                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11925                                          getPointerTy());
11926
11927   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11928   SDValue Zero = DAG.getIntPtrConstant(0, dl);
11929   SDValue Four = DAG.getIntPtrConstant(4, dl);
11930   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11931                                Zero, Four);
11932   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11933
11934   // Load the value out, extending it from f32 to f80.
11935   // FIXME: Avoid the extend by constructing the right constant pool?
11936   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11937                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11938                                  MVT::f32, false, false, false, 4);
11939   // Extend everything to 80 bits to force it to be done on x87.
11940   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11941   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11942                      DAG.getIntPtrConstant(0, dl));
11943 }
11944
11945 std::pair<SDValue,SDValue>
11946 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11947                                     bool IsSigned, bool IsReplace) const {
11948   SDLoc DL(Op);
11949
11950   EVT DstTy = Op.getValueType();
11951
11952   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11953     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11954     DstTy = MVT::i64;
11955   }
11956
11957   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11958          DstTy.getSimpleVT() >= MVT::i16 &&
11959          "Unknown FP_TO_INT to lower!");
11960
11961   // These are really Legal.
11962   if (DstTy == MVT::i32 &&
11963       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11964     return std::make_pair(SDValue(), SDValue());
11965   if (Subtarget->is64Bit() &&
11966       DstTy == MVT::i64 &&
11967       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11968     return std::make_pair(SDValue(), SDValue());
11969
11970   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11971   // stack slot, or into the FTOL runtime function.
11972   MachineFunction &MF = DAG.getMachineFunction();
11973   unsigned MemSize = DstTy.getSizeInBits()/8;
11974   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11975   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11976
11977   unsigned Opc;
11978   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11979     Opc = X86ISD::WIN_FTOL;
11980   else
11981     switch (DstTy.getSimpleVT().SimpleTy) {
11982     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11983     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11984     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11985     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11986     }
11987
11988   SDValue Chain = DAG.getEntryNode();
11989   SDValue Value = Op.getOperand(0);
11990   EVT TheVT = Op.getOperand(0).getValueType();
11991   // FIXME This causes a redundant load/store if the SSE-class value is already
11992   // in memory, such as if it is on the callstack.
11993   if (isScalarFPTypeInSSEReg(TheVT)) {
11994     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11995     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11996                          MachinePointerInfo::getFixedStack(SSFI),
11997                          false, false, 0);
11998     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11999     SDValue Ops[] = {
12000       Chain, StackSlot, DAG.getValueType(TheVT)
12001     };
12002
12003     MachineMemOperand *MMO =
12004       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12005                               MachineMemOperand::MOLoad, MemSize, MemSize);
12006     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12007     Chain = Value.getValue(1);
12008     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12009     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12010   }
12011
12012   MachineMemOperand *MMO =
12013     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12014                             MachineMemOperand::MOStore, MemSize, MemSize);
12015
12016   if (Opc != X86ISD::WIN_FTOL) {
12017     // Build the FP_TO_INT*_IN_MEM
12018     SDValue Ops[] = { Chain, Value, StackSlot };
12019     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12020                                            Ops, DstTy, MMO);
12021     return std::make_pair(FIST, StackSlot);
12022   } else {
12023     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12024       DAG.getVTList(MVT::Other, MVT::Glue),
12025       Chain, Value);
12026     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12027       MVT::i32, ftol.getValue(1));
12028     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12029       MVT::i32, eax.getValue(2));
12030     SDValue Ops[] = { eax, edx };
12031     SDValue pair = IsReplace
12032       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12033       : DAG.getMergeValues(Ops, DL);
12034     return std::make_pair(pair, SDValue());
12035   }
12036 }
12037
12038 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12039                               const X86Subtarget *Subtarget) {
12040   MVT VT = Op->getSimpleValueType(0);
12041   SDValue In = Op->getOperand(0);
12042   MVT InVT = In.getSimpleValueType();
12043   SDLoc dl(Op);
12044
12045   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12046     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12047
12048   // Optimize vectors in AVX mode:
12049   //
12050   //   v8i16 -> v8i32
12051   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12052   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12053   //   Concat upper and lower parts.
12054   //
12055   //   v4i32 -> v4i64
12056   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12057   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12058   //   Concat upper and lower parts.
12059   //
12060
12061   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12062       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12063       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12064     return SDValue();
12065
12066   if (Subtarget->hasInt256())
12067     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12068
12069   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12070   SDValue Undef = DAG.getUNDEF(InVT);
12071   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12072   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12073   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12074
12075   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12076                              VT.getVectorNumElements()/2);
12077
12078   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12079   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12080
12081   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12082 }
12083
12084 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12085                                         SelectionDAG &DAG) {
12086   MVT VT = Op->getSimpleValueType(0);
12087   SDValue In = Op->getOperand(0);
12088   MVT InVT = In.getSimpleValueType();
12089   SDLoc DL(Op);
12090   unsigned int NumElts = VT.getVectorNumElements();
12091   if (NumElts != 8 && NumElts != 16)
12092     return SDValue();
12093
12094   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12095     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12096
12097   assert(InVT.getVectorElementType() == MVT::i1);
12098   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12099   SDValue One =
12100    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12101   SDValue Zero =
12102    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12103
12104   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12105   if (VT.is512BitVector())
12106     return V;
12107   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12108 }
12109
12110 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12111                                SelectionDAG &DAG) {
12112   if (Subtarget->hasFp256()) {
12113     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12114     if (Res.getNode())
12115       return Res;
12116   }
12117
12118   return SDValue();
12119 }
12120
12121 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12122                                 SelectionDAG &DAG) {
12123   SDLoc DL(Op);
12124   MVT VT = Op.getSimpleValueType();
12125   SDValue In = Op.getOperand(0);
12126   MVT SVT = In.getSimpleValueType();
12127
12128   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12129     return LowerZERO_EXTEND_AVX512(Op, DAG);
12130
12131   if (Subtarget->hasFp256()) {
12132     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12133     if (Res.getNode())
12134       return Res;
12135   }
12136
12137   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12138          VT.getVectorNumElements() != SVT.getVectorNumElements());
12139   return SDValue();
12140 }
12141
12142 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12143   SDLoc DL(Op);
12144   MVT VT = Op.getSimpleValueType();
12145   SDValue In = Op.getOperand(0);
12146   MVT InVT = In.getSimpleValueType();
12147
12148   if (VT == MVT::i1) {
12149     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12150            "Invalid scalar TRUNCATE operation");
12151     if (InVT.getSizeInBits() >= 32)
12152       return SDValue();
12153     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12154     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12155   }
12156   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12157          "Invalid TRUNCATE operation");
12158
12159   // move vector to mask - truncate solution for SKX
12160   if (VT.getVectorElementType() == MVT::i1) {
12161     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12162         Subtarget->hasBWI())
12163       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12164     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12165         && InVT.getScalarSizeInBits() <= 16 &&
12166         Subtarget->hasBWI() && Subtarget->hasVLX())
12167       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12168     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12169         Subtarget->hasDQI())
12170       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12171     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12172         && InVT.getScalarSizeInBits() >= 32 &&
12173         Subtarget->hasDQI() && Subtarget->hasVLX())
12174       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12175   }
12176   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12177     if (VT.getVectorElementType().getSizeInBits() >=8)
12178       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12179
12180     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12181     unsigned NumElts = InVT.getVectorNumElements();
12182     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12183     if (InVT.getSizeInBits() < 512) {
12184       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12185       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12186       InVT = ExtVT;
12187     }
12188
12189     SDValue OneV =
12190      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12191     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12192     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12193   }
12194
12195   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12196     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12197     if (Subtarget->hasInt256()) {
12198       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12199       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12200       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12201                                 ShufMask);
12202       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12203                          DAG.getIntPtrConstant(0, DL));
12204     }
12205
12206     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12207                                DAG.getIntPtrConstant(0, DL));
12208     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12209                                DAG.getIntPtrConstant(2, DL));
12210     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12211     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12212     static const int ShufMask[] = {0, 2, 4, 6};
12213     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12214   }
12215
12216   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12217     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12218     if (Subtarget->hasInt256()) {
12219       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12220
12221       SmallVector<SDValue,32> pshufbMask;
12222       for (unsigned i = 0; i < 2; ++i) {
12223         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12224         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12225         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12226         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12227         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12228         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12229         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12230         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12231         for (unsigned j = 0; j < 8; ++j)
12232           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12233       }
12234       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12235       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12236       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12237
12238       static const int ShufMask[] = {0,  2,  -1,  -1};
12239       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12240                                 &ShufMask[0]);
12241       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12242                        DAG.getIntPtrConstant(0, DL));
12243       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12244     }
12245
12246     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12247                                DAG.getIntPtrConstant(0, DL));
12248
12249     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12250                                DAG.getIntPtrConstant(4, DL));
12251
12252     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12253     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12254
12255     // The PSHUFB mask:
12256     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12257                                    -1, -1, -1, -1, -1, -1, -1, -1};
12258
12259     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12260     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12261     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12262
12263     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12264     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12265
12266     // The MOVLHPS Mask:
12267     static const int ShufMask2[] = {0, 1, 4, 5};
12268     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12269     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12270   }
12271
12272   // Handle truncation of V256 to V128 using shuffles.
12273   if (!VT.is128BitVector() || !InVT.is256BitVector())
12274     return SDValue();
12275
12276   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12277
12278   unsigned NumElems = VT.getVectorNumElements();
12279   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12280
12281   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12282   // Prepare truncation shuffle mask
12283   for (unsigned i = 0; i != NumElems; ++i)
12284     MaskVec[i] = i * 2;
12285   SDValue V = DAG.getVectorShuffle(NVT, DL,
12286                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12287                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12288   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12289                      DAG.getIntPtrConstant(0, DL));
12290 }
12291
12292 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12293                                            SelectionDAG &DAG) const {
12294   assert(!Op.getSimpleValueType().isVector());
12295
12296   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12297     /*IsSigned=*/ true, /*IsReplace=*/ false);
12298   SDValue FIST = Vals.first, StackSlot = Vals.second;
12299   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12300   if (!FIST.getNode()) return Op;
12301
12302   if (StackSlot.getNode())
12303     // Load the result.
12304     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12305                        FIST, StackSlot, MachinePointerInfo(),
12306                        false, false, false, 0);
12307
12308   // The node is the result.
12309   return FIST;
12310 }
12311
12312 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12313                                            SelectionDAG &DAG) const {
12314   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12315     /*IsSigned=*/ false, /*IsReplace=*/ false);
12316   SDValue FIST = Vals.first, StackSlot = Vals.second;
12317   assert(FIST.getNode() && "Unexpected failure");
12318
12319   if (StackSlot.getNode())
12320     // Load the result.
12321     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12322                        FIST, StackSlot, MachinePointerInfo(),
12323                        false, false, false, 0);
12324
12325   // The node is the result.
12326   return FIST;
12327 }
12328
12329 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12330   SDLoc DL(Op);
12331   MVT VT = Op.getSimpleValueType();
12332   SDValue In = Op.getOperand(0);
12333   MVT SVT = In.getSimpleValueType();
12334
12335   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12336
12337   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12338                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12339                                  In, DAG.getUNDEF(SVT)));
12340 }
12341
12342 /// The only differences between FABS and FNEG are the mask and the logic op.
12343 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12344 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12345   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12346          "Wrong opcode for lowering FABS or FNEG.");
12347
12348   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12349
12350   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12351   // into an FNABS. We'll lower the FABS after that if it is still in use.
12352   if (IsFABS)
12353     for (SDNode *User : Op->uses())
12354       if (User->getOpcode() == ISD::FNEG)
12355         return Op;
12356
12357   SDValue Op0 = Op.getOperand(0);
12358   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12359
12360   SDLoc dl(Op);
12361   MVT VT = Op.getSimpleValueType();
12362   // Assume scalar op for initialization; update for vector if needed.
12363   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12364   // generate a 16-byte vector constant and logic op even for the scalar case.
12365   // Using a 16-byte mask allows folding the load of the mask with
12366   // the logic op, so it can save (~4 bytes) on code size.
12367   MVT EltVT = VT;
12368   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12369   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12370   // decide if we should generate a 16-byte constant mask when we only need 4 or
12371   // 8 bytes for the scalar case.
12372   if (VT.isVector()) {
12373     EltVT = VT.getVectorElementType();
12374     NumElts = VT.getVectorNumElements();
12375   }
12376
12377   unsigned EltBits = EltVT.getSizeInBits();
12378   LLVMContext *Context = DAG.getContext();
12379   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12380   APInt MaskElt =
12381     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12382   Constant *C = ConstantInt::get(*Context, MaskElt);
12383   C = ConstantVector::getSplat(NumElts, C);
12384   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12385   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12386   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12387   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12388                              MachinePointerInfo::getConstantPool(),
12389                              false, false, false, Alignment);
12390
12391   if (VT.isVector()) {
12392     // For a vector, cast operands to a vector type, perform the logic op,
12393     // and cast the result back to the original value type.
12394     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12395     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12396     SDValue Operand = IsFNABS ?
12397       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12398       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12399     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12400     return DAG.getNode(ISD::BITCAST, dl, VT,
12401                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12402   }
12403
12404   // If not vector, then scalar.
12405   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12406   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12407   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12408 }
12409
12410 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12411   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12412   LLVMContext *Context = DAG.getContext();
12413   SDValue Op0 = Op.getOperand(0);
12414   SDValue Op1 = Op.getOperand(1);
12415   SDLoc dl(Op);
12416   MVT VT = Op.getSimpleValueType();
12417   MVT SrcVT = Op1.getSimpleValueType();
12418
12419   // If second operand is smaller, extend it first.
12420   if (SrcVT.bitsLT(VT)) {
12421     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12422     SrcVT = VT;
12423   }
12424   // And if it is bigger, shrink it first.
12425   if (SrcVT.bitsGT(VT)) {
12426     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12427     SrcVT = VT;
12428   }
12429
12430   // At this point the operands and the result should have the same
12431   // type, and that won't be f80 since that is not custom lowered.
12432
12433   const fltSemantics &Sem =
12434       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12435   const unsigned SizeInBits = VT.getSizeInBits();
12436
12437   SmallVector<Constant *, 4> CV(
12438       VT == MVT::f64 ? 2 : 4,
12439       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12440
12441   // First, clear all bits but the sign bit from the second operand (sign).
12442   CV[0] = ConstantFP::get(*Context,
12443                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12444   Constant *C = ConstantVector::get(CV);
12445   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12446   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12447                               MachinePointerInfo::getConstantPool(),
12448                               false, false, false, 16);
12449   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12450
12451   // Next, clear the sign bit from the first operand (magnitude).
12452   // If it's a constant, we can clear it here.
12453   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12454     APFloat APF = Op0CN->getValueAPF();
12455     // If the magnitude is a positive zero, the sign bit alone is enough.
12456     if (APF.isPosZero())
12457       return SignBit;
12458     APF.clearSign();
12459     CV[0] = ConstantFP::get(*Context, APF);
12460   } else {
12461     CV[0] = ConstantFP::get(
12462         *Context,
12463         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12464   }
12465   C = ConstantVector::get(CV);
12466   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12467   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12468                             MachinePointerInfo::getConstantPool(),
12469                             false, false, false, 16);
12470   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12471   if (!isa<ConstantFPSDNode>(Op0))
12472     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12473
12474   // OR the magnitude value with the sign bit.
12475   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12476 }
12477
12478 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12479   SDValue N0 = Op.getOperand(0);
12480   SDLoc dl(Op);
12481   MVT VT = Op.getSimpleValueType();
12482
12483   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12484   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12485                                   DAG.getConstant(1, dl, VT));
12486   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12487 }
12488
12489 // Check whether an OR'd tree is PTEST-able.
12490 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12491                                       SelectionDAG &DAG) {
12492   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12493
12494   if (!Subtarget->hasSSE41())
12495     return SDValue();
12496
12497   if (!Op->hasOneUse())
12498     return SDValue();
12499
12500   SDNode *N = Op.getNode();
12501   SDLoc DL(N);
12502
12503   SmallVector<SDValue, 8> Opnds;
12504   DenseMap<SDValue, unsigned> VecInMap;
12505   SmallVector<SDValue, 8> VecIns;
12506   EVT VT = MVT::Other;
12507
12508   // Recognize a special case where a vector is casted into wide integer to
12509   // test all 0s.
12510   Opnds.push_back(N->getOperand(0));
12511   Opnds.push_back(N->getOperand(1));
12512
12513   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12514     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12515     // BFS traverse all OR'd operands.
12516     if (I->getOpcode() == ISD::OR) {
12517       Opnds.push_back(I->getOperand(0));
12518       Opnds.push_back(I->getOperand(1));
12519       // Re-evaluate the number of nodes to be traversed.
12520       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12521       continue;
12522     }
12523
12524     // Quit if a non-EXTRACT_VECTOR_ELT
12525     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12526       return SDValue();
12527
12528     // Quit if without a constant index.
12529     SDValue Idx = I->getOperand(1);
12530     if (!isa<ConstantSDNode>(Idx))
12531       return SDValue();
12532
12533     SDValue ExtractedFromVec = I->getOperand(0);
12534     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12535     if (M == VecInMap.end()) {
12536       VT = ExtractedFromVec.getValueType();
12537       // Quit if not 128/256-bit vector.
12538       if (!VT.is128BitVector() && !VT.is256BitVector())
12539         return SDValue();
12540       // Quit if not the same type.
12541       if (VecInMap.begin() != VecInMap.end() &&
12542           VT != VecInMap.begin()->first.getValueType())
12543         return SDValue();
12544       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12545       VecIns.push_back(ExtractedFromVec);
12546     }
12547     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12548   }
12549
12550   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12551          "Not extracted from 128-/256-bit vector.");
12552
12553   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12554
12555   for (DenseMap<SDValue, unsigned>::const_iterator
12556         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12557     // Quit if not all elements are used.
12558     if (I->second != FullMask)
12559       return SDValue();
12560   }
12561
12562   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12563
12564   // Cast all vectors into TestVT for PTEST.
12565   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12566     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12567
12568   // If more than one full vectors are evaluated, OR them first before PTEST.
12569   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12570     // Each iteration will OR 2 nodes and append the result until there is only
12571     // 1 node left, i.e. the final OR'd value of all vectors.
12572     SDValue LHS = VecIns[Slot];
12573     SDValue RHS = VecIns[Slot + 1];
12574     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12575   }
12576
12577   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12578                      VecIns.back(), VecIns.back());
12579 }
12580
12581 /// \brief return true if \c Op has a use that doesn't just read flags.
12582 static bool hasNonFlagsUse(SDValue Op) {
12583   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12584        ++UI) {
12585     SDNode *User = *UI;
12586     unsigned UOpNo = UI.getOperandNo();
12587     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12588       // Look pass truncate.
12589       UOpNo = User->use_begin().getOperandNo();
12590       User = *User->use_begin();
12591     }
12592
12593     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12594         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12595       return true;
12596   }
12597   return false;
12598 }
12599
12600 /// Emit nodes that will be selected as "test Op0,Op0", or something
12601 /// equivalent.
12602 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12603                                     SelectionDAG &DAG) const {
12604   if (Op.getValueType() == MVT::i1) {
12605     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12606     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12607                        DAG.getConstant(0, dl, MVT::i8));
12608   }
12609   // CF and OF aren't always set the way we want. Determine which
12610   // of these we need.
12611   bool NeedCF = false;
12612   bool NeedOF = false;
12613   switch (X86CC) {
12614   default: break;
12615   case X86::COND_A: case X86::COND_AE:
12616   case X86::COND_B: case X86::COND_BE:
12617     NeedCF = true;
12618     break;
12619   case X86::COND_G: case X86::COND_GE:
12620   case X86::COND_L: case X86::COND_LE:
12621   case X86::COND_O: case X86::COND_NO: {
12622     // Check if we really need to set the
12623     // Overflow flag. If NoSignedWrap is present
12624     // that is not actually needed.
12625     switch (Op->getOpcode()) {
12626     case ISD::ADD:
12627     case ISD::SUB:
12628     case ISD::MUL:
12629     case ISD::SHL: {
12630       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12631       if (BinNode->Flags.hasNoSignedWrap())
12632         break;
12633     }
12634     default:
12635       NeedOF = true;
12636       break;
12637     }
12638     break;
12639   }
12640   }
12641   // See if we can use the EFLAGS value from the operand instead of
12642   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12643   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12644   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12645     // Emit a CMP with 0, which is the TEST pattern.
12646     //if (Op.getValueType() == MVT::i1)
12647     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12648     //                     DAG.getConstant(0, MVT::i1));
12649     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12650                        DAG.getConstant(0, dl, Op.getValueType()));
12651   }
12652   unsigned Opcode = 0;
12653   unsigned NumOperands = 0;
12654
12655   // Truncate operations may prevent the merge of the SETCC instruction
12656   // and the arithmetic instruction before it. Attempt to truncate the operands
12657   // of the arithmetic instruction and use a reduced bit-width instruction.
12658   bool NeedTruncation = false;
12659   SDValue ArithOp = Op;
12660   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12661     SDValue Arith = Op->getOperand(0);
12662     // Both the trunc and the arithmetic op need to have one user each.
12663     if (Arith->hasOneUse())
12664       switch (Arith.getOpcode()) {
12665         default: break;
12666         case ISD::ADD:
12667         case ISD::SUB:
12668         case ISD::AND:
12669         case ISD::OR:
12670         case ISD::XOR: {
12671           NeedTruncation = true;
12672           ArithOp = Arith;
12673         }
12674       }
12675   }
12676
12677   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12678   // which may be the result of a CAST.  We use the variable 'Op', which is the
12679   // non-casted variable when we check for possible users.
12680   switch (ArithOp.getOpcode()) {
12681   case ISD::ADD:
12682     // Due to an isel shortcoming, be conservative if this add is likely to be
12683     // selected as part of a load-modify-store instruction. When the root node
12684     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12685     // uses of other nodes in the match, such as the ADD in this case. This
12686     // leads to the ADD being left around and reselected, with the result being
12687     // two adds in the output.  Alas, even if none our users are stores, that
12688     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12689     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12690     // climbing the DAG back to the root, and it doesn't seem to be worth the
12691     // effort.
12692     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12693          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12694       if (UI->getOpcode() != ISD::CopyToReg &&
12695           UI->getOpcode() != ISD::SETCC &&
12696           UI->getOpcode() != ISD::STORE)
12697         goto default_case;
12698
12699     if (ConstantSDNode *C =
12700         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12701       // An add of one will be selected as an INC.
12702       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12703         Opcode = X86ISD::INC;
12704         NumOperands = 1;
12705         break;
12706       }
12707
12708       // An add of negative one (subtract of one) will be selected as a DEC.
12709       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12710         Opcode = X86ISD::DEC;
12711         NumOperands = 1;
12712         break;
12713       }
12714     }
12715
12716     // Otherwise use a regular EFLAGS-setting add.
12717     Opcode = X86ISD::ADD;
12718     NumOperands = 2;
12719     break;
12720   case ISD::SHL:
12721   case ISD::SRL:
12722     // If we have a constant logical shift that's only used in a comparison
12723     // against zero turn it into an equivalent AND. This allows turning it into
12724     // a TEST instruction later.
12725     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12726         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12727       EVT VT = Op.getValueType();
12728       unsigned BitWidth = VT.getSizeInBits();
12729       unsigned ShAmt = Op->getConstantOperandVal(1);
12730       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12731         break;
12732       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12733                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12734                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12735       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12736         break;
12737       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12738                                 DAG.getConstant(Mask, dl, VT));
12739       DAG.ReplaceAllUsesWith(Op, New);
12740       Op = New;
12741     }
12742     break;
12743
12744   case ISD::AND:
12745     // If the primary and result isn't used, don't bother using X86ISD::AND,
12746     // because a TEST instruction will be better.
12747     if (!hasNonFlagsUse(Op))
12748       break;
12749     // FALL THROUGH
12750   case ISD::SUB:
12751   case ISD::OR:
12752   case ISD::XOR:
12753     // Due to the ISEL shortcoming noted above, be conservative if this op is
12754     // likely to be selected as part of a load-modify-store instruction.
12755     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12756            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12757       if (UI->getOpcode() == ISD::STORE)
12758         goto default_case;
12759
12760     // Otherwise use a regular EFLAGS-setting instruction.
12761     switch (ArithOp.getOpcode()) {
12762     default: llvm_unreachable("unexpected operator!");
12763     case ISD::SUB: Opcode = X86ISD::SUB; break;
12764     case ISD::XOR: Opcode = X86ISD::XOR; break;
12765     case ISD::AND: Opcode = X86ISD::AND; break;
12766     case ISD::OR: {
12767       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12768         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12769         if (EFLAGS.getNode())
12770           return EFLAGS;
12771       }
12772       Opcode = X86ISD::OR;
12773       break;
12774     }
12775     }
12776
12777     NumOperands = 2;
12778     break;
12779   case X86ISD::ADD:
12780   case X86ISD::SUB:
12781   case X86ISD::INC:
12782   case X86ISD::DEC:
12783   case X86ISD::OR:
12784   case X86ISD::XOR:
12785   case X86ISD::AND:
12786     return SDValue(Op.getNode(), 1);
12787   default:
12788   default_case:
12789     break;
12790   }
12791
12792   // If we found that truncation is beneficial, perform the truncation and
12793   // update 'Op'.
12794   if (NeedTruncation) {
12795     EVT VT = Op.getValueType();
12796     SDValue WideVal = Op->getOperand(0);
12797     EVT WideVT = WideVal.getValueType();
12798     unsigned ConvertedOp = 0;
12799     // Use a target machine opcode to prevent further DAGCombine
12800     // optimizations that may separate the arithmetic operations
12801     // from the setcc node.
12802     switch (WideVal.getOpcode()) {
12803       default: break;
12804       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12805       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12806       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12807       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12808       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12809     }
12810
12811     if (ConvertedOp) {
12812       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12813       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12814         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12815         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12816         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12817       }
12818     }
12819   }
12820
12821   if (Opcode == 0)
12822     // Emit a CMP with 0, which is the TEST pattern.
12823     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12824                        DAG.getConstant(0, dl, Op.getValueType()));
12825
12826   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12827   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12828
12829   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12830   DAG.ReplaceAllUsesWith(Op, New);
12831   return SDValue(New.getNode(), 1);
12832 }
12833
12834 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12835 /// equivalent.
12836 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12837                                    SDLoc dl, SelectionDAG &DAG) const {
12838   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12839     if (C->getAPIntValue() == 0)
12840       return EmitTest(Op0, X86CC, dl, DAG);
12841
12842      if (Op0.getValueType() == MVT::i1)
12843        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12844   }
12845
12846   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12847        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12848     // Do the comparison at i32 if it's smaller, besides the Atom case.
12849     // This avoids subregister aliasing issues. Keep the smaller reference
12850     // if we're optimizing for size, however, as that'll allow better folding
12851     // of memory operations.
12852     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12853         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12854             Attribute::MinSize) &&
12855         !Subtarget->isAtom()) {
12856       unsigned ExtendOp =
12857           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12858       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12859       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12860     }
12861     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12862     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12863     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12864                               Op0, Op1);
12865     return SDValue(Sub.getNode(), 1);
12866   }
12867   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12868 }
12869
12870 /// Convert a comparison if required by the subtarget.
12871 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12872                                                  SelectionDAG &DAG) const {
12873   // If the subtarget does not support the FUCOMI instruction, floating-point
12874   // comparisons have to be converted.
12875   if (Subtarget->hasCMov() ||
12876       Cmp.getOpcode() != X86ISD::CMP ||
12877       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12878       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12879     return Cmp;
12880
12881   // The instruction selector will select an FUCOM instruction instead of
12882   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12883   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12884   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12885   SDLoc dl(Cmp);
12886   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12887   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12888   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12889                             DAG.getConstant(8, dl, MVT::i8));
12890   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12891   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12892 }
12893
12894 /// The minimum architected relative accuracy is 2^-12. We need one
12895 /// Newton-Raphson step to have a good float result (24 bits of precision).
12896 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12897                                             DAGCombinerInfo &DCI,
12898                                             unsigned &RefinementSteps,
12899                                             bool &UseOneConstNR) const {
12900   // FIXME: We should use instruction latency models to calculate the cost of
12901   // each potential sequence, but this is very hard to do reliably because
12902   // at least Intel's Core* chips have variable timing based on the number of
12903   // significant digits in the divisor and/or sqrt operand.
12904   if (!Subtarget->useSqrtEst())
12905     return SDValue();
12906
12907   EVT VT = Op.getValueType();
12908
12909   // SSE1 has rsqrtss and rsqrtps.
12910   // TODO: Add support for AVX512 (v16f32).
12911   // It is likely not profitable to do this for f64 because a double-precision
12912   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12913   // instructions: convert to single, rsqrtss, convert back to double, refine
12914   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12915   // along with FMA, this could be a throughput win.
12916   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12917       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12918     RefinementSteps = 1;
12919     UseOneConstNR = false;
12920     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12921   }
12922   return SDValue();
12923 }
12924
12925 /// The minimum architected relative accuracy is 2^-12. We need one
12926 /// Newton-Raphson step to have a good float result (24 bits of precision).
12927 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12928                                             DAGCombinerInfo &DCI,
12929                                             unsigned &RefinementSteps) const {
12930   // FIXME: We should use instruction latency models to calculate the cost of
12931   // each potential sequence, but this is very hard to do reliably because
12932   // at least Intel's Core* chips have variable timing based on the number of
12933   // significant digits in the divisor.
12934   if (!Subtarget->useReciprocalEst())
12935     return SDValue();
12936
12937   EVT VT = Op.getValueType();
12938
12939   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12940   // TODO: Add support for AVX512 (v16f32).
12941   // It is likely not profitable to do this for f64 because a double-precision
12942   // reciprocal estimate with refinement on x86 prior to FMA requires
12943   // 15 instructions: convert to single, rcpss, convert back to double, refine
12944   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12945   // along with FMA, this could be a throughput win.
12946   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12947       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12948     RefinementSteps = ReciprocalEstimateRefinementSteps;
12949     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12950   }
12951   return SDValue();
12952 }
12953
12954 /// If we have at least two divisions that use the same divisor, convert to
12955 /// multplication by a reciprocal. This may need to be adjusted for a given
12956 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12957 /// This is because we still need one division to calculate the reciprocal and
12958 /// then we need two multiplies by that reciprocal as replacements for the
12959 /// original divisions.
12960 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12961   return NumUsers > 1;
12962 }
12963
12964 static bool isAllOnes(SDValue V) {
12965   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12966   return C && C->isAllOnesValue();
12967 }
12968
12969 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12970 /// if it's possible.
12971 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12972                                      SDLoc dl, SelectionDAG &DAG) const {
12973   SDValue Op0 = And.getOperand(0);
12974   SDValue Op1 = And.getOperand(1);
12975   if (Op0.getOpcode() == ISD::TRUNCATE)
12976     Op0 = Op0.getOperand(0);
12977   if (Op1.getOpcode() == ISD::TRUNCATE)
12978     Op1 = Op1.getOperand(0);
12979
12980   SDValue LHS, RHS;
12981   if (Op1.getOpcode() == ISD::SHL)
12982     std::swap(Op0, Op1);
12983   if (Op0.getOpcode() == ISD::SHL) {
12984     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12985       if (And00C->getZExtValue() == 1) {
12986         // If we looked past a truncate, check that it's only truncating away
12987         // known zeros.
12988         unsigned BitWidth = Op0.getValueSizeInBits();
12989         unsigned AndBitWidth = And.getValueSizeInBits();
12990         if (BitWidth > AndBitWidth) {
12991           APInt Zeros, Ones;
12992           DAG.computeKnownBits(Op0, Zeros, Ones);
12993           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12994             return SDValue();
12995         }
12996         LHS = Op1;
12997         RHS = Op0.getOperand(1);
12998       }
12999   } else if (Op1.getOpcode() == ISD::Constant) {
13000     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13001     uint64_t AndRHSVal = AndRHS->getZExtValue();
13002     SDValue AndLHS = Op0;
13003
13004     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13005       LHS = AndLHS.getOperand(0);
13006       RHS = AndLHS.getOperand(1);
13007     }
13008
13009     // Use BT if the immediate can't be encoded in a TEST instruction.
13010     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13011       LHS = AndLHS;
13012       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13013     }
13014   }
13015
13016   if (LHS.getNode()) {
13017     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13018     // instruction.  Since the shift amount is in-range-or-undefined, we know
13019     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13020     // the encoding for the i16 version is larger than the i32 version.
13021     // Also promote i16 to i32 for performance / code size reason.
13022     if (LHS.getValueType() == MVT::i8 ||
13023         LHS.getValueType() == MVT::i16)
13024       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13025
13026     // If the operand types disagree, extend the shift amount to match.  Since
13027     // BT ignores high bits (like shifts) we can use anyextend.
13028     if (LHS.getValueType() != RHS.getValueType())
13029       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13030
13031     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13032     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13033     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13034                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13035   }
13036
13037   return SDValue();
13038 }
13039
13040 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13041 /// mask CMPs.
13042 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13043                               SDValue &Op1) {
13044   unsigned SSECC;
13045   bool Swap = false;
13046
13047   // SSE Condition code mapping:
13048   //  0 - EQ
13049   //  1 - LT
13050   //  2 - LE
13051   //  3 - UNORD
13052   //  4 - NEQ
13053   //  5 - NLT
13054   //  6 - NLE
13055   //  7 - ORD
13056   switch (SetCCOpcode) {
13057   default: llvm_unreachable("Unexpected SETCC condition");
13058   case ISD::SETOEQ:
13059   case ISD::SETEQ:  SSECC = 0; break;
13060   case ISD::SETOGT:
13061   case ISD::SETGT:  Swap = true; // Fallthrough
13062   case ISD::SETLT:
13063   case ISD::SETOLT: SSECC = 1; break;
13064   case ISD::SETOGE:
13065   case ISD::SETGE:  Swap = true; // Fallthrough
13066   case ISD::SETLE:
13067   case ISD::SETOLE: SSECC = 2; break;
13068   case ISD::SETUO:  SSECC = 3; break;
13069   case ISD::SETUNE:
13070   case ISD::SETNE:  SSECC = 4; break;
13071   case ISD::SETULE: Swap = true; // Fallthrough
13072   case ISD::SETUGE: SSECC = 5; break;
13073   case ISD::SETULT: Swap = true; // Fallthrough
13074   case ISD::SETUGT: SSECC = 6; break;
13075   case ISD::SETO:   SSECC = 7; break;
13076   case ISD::SETUEQ:
13077   case ISD::SETONE: SSECC = 8; break;
13078   }
13079   if (Swap)
13080     std::swap(Op0, Op1);
13081
13082   return SSECC;
13083 }
13084
13085 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13086 // ones, and then concatenate the result back.
13087 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13088   MVT VT = Op.getSimpleValueType();
13089
13090   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13091          "Unsupported value type for operation");
13092
13093   unsigned NumElems = VT.getVectorNumElements();
13094   SDLoc dl(Op);
13095   SDValue CC = Op.getOperand(2);
13096
13097   // Extract the LHS vectors
13098   SDValue LHS = Op.getOperand(0);
13099   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13100   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13101
13102   // Extract the RHS vectors
13103   SDValue RHS = Op.getOperand(1);
13104   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13105   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13106
13107   // Issue the operation on the smaller types and concatenate the result back
13108   MVT EltVT = VT.getVectorElementType();
13109   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13110   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13111                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13112                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13113 }
13114
13115 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13116   SDValue Op0 = Op.getOperand(0);
13117   SDValue Op1 = Op.getOperand(1);
13118   SDValue CC = Op.getOperand(2);
13119   MVT VT = Op.getSimpleValueType();
13120   SDLoc dl(Op);
13121
13122   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13123          "Unexpected type for boolean compare operation");
13124   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13125   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13126                                DAG.getConstant(-1, dl, VT));
13127   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13128                                DAG.getConstant(-1, dl, VT));
13129   switch (SetCCOpcode) {
13130   default: llvm_unreachable("Unexpected SETCC condition");
13131   case ISD::SETNE:
13132     // (x != y) -> ~(x ^ y)
13133     return DAG.getNode(ISD::XOR, dl, VT,
13134                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13135                        DAG.getConstant(-1, dl, VT));
13136   case ISD::SETEQ:
13137     // (x == y) -> (x ^ y)
13138     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13139   case ISD::SETUGT:
13140   case ISD::SETGT:
13141     // (x > y) -> (x & ~y)
13142     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13143   case ISD::SETULT:
13144   case ISD::SETLT:
13145     // (x < y) -> (~x & y)
13146     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13147   case ISD::SETULE:
13148   case ISD::SETLE:
13149     // (x <= y) -> (~x | y)
13150     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13151   case ISD::SETUGE:
13152   case ISD::SETGE:
13153     // (x >=y) -> (x | ~y)
13154     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13155   }
13156 }
13157
13158 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13159                                      const X86Subtarget *Subtarget) {
13160   SDValue Op0 = Op.getOperand(0);
13161   SDValue Op1 = Op.getOperand(1);
13162   SDValue CC = Op.getOperand(2);
13163   MVT VT = Op.getSimpleValueType();
13164   SDLoc dl(Op);
13165
13166   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13167          Op.getValueType().getScalarType() == MVT::i1 &&
13168          "Cannot set masked compare for this operation");
13169
13170   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13171   unsigned  Opc = 0;
13172   bool Unsigned = false;
13173   bool Swap = false;
13174   unsigned SSECC;
13175   switch (SetCCOpcode) {
13176   default: llvm_unreachable("Unexpected SETCC condition");
13177   case ISD::SETNE:  SSECC = 4; break;
13178   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13179   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13180   case ISD::SETLT:  Swap = true; //fall-through
13181   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13182   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13183   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13184   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13185   case ISD::SETULE: Unsigned = true; //fall-through
13186   case ISD::SETLE:  SSECC = 2; break;
13187   }
13188
13189   if (Swap)
13190     std::swap(Op0, Op1);
13191   if (Opc)
13192     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13193   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13194   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13195                      DAG.getConstant(SSECC, dl, MVT::i8));
13196 }
13197
13198 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13199 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13200 /// return an empty value.
13201 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13202 {
13203   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13204   if (!BV)
13205     return SDValue();
13206
13207   MVT VT = Op1.getSimpleValueType();
13208   MVT EVT = VT.getVectorElementType();
13209   unsigned n = VT.getVectorNumElements();
13210   SmallVector<SDValue, 8> ULTOp1;
13211
13212   for (unsigned i = 0; i < n; ++i) {
13213     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13214     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13215       return SDValue();
13216
13217     // Avoid underflow.
13218     APInt Val = Elt->getAPIntValue();
13219     if (Val == 0)
13220       return SDValue();
13221
13222     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13223   }
13224
13225   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13226 }
13227
13228 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13229                            SelectionDAG &DAG) {
13230   SDValue Op0 = Op.getOperand(0);
13231   SDValue Op1 = Op.getOperand(1);
13232   SDValue CC = Op.getOperand(2);
13233   MVT VT = Op.getSimpleValueType();
13234   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13235   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13236   SDLoc dl(Op);
13237
13238   if (isFP) {
13239 #ifndef NDEBUG
13240     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13241     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13242 #endif
13243
13244     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13245     unsigned Opc = X86ISD::CMPP;
13246     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13247       assert(VT.getVectorNumElements() <= 16);
13248       Opc = X86ISD::CMPM;
13249     }
13250     // In the two special cases we can't handle, emit two comparisons.
13251     if (SSECC == 8) {
13252       unsigned CC0, CC1;
13253       unsigned CombineOpc;
13254       if (SetCCOpcode == ISD::SETUEQ) {
13255         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13256       } else {
13257         assert(SetCCOpcode == ISD::SETONE);
13258         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13259       }
13260
13261       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13262                                  DAG.getConstant(CC0, dl, MVT::i8));
13263       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13264                                  DAG.getConstant(CC1, dl, MVT::i8));
13265       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13266     }
13267     // Handle all other FP comparisons here.
13268     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13269                        DAG.getConstant(SSECC, dl, MVT::i8));
13270   }
13271
13272   // Break 256-bit integer vector compare into smaller ones.
13273   if (VT.is256BitVector() && !Subtarget->hasInt256())
13274     return Lower256IntVSETCC(Op, DAG);
13275
13276   EVT OpVT = Op1.getValueType();
13277   if (OpVT.getVectorElementType() == MVT::i1)
13278     return LowerBoolVSETCC_AVX512(Op, DAG);
13279
13280   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13281   if (Subtarget->hasAVX512()) {
13282     if (Op1.getValueType().is512BitVector() ||
13283         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13284         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13285       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13286
13287     // In AVX-512 architecture setcc returns mask with i1 elements,
13288     // But there is no compare instruction for i8 and i16 elements in KNL.
13289     // We are not talking about 512-bit operands in this case, these
13290     // types are illegal.
13291     if (MaskResult &&
13292         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13293          OpVT.getVectorElementType().getSizeInBits() >= 8))
13294       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13295                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13296   }
13297
13298   // We are handling one of the integer comparisons here.  Since SSE only has
13299   // GT and EQ comparisons for integer, swapping operands and multiple
13300   // operations may be required for some comparisons.
13301   unsigned Opc;
13302   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13303   bool Subus = false;
13304
13305   switch (SetCCOpcode) {
13306   default: llvm_unreachable("Unexpected SETCC condition");
13307   case ISD::SETNE:  Invert = true;
13308   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13309   case ISD::SETLT:  Swap = true;
13310   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13311   case ISD::SETGE:  Swap = true;
13312   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13313                     Invert = true; break;
13314   case ISD::SETULT: Swap = true;
13315   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13316                     FlipSigns = true; break;
13317   case ISD::SETUGE: Swap = true;
13318   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13319                     FlipSigns = true; Invert = true; break;
13320   }
13321
13322   // Special case: Use min/max operations for SETULE/SETUGE
13323   MVT VET = VT.getVectorElementType();
13324   bool hasMinMax =
13325        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13326     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13327
13328   if (hasMinMax) {
13329     switch (SetCCOpcode) {
13330     default: break;
13331     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13332     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13333     }
13334
13335     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13336   }
13337
13338   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13339   if (!MinMax && hasSubus) {
13340     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13341     // Op0 u<= Op1:
13342     //   t = psubus Op0, Op1
13343     //   pcmpeq t, <0..0>
13344     switch (SetCCOpcode) {
13345     default: break;
13346     case ISD::SETULT: {
13347       // If the comparison is against a constant we can turn this into a
13348       // setule.  With psubus, setule does not require a swap.  This is
13349       // beneficial because the constant in the register is no longer
13350       // destructed as the destination so it can be hoisted out of a loop.
13351       // Only do this pre-AVX since vpcmp* is no longer destructive.
13352       if (Subtarget->hasAVX())
13353         break;
13354       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13355       if (ULEOp1.getNode()) {
13356         Op1 = ULEOp1;
13357         Subus = true; Invert = false; Swap = false;
13358       }
13359       break;
13360     }
13361     // Psubus is better than flip-sign because it requires no inversion.
13362     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13363     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13364     }
13365
13366     if (Subus) {
13367       Opc = X86ISD::SUBUS;
13368       FlipSigns = false;
13369     }
13370   }
13371
13372   if (Swap)
13373     std::swap(Op0, Op1);
13374
13375   // Check that the operation in question is available (most are plain SSE2,
13376   // but PCMPGTQ and PCMPEQQ have different requirements).
13377   if (VT == MVT::v2i64) {
13378     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13379       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13380
13381       // First cast everything to the right type.
13382       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13383       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13384
13385       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13386       // bits of the inputs before performing those operations. The lower
13387       // compare is always unsigned.
13388       SDValue SB;
13389       if (FlipSigns) {
13390         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13391       } else {
13392         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13393         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13394         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13395                          Sign, Zero, Sign, Zero);
13396       }
13397       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13398       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13399
13400       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13401       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13402       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13403
13404       // Create masks for only the low parts/high parts of the 64 bit integers.
13405       static const int MaskHi[] = { 1, 1, 3, 3 };
13406       static const int MaskLo[] = { 0, 0, 2, 2 };
13407       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13408       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13409       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13410
13411       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13412       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13413
13414       if (Invert)
13415         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13416
13417       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13418     }
13419
13420     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13421       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13422       // pcmpeqd + pshufd + pand.
13423       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13424
13425       // First cast everything to the right type.
13426       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13427       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13428
13429       // Do the compare.
13430       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13431
13432       // Make sure the lower and upper halves are both all-ones.
13433       static const int Mask[] = { 1, 0, 3, 2 };
13434       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13435       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13436
13437       if (Invert)
13438         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13439
13440       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13441     }
13442   }
13443
13444   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13445   // bits of the inputs before performing those operations.
13446   if (FlipSigns) {
13447     EVT EltVT = VT.getVectorElementType();
13448     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13449                                  VT);
13450     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13451     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13452   }
13453
13454   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13455
13456   // If the logical-not of the result is required, perform that now.
13457   if (Invert)
13458     Result = DAG.getNOT(dl, Result, VT);
13459
13460   if (MinMax)
13461     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13462
13463   if (Subus)
13464     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13465                          getZeroVector(VT, Subtarget, DAG, dl));
13466
13467   return Result;
13468 }
13469
13470 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13471
13472   MVT VT = Op.getSimpleValueType();
13473
13474   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13475
13476   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13477          && "SetCC type must be 8-bit or 1-bit integer");
13478   SDValue Op0 = Op.getOperand(0);
13479   SDValue Op1 = Op.getOperand(1);
13480   SDLoc dl(Op);
13481   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13482
13483   // Optimize to BT if possible.
13484   // Lower (X & (1 << N)) == 0 to BT(X, N).
13485   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13486   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13487   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13488       Op1.getOpcode() == ISD::Constant &&
13489       cast<ConstantSDNode>(Op1)->isNullValue() &&
13490       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13491     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13492     if (NewSetCC.getNode()) {
13493       if (VT == MVT::i1)
13494         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13495       return NewSetCC;
13496     }
13497   }
13498
13499   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13500   // these.
13501   if (Op1.getOpcode() == ISD::Constant &&
13502       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13503        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13504       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13505
13506     // If the input is a setcc, then reuse the input setcc or use a new one with
13507     // the inverted condition.
13508     if (Op0.getOpcode() == X86ISD::SETCC) {
13509       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13510       bool Invert = (CC == ISD::SETNE) ^
13511         cast<ConstantSDNode>(Op1)->isNullValue();
13512       if (!Invert)
13513         return Op0;
13514
13515       CCode = X86::GetOppositeBranchCondition(CCode);
13516       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13517                                   DAG.getConstant(CCode, dl, MVT::i8),
13518                                   Op0.getOperand(1));
13519       if (VT == MVT::i1)
13520         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13521       return SetCC;
13522     }
13523   }
13524   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13525       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13526       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13527
13528     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13529     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13530   }
13531
13532   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13533   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13534   if (X86CC == X86::COND_INVALID)
13535     return SDValue();
13536
13537   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13538   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13539   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13540                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13541   if (VT == MVT::i1)
13542     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13543   return SetCC;
13544 }
13545
13546 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13547 static bool isX86LogicalCmp(SDValue Op) {
13548   unsigned Opc = Op.getNode()->getOpcode();
13549   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13550       Opc == X86ISD::SAHF)
13551     return true;
13552   if (Op.getResNo() == 1 &&
13553       (Opc == X86ISD::ADD ||
13554        Opc == X86ISD::SUB ||
13555        Opc == X86ISD::ADC ||
13556        Opc == X86ISD::SBB ||
13557        Opc == X86ISD::SMUL ||
13558        Opc == X86ISD::UMUL ||
13559        Opc == X86ISD::INC ||
13560        Opc == X86ISD::DEC ||
13561        Opc == X86ISD::OR ||
13562        Opc == X86ISD::XOR ||
13563        Opc == X86ISD::AND))
13564     return true;
13565
13566   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13567     return true;
13568
13569   return false;
13570 }
13571
13572 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13573   if (V.getOpcode() != ISD::TRUNCATE)
13574     return false;
13575
13576   SDValue VOp0 = V.getOperand(0);
13577   unsigned InBits = VOp0.getValueSizeInBits();
13578   unsigned Bits = V.getValueSizeInBits();
13579   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13580 }
13581
13582 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13583   bool addTest = true;
13584   SDValue Cond  = Op.getOperand(0);
13585   SDValue Op1 = Op.getOperand(1);
13586   SDValue Op2 = Op.getOperand(2);
13587   SDLoc DL(Op);
13588   EVT VT = Op1.getValueType();
13589   SDValue CC;
13590
13591   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13592   // are available or VBLENDV if AVX is available.
13593   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13594   if (Cond.getOpcode() == ISD::SETCC &&
13595       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13596        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13597       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13598     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13599     int SSECC = translateX86FSETCC(
13600         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13601
13602     if (SSECC != 8) {
13603       if (Subtarget->hasAVX512()) {
13604         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13605                                   DAG.getConstant(SSECC, DL, MVT::i8));
13606         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13607       }
13608
13609       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13610                                 DAG.getConstant(SSECC, DL, MVT::i8));
13611
13612       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13613       // of 3 logic instructions for size savings and potentially speed.
13614       // Unfortunately, there is no scalar form of VBLENDV.
13615
13616       // If either operand is a constant, don't try this. We can expect to
13617       // optimize away at least one of the logic instructions later in that
13618       // case, so that sequence would be faster than a variable blend.
13619
13620       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13621       // uses XMM0 as the selection register. That may need just as many
13622       // instructions as the AND/ANDN/OR sequence due to register moves, so
13623       // don't bother.
13624
13625       if (Subtarget->hasAVX() &&
13626           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13627
13628         // Convert to vectors, do a VSELECT, and convert back to scalar.
13629         // All of the conversions should be optimized away.
13630
13631         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13632         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13633         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13634         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13635
13636         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13637         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13638
13639         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13640
13641         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13642                            VSel, DAG.getIntPtrConstant(0, DL));
13643       }
13644       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13645       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13646       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13647     }
13648   }
13649
13650     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13651       SDValue Op1Scalar;
13652       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13653         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13654       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13655         Op1Scalar = Op1.getOperand(0);
13656       SDValue Op2Scalar;
13657       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13658         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13659       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13660         Op2Scalar = Op2.getOperand(0);
13661       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13662         SDValue newSelect = DAG.getNode(ISD::SELECT, DL, 
13663                                         Op1Scalar.getValueType(),
13664                                         Cond, Op1Scalar, Op2Scalar);
13665         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13666           return DAG.getNode(ISD::BITCAST, DL, VT, newSelect);
13667         SDValue ExtVec = DAG.getNode(ISD::BITCAST, DL, MVT::v8i1, newSelect);
13668         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13669                            DAG.getIntPtrConstant(0, DL));
13670     }
13671   }
13672
13673   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13674     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13675     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13676                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13677     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13678                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13679     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13680                                     Cond, Op1, Op2);
13681     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13682   }
13683
13684   if (Cond.getOpcode() == ISD::SETCC) {
13685     SDValue NewCond = LowerSETCC(Cond, DAG);
13686     if (NewCond.getNode())
13687       Cond = NewCond;
13688   }
13689
13690   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13691   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13692   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13693   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13694   if (Cond.getOpcode() == X86ISD::SETCC &&
13695       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13696       isZero(Cond.getOperand(1).getOperand(1))) {
13697     SDValue Cmp = Cond.getOperand(1);
13698
13699     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13700
13701     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13702         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13703       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13704
13705       SDValue CmpOp0 = Cmp.getOperand(0);
13706       // Apply further optimizations for special cases
13707       // (select (x != 0), -1, 0) -> neg & sbb
13708       // (select (x == 0), 0, -1) -> neg & sbb
13709       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13710         if (YC->isNullValue() &&
13711             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13712           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13713           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13714                                     DAG.getConstant(0, DL,
13715                                                     CmpOp0.getValueType()),
13716                                     CmpOp0);
13717           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13718                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13719                                     SDValue(Neg.getNode(), 1));
13720           return Res;
13721         }
13722
13723       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13724                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13725       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13726
13727       SDValue Res =   // Res = 0 or -1.
13728         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13729                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13730
13731       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13732         Res = DAG.getNOT(DL, Res, Res.getValueType());
13733
13734       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13735       if (!N2C || !N2C->isNullValue())
13736         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13737       return Res;
13738     }
13739   }
13740
13741   // Look past (and (setcc_carry (cmp ...)), 1).
13742   if (Cond.getOpcode() == ISD::AND &&
13743       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13744     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13745     if (C && C->getAPIntValue() == 1)
13746       Cond = Cond.getOperand(0);
13747   }
13748
13749   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13750   // setting operand in place of the X86ISD::SETCC.
13751   unsigned CondOpcode = Cond.getOpcode();
13752   if (CondOpcode == X86ISD::SETCC ||
13753       CondOpcode == X86ISD::SETCC_CARRY) {
13754     CC = Cond.getOperand(0);
13755
13756     SDValue Cmp = Cond.getOperand(1);
13757     unsigned Opc = Cmp.getOpcode();
13758     MVT VT = Op.getSimpleValueType();
13759
13760     bool IllegalFPCMov = false;
13761     if (VT.isFloatingPoint() && !VT.isVector() &&
13762         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13763       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13764
13765     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13766         Opc == X86ISD::BT) { // FIXME
13767       Cond = Cmp;
13768       addTest = false;
13769     }
13770   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13771              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13772              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13773               Cond.getOperand(0).getValueType() != MVT::i8)) {
13774     SDValue LHS = Cond.getOperand(0);
13775     SDValue RHS = Cond.getOperand(1);
13776     unsigned X86Opcode;
13777     unsigned X86Cond;
13778     SDVTList VTs;
13779     switch (CondOpcode) {
13780     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13781     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13782     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13783     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13784     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13785     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13786     default: llvm_unreachable("unexpected overflowing operator");
13787     }
13788     if (CondOpcode == ISD::UMULO)
13789       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13790                           MVT::i32);
13791     else
13792       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13793
13794     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13795
13796     if (CondOpcode == ISD::UMULO)
13797       Cond = X86Op.getValue(2);
13798     else
13799       Cond = X86Op.getValue(1);
13800
13801     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13802     addTest = false;
13803   }
13804
13805   if (addTest) {
13806     // Look pass the truncate if the high bits are known zero.
13807     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13808         Cond = Cond.getOperand(0);
13809
13810     // We know the result of AND is compared against zero. Try to match
13811     // it to BT.
13812     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13813       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13814       if (NewSetCC.getNode()) {
13815         CC = NewSetCC.getOperand(0);
13816         Cond = NewSetCC.getOperand(1);
13817         addTest = false;
13818       }
13819     }
13820   }
13821
13822   if (addTest) {
13823     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13824     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13825   }
13826
13827   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13828   // a <  b ?  0 : -1 -> RES = setcc_carry
13829   // a >= b ? -1 :  0 -> RES = setcc_carry
13830   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13831   if (Cond.getOpcode() == X86ISD::SUB) {
13832     Cond = ConvertCmpIfNecessary(Cond, DAG);
13833     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13834
13835     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13836         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13837       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13838                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13839                                 Cond);
13840       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13841         return DAG.getNOT(DL, Res, Res.getValueType());
13842       return Res;
13843     }
13844   }
13845
13846   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13847   // widen the cmov and push the truncate through. This avoids introducing a new
13848   // branch during isel and doesn't add any extensions.
13849   if (Op.getValueType() == MVT::i8 &&
13850       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13851     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13852     if (T1.getValueType() == T2.getValueType() &&
13853         // Blacklist CopyFromReg to avoid partial register stalls.
13854         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13855       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13856       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13857       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13858     }
13859   }
13860
13861   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13862   // condition is true.
13863   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13864   SDValue Ops[] = { Op2, Op1, CC, Cond };
13865   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13866 }
13867
13868 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13869                                        SelectionDAG &DAG) {
13870   MVT VT = Op->getSimpleValueType(0);
13871   SDValue In = Op->getOperand(0);
13872   MVT InVT = In.getSimpleValueType();
13873   MVT VTElt = VT.getVectorElementType();
13874   MVT InVTElt = InVT.getVectorElementType();
13875   SDLoc dl(Op);
13876
13877   // SKX processor
13878   if ((InVTElt == MVT::i1) &&
13879       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13880         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13881
13882        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13883         VTElt.getSizeInBits() <= 16)) ||
13884
13885        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13886         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13887
13888        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13889         VTElt.getSizeInBits() >= 32))))
13890     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13891
13892   unsigned int NumElts = VT.getVectorNumElements();
13893
13894   if (NumElts != 8 && NumElts != 16)
13895     return SDValue();
13896
13897   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13898     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13899       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13900     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13901   }
13902
13903   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13904   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13905   SDValue NegOne =
13906    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13907                    ExtVT);
13908   SDValue Zero =
13909    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13910
13911   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13912   if (VT.is512BitVector())
13913     return V;
13914   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13915 }
13916
13917 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13918                                 SelectionDAG &DAG) {
13919   MVT VT = Op->getSimpleValueType(0);
13920   SDValue In = Op->getOperand(0);
13921   MVT InVT = In.getSimpleValueType();
13922   SDLoc dl(Op);
13923
13924   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13925     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13926
13927   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13928       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13929       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13930     return SDValue();
13931
13932   if (Subtarget->hasInt256())
13933     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13934
13935   // Optimize vectors in AVX mode
13936   // Sign extend  v8i16 to v8i32 and
13937   //              v4i32 to v4i64
13938   //
13939   // Divide input vector into two parts
13940   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13941   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13942   // concat the vectors to original VT
13943
13944   unsigned NumElems = InVT.getVectorNumElements();
13945   SDValue Undef = DAG.getUNDEF(InVT);
13946
13947   SmallVector<int,8> ShufMask1(NumElems, -1);
13948   for (unsigned i = 0; i != NumElems/2; ++i)
13949     ShufMask1[i] = i;
13950
13951   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13952
13953   SmallVector<int,8> ShufMask2(NumElems, -1);
13954   for (unsigned i = 0; i != NumElems/2; ++i)
13955     ShufMask2[i] = i + NumElems/2;
13956
13957   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13958
13959   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13960                                 VT.getVectorNumElements()/2);
13961
13962   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13963   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13964
13965   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13966 }
13967
13968 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13969 // may emit an illegal shuffle but the expansion is still better than scalar
13970 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13971 // we'll emit a shuffle and a arithmetic shift.
13972 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13973 // TODO: It is possible to support ZExt by zeroing the undef values during
13974 // the shuffle phase or after the shuffle.
13975 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13976                                  SelectionDAG &DAG) {
13977   MVT RegVT = Op.getSimpleValueType();
13978   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13979   assert(RegVT.isInteger() &&
13980          "We only custom lower integer vector sext loads.");
13981
13982   // Nothing useful we can do without SSE2 shuffles.
13983   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13984
13985   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13986   SDLoc dl(Ld);
13987   EVT MemVT = Ld->getMemoryVT();
13988   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13989   unsigned RegSz = RegVT.getSizeInBits();
13990
13991   ISD::LoadExtType Ext = Ld->getExtensionType();
13992
13993   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13994          && "Only anyext and sext are currently implemented.");
13995   assert(MemVT != RegVT && "Cannot extend to the same type");
13996   assert(MemVT.isVector() && "Must load a vector from memory");
13997
13998   unsigned NumElems = RegVT.getVectorNumElements();
13999   unsigned MemSz = MemVT.getSizeInBits();
14000   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14001
14002   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14003     // The only way in which we have a legal 256-bit vector result but not the
14004     // integer 256-bit operations needed to directly lower a sextload is if we
14005     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14006     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14007     // correctly legalized. We do this late to allow the canonical form of
14008     // sextload to persist throughout the rest of the DAG combiner -- it wants
14009     // to fold together any extensions it can, and so will fuse a sign_extend
14010     // of an sextload into a sextload targeting a wider value.
14011     SDValue Load;
14012     if (MemSz == 128) {
14013       // Just switch this to a normal load.
14014       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14015                                        "it must be a legal 128-bit vector "
14016                                        "type!");
14017       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14018                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14019                   Ld->isInvariant(), Ld->getAlignment());
14020     } else {
14021       assert(MemSz < 128 &&
14022              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14023       // Do an sext load to a 128-bit vector type. We want to use the same
14024       // number of elements, but elements half as wide. This will end up being
14025       // recursively lowered by this routine, but will succeed as we definitely
14026       // have all the necessary features if we're using AVX1.
14027       EVT HalfEltVT =
14028           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14029       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14030       Load =
14031           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14032                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14033                          Ld->isNonTemporal(), Ld->isInvariant(),
14034                          Ld->getAlignment());
14035     }
14036
14037     // Replace chain users with the new chain.
14038     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14039     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14040
14041     // Finally, do a normal sign-extend to the desired register.
14042     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14043   }
14044
14045   // All sizes must be a power of two.
14046   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14047          "Non-power-of-two elements are not custom lowered!");
14048
14049   // Attempt to load the original value using scalar loads.
14050   // Find the largest scalar type that divides the total loaded size.
14051   MVT SclrLoadTy = MVT::i8;
14052   for (MVT Tp : MVT::integer_valuetypes()) {
14053     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14054       SclrLoadTy = Tp;
14055     }
14056   }
14057
14058   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14059   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14060       (64 <= MemSz))
14061     SclrLoadTy = MVT::f64;
14062
14063   // Calculate the number of scalar loads that we need to perform
14064   // in order to load our vector from memory.
14065   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14066
14067   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14068          "Can only lower sext loads with a single scalar load!");
14069
14070   unsigned loadRegZize = RegSz;
14071   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14072     loadRegZize = 128;
14073
14074   // Represent our vector as a sequence of elements which are the
14075   // largest scalar that we can load.
14076   EVT LoadUnitVecVT = EVT::getVectorVT(
14077       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14078
14079   // Represent the data using the same element type that is stored in
14080   // memory. In practice, we ''widen'' MemVT.
14081   EVT WideVecVT =
14082       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14083                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14084
14085   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14086          "Invalid vector type");
14087
14088   // We can't shuffle using an illegal type.
14089   assert(TLI.isTypeLegal(WideVecVT) &&
14090          "We only lower types that form legal widened vector types");
14091
14092   SmallVector<SDValue, 8> Chains;
14093   SDValue Ptr = Ld->getBasePtr();
14094   SDValue Increment =
14095       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14096   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14097
14098   for (unsigned i = 0; i < NumLoads; ++i) {
14099     // Perform a single load.
14100     SDValue ScalarLoad =
14101         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14102                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14103                     Ld->getAlignment());
14104     Chains.push_back(ScalarLoad.getValue(1));
14105     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14106     // another round of DAGCombining.
14107     if (i == 0)
14108       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14109     else
14110       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14111                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14112
14113     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14114   }
14115
14116   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14117
14118   // Bitcast the loaded value to a vector of the original element type, in
14119   // the size of the target vector type.
14120   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14121   unsigned SizeRatio = RegSz / MemSz;
14122
14123   if (Ext == ISD::SEXTLOAD) {
14124     // If we have SSE4.1, we can directly emit a VSEXT node.
14125     if (Subtarget->hasSSE41()) {
14126       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14127       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14128       return Sext;
14129     }
14130
14131     // Otherwise we'll shuffle the small elements in the high bits of the
14132     // larger type and perform an arithmetic shift. If the shift is not legal
14133     // it's better to scalarize.
14134     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14135            "We can't implement a sext load without an arithmetic right shift!");
14136
14137     // Redistribute the loaded elements into the different locations.
14138     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14139     for (unsigned i = 0; i != NumElems; ++i)
14140       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14141
14142     SDValue Shuff = DAG.getVectorShuffle(
14143         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14144
14145     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14146
14147     // Build the arithmetic shift.
14148     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14149                    MemVT.getVectorElementType().getSizeInBits();
14150     Shuff =
14151         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14152                     DAG.getConstant(Amt, dl, RegVT));
14153
14154     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14155     return Shuff;
14156   }
14157
14158   // Redistribute the loaded elements into the different locations.
14159   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14160   for (unsigned i = 0; i != NumElems; ++i)
14161     ShuffleVec[i * SizeRatio] = i;
14162
14163   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14164                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14165
14166   // Bitcast to the requested type.
14167   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14168   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14169   return Shuff;
14170 }
14171
14172 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14173 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14174 // from the AND / OR.
14175 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14176   Opc = Op.getOpcode();
14177   if (Opc != ISD::OR && Opc != ISD::AND)
14178     return false;
14179   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14180           Op.getOperand(0).hasOneUse() &&
14181           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14182           Op.getOperand(1).hasOneUse());
14183 }
14184
14185 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14186 // 1 and that the SETCC node has a single use.
14187 static bool isXor1OfSetCC(SDValue Op) {
14188   if (Op.getOpcode() != ISD::XOR)
14189     return false;
14190   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14191   if (N1C && N1C->getAPIntValue() == 1) {
14192     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14193       Op.getOperand(0).hasOneUse();
14194   }
14195   return false;
14196 }
14197
14198 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14199   bool addTest = true;
14200   SDValue Chain = Op.getOperand(0);
14201   SDValue Cond  = Op.getOperand(1);
14202   SDValue Dest  = Op.getOperand(2);
14203   SDLoc dl(Op);
14204   SDValue CC;
14205   bool Inverted = false;
14206
14207   if (Cond.getOpcode() == ISD::SETCC) {
14208     // Check for setcc([su]{add,sub,mul}o == 0).
14209     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14210         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14211         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14212         Cond.getOperand(0).getResNo() == 1 &&
14213         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14214          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14215          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14216          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14217          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14218          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14219       Inverted = true;
14220       Cond = Cond.getOperand(0);
14221     } else {
14222       SDValue NewCond = LowerSETCC(Cond, DAG);
14223       if (NewCond.getNode())
14224         Cond = NewCond;
14225     }
14226   }
14227 #if 0
14228   // FIXME: LowerXALUO doesn't handle these!!
14229   else if (Cond.getOpcode() == X86ISD::ADD  ||
14230            Cond.getOpcode() == X86ISD::SUB  ||
14231            Cond.getOpcode() == X86ISD::SMUL ||
14232            Cond.getOpcode() == X86ISD::UMUL)
14233     Cond = LowerXALUO(Cond, DAG);
14234 #endif
14235
14236   // Look pass (and (setcc_carry (cmp ...)), 1).
14237   if (Cond.getOpcode() == ISD::AND &&
14238       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14239     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14240     if (C && C->getAPIntValue() == 1)
14241       Cond = Cond.getOperand(0);
14242   }
14243
14244   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14245   // setting operand in place of the X86ISD::SETCC.
14246   unsigned CondOpcode = Cond.getOpcode();
14247   if (CondOpcode == X86ISD::SETCC ||
14248       CondOpcode == X86ISD::SETCC_CARRY) {
14249     CC = Cond.getOperand(0);
14250
14251     SDValue Cmp = Cond.getOperand(1);
14252     unsigned Opc = Cmp.getOpcode();
14253     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14254     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14255       Cond = Cmp;
14256       addTest = false;
14257     } else {
14258       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14259       default: break;
14260       case X86::COND_O:
14261       case X86::COND_B:
14262         // These can only come from an arithmetic instruction with overflow,
14263         // e.g. SADDO, UADDO.
14264         Cond = Cond.getNode()->getOperand(1);
14265         addTest = false;
14266         break;
14267       }
14268     }
14269   }
14270   CondOpcode = Cond.getOpcode();
14271   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14272       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14273       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14274        Cond.getOperand(0).getValueType() != MVT::i8)) {
14275     SDValue LHS = Cond.getOperand(0);
14276     SDValue RHS = Cond.getOperand(1);
14277     unsigned X86Opcode;
14278     unsigned X86Cond;
14279     SDVTList VTs;
14280     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14281     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14282     // X86ISD::INC).
14283     switch (CondOpcode) {
14284     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14285     case ISD::SADDO:
14286       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14287         if (C->isOne()) {
14288           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14289           break;
14290         }
14291       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14292     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14293     case ISD::SSUBO:
14294       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14295         if (C->isOne()) {
14296           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14297           break;
14298         }
14299       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14300     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14301     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14302     default: llvm_unreachable("unexpected overflowing operator");
14303     }
14304     if (Inverted)
14305       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14306     if (CondOpcode == ISD::UMULO)
14307       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14308                           MVT::i32);
14309     else
14310       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14311
14312     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14313
14314     if (CondOpcode == ISD::UMULO)
14315       Cond = X86Op.getValue(2);
14316     else
14317       Cond = X86Op.getValue(1);
14318
14319     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14320     addTest = false;
14321   } else {
14322     unsigned CondOpc;
14323     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14324       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14325       if (CondOpc == ISD::OR) {
14326         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14327         // two branches instead of an explicit OR instruction with a
14328         // separate test.
14329         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14330             isX86LogicalCmp(Cmp)) {
14331           CC = Cond.getOperand(0).getOperand(0);
14332           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14333                               Chain, Dest, CC, Cmp);
14334           CC = Cond.getOperand(1).getOperand(0);
14335           Cond = Cmp;
14336           addTest = false;
14337         }
14338       } else { // ISD::AND
14339         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14340         // two branches instead of an explicit AND instruction with a
14341         // separate test. However, we only do this if this block doesn't
14342         // have a fall-through edge, because this requires an explicit
14343         // jmp when the condition is false.
14344         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14345             isX86LogicalCmp(Cmp) &&
14346             Op.getNode()->hasOneUse()) {
14347           X86::CondCode CCode =
14348             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14349           CCode = X86::GetOppositeBranchCondition(CCode);
14350           CC = DAG.getConstant(CCode, dl, MVT::i8);
14351           SDNode *User = *Op.getNode()->use_begin();
14352           // Look for an unconditional branch following this conditional branch.
14353           // We need this because we need to reverse the successors in order
14354           // to implement FCMP_OEQ.
14355           if (User->getOpcode() == ISD::BR) {
14356             SDValue FalseBB = User->getOperand(1);
14357             SDNode *NewBR =
14358               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14359             assert(NewBR == User);
14360             (void)NewBR;
14361             Dest = FalseBB;
14362
14363             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14364                                 Chain, Dest, CC, Cmp);
14365             X86::CondCode CCode =
14366               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14367             CCode = X86::GetOppositeBranchCondition(CCode);
14368             CC = DAG.getConstant(CCode, dl, MVT::i8);
14369             Cond = Cmp;
14370             addTest = false;
14371           }
14372         }
14373       }
14374     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14375       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14376       // It should be transformed during dag combiner except when the condition
14377       // is set by a arithmetics with overflow node.
14378       X86::CondCode CCode =
14379         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14380       CCode = X86::GetOppositeBranchCondition(CCode);
14381       CC = DAG.getConstant(CCode, dl, MVT::i8);
14382       Cond = Cond.getOperand(0).getOperand(1);
14383       addTest = false;
14384     } else if (Cond.getOpcode() == ISD::SETCC &&
14385                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14386       // For FCMP_OEQ, we can emit
14387       // two branches instead of an explicit AND instruction with a
14388       // separate test. However, we only do this if this block doesn't
14389       // have a fall-through edge, because this requires an explicit
14390       // jmp when the condition is false.
14391       if (Op.getNode()->hasOneUse()) {
14392         SDNode *User = *Op.getNode()->use_begin();
14393         // Look for an unconditional branch following this conditional branch.
14394         // We need this because we need to reverse the successors in order
14395         // to implement FCMP_OEQ.
14396         if (User->getOpcode() == ISD::BR) {
14397           SDValue FalseBB = User->getOperand(1);
14398           SDNode *NewBR =
14399             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14400           assert(NewBR == User);
14401           (void)NewBR;
14402           Dest = FalseBB;
14403
14404           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14405                                     Cond.getOperand(0), Cond.getOperand(1));
14406           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14407           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14408           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14409                               Chain, Dest, CC, Cmp);
14410           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14411           Cond = Cmp;
14412           addTest = false;
14413         }
14414       }
14415     } else if (Cond.getOpcode() == ISD::SETCC &&
14416                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14417       // For FCMP_UNE, we can emit
14418       // two branches instead of an explicit AND instruction with a
14419       // separate test. However, we only do this if this block doesn't
14420       // have a fall-through edge, because this requires an explicit
14421       // jmp when the condition is false.
14422       if (Op.getNode()->hasOneUse()) {
14423         SDNode *User = *Op.getNode()->use_begin();
14424         // Look for an unconditional branch following this conditional branch.
14425         // We need this because we need to reverse the successors in order
14426         // to implement FCMP_UNE.
14427         if (User->getOpcode() == ISD::BR) {
14428           SDValue FalseBB = User->getOperand(1);
14429           SDNode *NewBR =
14430             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14431           assert(NewBR == User);
14432           (void)NewBR;
14433
14434           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14435                                     Cond.getOperand(0), Cond.getOperand(1));
14436           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14437           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14438           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14439                               Chain, Dest, CC, Cmp);
14440           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14441           Cond = Cmp;
14442           addTest = false;
14443           Dest = FalseBB;
14444         }
14445       }
14446     }
14447   }
14448
14449   if (addTest) {
14450     // Look pass the truncate if the high bits are known zero.
14451     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14452         Cond = Cond.getOperand(0);
14453
14454     // We know the result of AND is compared against zero. Try to match
14455     // it to BT.
14456     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14457       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14458       if (NewSetCC.getNode()) {
14459         CC = NewSetCC.getOperand(0);
14460         Cond = NewSetCC.getOperand(1);
14461         addTest = false;
14462       }
14463     }
14464   }
14465
14466   if (addTest) {
14467     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14468     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14469     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14470   }
14471   Cond = ConvertCmpIfNecessary(Cond, DAG);
14472   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14473                      Chain, Dest, CC, Cond);
14474 }
14475
14476 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14477 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14478 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14479 // that the guard pages used by the OS virtual memory manager are allocated in
14480 // correct sequence.
14481 SDValue
14482 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14483                                            SelectionDAG &DAG) const {
14484   MachineFunction &MF = DAG.getMachineFunction();
14485   bool SplitStack = MF.shouldSplitStack();
14486   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14487                SplitStack;
14488   SDLoc dl(Op);
14489
14490   if (!Lower) {
14491     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14492     SDNode* Node = Op.getNode();
14493
14494     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14495     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14496         " not tell us which reg is the stack pointer!");
14497     EVT VT = Node->getValueType(0);
14498     SDValue Tmp1 = SDValue(Node, 0);
14499     SDValue Tmp2 = SDValue(Node, 1);
14500     SDValue Tmp3 = Node->getOperand(2);
14501     SDValue Chain = Tmp1.getOperand(0);
14502
14503     // Chain the dynamic stack allocation so that it doesn't modify the stack
14504     // pointer when other instructions are using the stack.
14505     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14506         SDLoc(Node));
14507
14508     SDValue Size = Tmp2.getOperand(1);
14509     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14510     Chain = SP.getValue(1);
14511     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14512     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14513     unsigned StackAlign = TFI.getStackAlignment();
14514     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14515     if (Align > StackAlign)
14516       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14517           DAG.getConstant(-(uint64_t)Align, dl, VT));
14518     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14519
14520     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14521         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14522         SDLoc(Node));
14523
14524     SDValue Ops[2] = { Tmp1, Tmp2 };
14525     return DAG.getMergeValues(Ops, dl);
14526   }
14527
14528   // Get the inputs.
14529   SDValue Chain = Op.getOperand(0);
14530   SDValue Size  = Op.getOperand(1);
14531   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14532   EVT VT = Op.getNode()->getValueType(0);
14533
14534   bool Is64Bit = Subtarget->is64Bit();
14535   EVT SPTy = getPointerTy();
14536
14537   if (SplitStack) {
14538     MachineRegisterInfo &MRI = MF.getRegInfo();
14539
14540     if (Is64Bit) {
14541       // The 64 bit implementation of segmented stacks needs to clobber both r10
14542       // r11. This makes it impossible to use it along with nested parameters.
14543       const Function *F = MF.getFunction();
14544
14545       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14546            I != E; ++I)
14547         if (I->hasNestAttr())
14548           report_fatal_error("Cannot use segmented stacks with functions that "
14549                              "have nested arguments.");
14550     }
14551
14552     const TargetRegisterClass *AddrRegClass =
14553       getRegClassFor(getPointerTy());
14554     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14555     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14556     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14557                                 DAG.getRegister(Vreg, SPTy));
14558     SDValue Ops1[2] = { Value, Chain };
14559     return DAG.getMergeValues(Ops1, dl);
14560   } else {
14561     SDValue Flag;
14562     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14563
14564     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14565     Flag = Chain.getValue(1);
14566     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14567
14568     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14569
14570     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14571     unsigned SPReg = RegInfo->getStackRegister();
14572     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14573     Chain = SP.getValue(1);
14574
14575     if (Align) {
14576       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14577                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14578       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14579     }
14580
14581     SDValue Ops1[2] = { SP, Chain };
14582     return DAG.getMergeValues(Ops1, dl);
14583   }
14584 }
14585
14586 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14587   MachineFunction &MF = DAG.getMachineFunction();
14588   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14589
14590   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14591   SDLoc DL(Op);
14592
14593   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14594     // vastart just stores the address of the VarArgsFrameIndex slot into the
14595     // memory location argument.
14596     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14597                                    getPointerTy());
14598     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14599                         MachinePointerInfo(SV), false, false, 0);
14600   }
14601
14602   // __va_list_tag:
14603   //   gp_offset         (0 - 6 * 8)
14604   //   fp_offset         (48 - 48 + 8 * 16)
14605   //   overflow_arg_area (point to parameters coming in memory).
14606   //   reg_save_area
14607   SmallVector<SDValue, 8> MemOps;
14608   SDValue FIN = Op.getOperand(1);
14609   // Store gp_offset
14610   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14611                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14612                                                DL, MVT::i32),
14613                                FIN, MachinePointerInfo(SV), false, false, 0);
14614   MemOps.push_back(Store);
14615
14616   // Store fp_offset
14617   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14618                     FIN, DAG.getIntPtrConstant(4, DL));
14619   Store = DAG.getStore(Op.getOperand(0), DL,
14620                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14621                                        MVT::i32),
14622                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14623   MemOps.push_back(Store);
14624
14625   // Store ptr to overflow_arg_area
14626   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14627                     FIN, DAG.getIntPtrConstant(4, DL));
14628   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14629                                     getPointerTy());
14630   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14631                        MachinePointerInfo(SV, 8),
14632                        false, false, 0);
14633   MemOps.push_back(Store);
14634
14635   // Store ptr to reg_save_area.
14636   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14637                     FIN, DAG.getIntPtrConstant(8, DL));
14638   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14639                                     getPointerTy());
14640   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14641                        MachinePointerInfo(SV, 16), false, false, 0);
14642   MemOps.push_back(Store);
14643   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14644 }
14645
14646 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14647   assert(Subtarget->is64Bit() &&
14648          "LowerVAARG only handles 64-bit va_arg!");
14649   assert((Subtarget->isTargetLinux() ||
14650           Subtarget->isTargetDarwin()) &&
14651           "Unhandled target in LowerVAARG");
14652   assert(Op.getNode()->getNumOperands() == 4);
14653   SDValue Chain = Op.getOperand(0);
14654   SDValue SrcPtr = Op.getOperand(1);
14655   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14656   unsigned Align = Op.getConstantOperandVal(3);
14657   SDLoc dl(Op);
14658
14659   EVT ArgVT = Op.getNode()->getValueType(0);
14660   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14661   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14662   uint8_t ArgMode;
14663
14664   // Decide which area this value should be read from.
14665   // TODO: Implement the AMD64 ABI in its entirety. This simple
14666   // selection mechanism works only for the basic types.
14667   if (ArgVT == MVT::f80) {
14668     llvm_unreachable("va_arg for f80 not yet implemented");
14669   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14670     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14671   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14672     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14673   } else {
14674     llvm_unreachable("Unhandled argument type in LowerVAARG");
14675   }
14676
14677   if (ArgMode == 2) {
14678     // Sanity Check: Make sure using fp_offset makes sense.
14679     assert(!Subtarget->useSoftFloat() &&
14680            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14681                Attribute::NoImplicitFloat)) &&
14682            Subtarget->hasSSE1());
14683   }
14684
14685   // Insert VAARG_64 node into the DAG
14686   // VAARG_64 returns two values: Variable Argument Address, Chain
14687   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14688                        DAG.getConstant(ArgMode, dl, MVT::i8),
14689                        DAG.getConstant(Align, dl, MVT::i32)};
14690   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14691   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14692                                           VTs, InstOps, MVT::i64,
14693                                           MachinePointerInfo(SV),
14694                                           /*Align=*/0,
14695                                           /*Volatile=*/false,
14696                                           /*ReadMem=*/true,
14697                                           /*WriteMem=*/true);
14698   Chain = VAARG.getValue(1);
14699
14700   // Load the next argument and return it
14701   return DAG.getLoad(ArgVT, dl,
14702                      Chain,
14703                      VAARG,
14704                      MachinePointerInfo(),
14705                      false, false, false, 0);
14706 }
14707
14708 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14709                            SelectionDAG &DAG) {
14710   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14711   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14712   SDValue Chain = Op.getOperand(0);
14713   SDValue DstPtr = Op.getOperand(1);
14714   SDValue SrcPtr = Op.getOperand(2);
14715   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14716   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14717   SDLoc DL(Op);
14718
14719   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14720                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14721                        false, false,
14722                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14723 }
14724
14725 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14726 // amount is a constant. Takes immediate version of shift as input.
14727 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14728                                           SDValue SrcOp, uint64_t ShiftAmt,
14729                                           SelectionDAG &DAG) {
14730   MVT ElementType = VT.getVectorElementType();
14731
14732   // Fold this packed shift into its first operand if ShiftAmt is 0.
14733   if (ShiftAmt == 0)
14734     return SrcOp;
14735
14736   // Check for ShiftAmt >= element width
14737   if (ShiftAmt >= ElementType.getSizeInBits()) {
14738     if (Opc == X86ISD::VSRAI)
14739       ShiftAmt = ElementType.getSizeInBits() - 1;
14740     else
14741       return DAG.getConstant(0, dl, VT);
14742   }
14743
14744   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14745          && "Unknown target vector shift-by-constant node");
14746
14747   // Fold this packed vector shift into a build vector if SrcOp is a
14748   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14749   if (VT == SrcOp.getSimpleValueType() &&
14750       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14751     SmallVector<SDValue, 8> Elts;
14752     unsigned NumElts = SrcOp->getNumOperands();
14753     ConstantSDNode *ND;
14754
14755     switch(Opc) {
14756     default: llvm_unreachable(nullptr);
14757     case X86ISD::VSHLI:
14758       for (unsigned i=0; i!=NumElts; ++i) {
14759         SDValue CurrentOp = SrcOp->getOperand(i);
14760         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14761           Elts.push_back(CurrentOp);
14762           continue;
14763         }
14764         ND = cast<ConstantSDNode>(CurrentOp);
14765         const APInt &C = ND->getAPIntValue();
14766         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14767       }
14768       break;
14769     case X86ISD::VSRLI:
14770       for (unsigned i=0; i!=NumElts; ++i) {
14771         SDValue CurrentOp = SrcOp->getOperand(i);
14772         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14773           Elts.push_back(CurrentOp);
14774           continue;
14775         }
14776         ND = cast<ConstantSDNode>(CurrentOp);
14777         const APInt &C = ND->getAPIntValue();
14778         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14779       }
14780       break;
14781     case X86ISD::VSRAI:
14782       for (unsigned i=0; i!=NumElts; ++i) {
14783         SDValue CurrentOp = SrcOp->getOperand(i);
14784         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14785           Elts.push_back(CurrentOp);
14786           continue;
14787         }
14788         ND = cast<ConstantSDNode>(CurrentOp);
14789         const APInt &C = ND->getAPIntValue();
14790         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14791       }
14792       break;
14793     }
14794
14795     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14796   }
14797
14798   return DAG.getNode(Opc, dl, VT, SrcOp,
14799                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14800 }
14801
14802 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14803 // may or may not be a constant. Takes immediate version of shift as input.
14804 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14805                                    SDValue SrcOp, SDValue ShAmt,
14806                                    SelectionDAG &DAG) {
14807   MVT SVT = ShAmt.getSimpleValueType();
14808   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14809
14810   // Catch shift-by-constant.
14811   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14812     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14813                                       CShAmt->getZExtValue(), DAG);
14814
14815   // Change opcode to non-immediate version
14816   switch (Opc) {
14817     default: llvm_unreachable("Unknown target vector shift node");
14818     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14819     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14820     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14821   }
14822
14823   const X86Subtarget &Subtarget =
14824       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14825   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14826       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14827     // Let the shuffle legalizer expand this shift amount node.
14828     SDValue Op0 = ShAmt.getOperand(0);
14829     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14830     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14831   } else {
14832     // Need to build a vector containing shift amount.
14833     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14834     SmallVector<SDValue, 4> ShOps;
14835     ShOps.push_back(ShAmt);
14836     if (SVT == MVT::i32) {
14837       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14838       ShOps.push_back(DAG.getUNDEF(SVT));
14839     }
14840     ShOps.push_back(DAG.getUNDEF(SVT));
14841
14842     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14843     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14844   }
14845
14846   // The return type has to be a 128-bit type with the same element
14847   // type as the input type.
14848   MVT EltVT = VT.getVectorElementType();
14849   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14850
14851   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14852   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14853 }
14854
14855 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14856 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14857 /// necessary casting for \p Mask when lowering masking intrinsics.
14858 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14859                                     SDValue PreservedSrc,
14860                                     const X86Subtarget *Subtarget,
14861                                     SelectionDAG &DAG) {
14862     EVT VT = Op.getValueType();
14863     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14864                                   MVT::i1, VT.getVectorNumElements());
14865     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14866                                      Mask.getValueType().getSizeInBits());
14867     SDLoc dl(Op);
14868
14869     assert(MaskVT.isSimple() && "invalid mask type");
14870
14871     if (isAllOnes(Mask))
14872       return Op;
14873
14874     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14875     // are extracted by EXTRACT_SUBVECTOR.
14876     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14877                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14878                               DAG.getIntPtrConstant(0, dl));
14879
14880     switch (Op.getOpcode()) {
14881       default: break;
14882       case X86ISD::PCMPEQM:
14883       case X86ISD::PCMPGTM:
14884       case X86ISD::CMPM:
14885       case X86ISD::CMPMU:
14886         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14887     }
14888     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14889       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14890     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14891 }
14892
14893 /// \brief Creates an SDNode for a predicated scalar operation.
14894 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14895 /// The mask is comming as MVT::i8 and it should be truncated
14896 /// to MVT::i1 while lowering masking intrinsics.
14897 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14898 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14899 /// a scalar instruction.
14900 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14901                                     SDValue PreservedSrc,
14902                                     const X86Subtarget *Subtarget,
14903                                     SelectionDAG &DAG) {
14904     if (isAllOnes(Mask))
14905       return Op;
14906
14907     EVT VT = Op.getValueType();
14908     SDLoc dl(Op);
14909     // The mask should be of type MVT::i1
14910     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14911
14912     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14913       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14914     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14915 }
14916
14917 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14918                                        SelectionDAG &DAG) {
14919   SDLoc dl(Op);
14920   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14921   EVT VT = Op.getValueType();
14922   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14923   if (IntrData) {
14924     switch(IntrData->Type) {
14925     case INTR_TYPE_1OP:
14926       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14927     case INTR_TYPE_2OP:
14928       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14929         Op.getOperand(2));
14930     case INTR_TYPE_3OP:
14931       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14932         Op.getOperand(2), Op.getOperand(3));
14933     case INTR_TYPE_1OP_MASK_RM: {
14934       SDValue Src = Op.getOperand(1);
14935       SDValue Src0 = Op.getOperand(2);
14936       SDValue Mask = Op.getOperand(3);
14937       SDValue RoundingMode = Op.getOperand(4);
14938       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14939                                               RoundingMode),
14940                                   Mask, Src0, Subtarget, DAG);
14941     }
14942     case INTR_TYPE_SCALAR_MASK_RM: {
14943       SDValue Src1 = Op.getOperand(1);
14944       SDValue Src2 = Op.getOperand(2);
14945       SDValue Src0 = Op.getOperand(3);
14946       SDValue Mask = Op.getOperand(4);
14947       // There are 2 kinds of intrinsics in this group:
14948       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
14949       // (2) With rounding mode and sae - 7 operands.
14950       if (Op.getNumOperands() == 6) {
14951         SDValue Sae  = Op.getOperand(5);
14952         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
14953         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
14954                                                 Sae),
14955                                     Mask, Src0, Subtarget, DAG);
14956       }
14957       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14958       SDValue RoundingMode  = Op.getOperand(5);
14959       SDValue Sae  = Op.getOperand(6);
14960       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14961                                               RoundingMode, Sae),
14962                                   Mask, Src0, Subtarget, DAG);
14963     }
14964     case INTR_TYPE_2OP_MASK: {
14965       SDValue Src1 = Op.getOperand(1);
14966       SDValue Src2 = Op.getOperand(2);
14967       SDValue PassThru = Op.getOperand(3);
14968       SDValue Mask = Op.getOperand(4);
14969       // We specify 2 possible opcodes for intrinsics with rounding modes.
14970       // First, we check if the intrinsic may have non-default rounding mode,
14971       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14972       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14973       if (IntrWithRoundingModeOpcode != 0) {
14974         SDValue Rnd = Op.getOperand(5);
14975         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14976         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14977           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14978                                       dl, Op.getValueType(),
14979                                       Src1, Src2, Rnd),
14980                                       Mask, PassThru, Subtarget, DAG);
14981         }
14982       }
14983       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14984                                               Src1,Src2),
14985                                   Mask, PassThru, Subtarget, DAG);
14986     }
14987     case FMA_OP_MASK: {
14988       SDValue Src1 = Op.getOperand(1);
14989       SDValue Src2 = Op.getOperand(2);
14990       SDValue Src3 = Op.getOperand(3);
14991       SDValue Mask = Op.getOperand(4);
14992       // We specify 2 possible opcodes for intrinsics with rounding modes.
14993       // First, we check if the intrinsic may have non-default rounding mode,
14994       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14995       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14996       if (IntrWithRoundingModeOpcode != 0) {
14997         SDValue Rnd = Op.getOperand(5);
14998         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14999             X86::STATIC_ROUNDING::CUR_DIRECTION)
15000           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15001                                                   dl, Op.getValueType(),
15002                                                   Src1, Src2, Src3, Rnd),
15003                                       Mask, Src1, Subtarget, DAG);
15004       }
15005       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15006                                               dl, Op.getValueType(),
15007                                               Src1, Src2, Src3),
15008                                   Mask, Src1, Subtarget, DAG);
15009     }
15010     case CMP_MASK:
15011     case CMP_MASK_CC: {
15012       // Comparison intrinsics with masks.
15013       // Example of transformation:
15014       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15015       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15016       // (i8 (bitcast
15017       //   (v8i1 (insert_subvector undef,
15018       //           (v2i1 (and (PCMPEQM %a, %b),
15019       //                      (extract_subvector
15020       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15021       EVT VT = Op.getOperand(1).getValueType();
15022       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15023                                     VT.getVectorNumElements());
15024       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15025       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15026                                        Mask.getValueType().getSizeInBits());
15027       SDValue Cmp;
15028       if (IntrData->Type == CMP_MASK_CC) {
15029         SDValue CC = Op.getOperand(3);
15030         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15031         // We specify 2 possible opcodes for intrinsics with rounding modes.
15032         // First, we check if the intrinsic may have non-default rounding mode,
15033         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15034         if (IntrData->Opc1 != 0) {
15035           SDValue Rnd = Op.getOperand(5);
15036           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15037               X86::STATIC_ROUNDING::CUR_DIRECTION)
15038             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15039                               Op.getOperand(2), CC, Rnd);
15040         }
15041         //default rounding mode
15042         if(!Cmp.getNode())
15043             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15044                               Op.getOperand(2), CC);
15045
15046       } else {
15047         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15048         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15049                           Op.getOperand(2));
15050       }
15051       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15052                                              DAG.getTargetConstant(0, dl,
15053                                                                    MaskVT),
15054                                              Subtarget, DAG);
15055       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15056                                 DAG.getUNDEF(BitcastVT), CmpMask,
15057                                 DAG.getIntPtrConstant(0, dl));
15058       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
15059     }
15060     case COMI: { // Comparison intrinsics
15061       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15062       SDValue LHS = Op.getOperand(1);
15063       SDValue RHS = Op.getOperand(2);
15064       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15065       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15066       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15067       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15068                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15069       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15070     }
15071     case VSHIFT:
15072       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15073                                  Op.getOperand(1), Op.getOperand(2), DAG);
15074     case VSHIFT_MASK:
15075       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15076                                                       Op.getSimpleValueType(),
15077                                                       Op.getOperand(1),
15078                                                       Op.getOperand(2), DAG),
15079                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15080                                   DAG);
15081     case COMPRESS_EXPAND_IN_REG: {
15082       SDValue Mask = Op.getOperand(3);
15083       SDValue DataToCompress = Op.getOperand(1);
15084       SDValue PassThru = Op.getOperand(2);
15085       if (isAllOnes(Mask)) // return data as is
15086         return Op.getOperand(1);
15087       EVT VT = Op.getValueType();
15088       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15089                                     VT.getVectorNumElements());
15090       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15091                                        Mask.getValueType().getSizeInBits());
15092       SDLoc dl(Op);
15093       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15094                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15095                                   DAG.getIntPtrConstant(0, dl));
15096
15097       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15098                          PassThru);
15099     }
15100     case BLEND: {
15101       SDValue Mask = Op.getOperand(3);
15102       EVT VT = Op.getValueType();
15103       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15104                                     VT.getVectorNumElements());
15105       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15106                                        Mask.getValueType().getSizeInBits());
15107       SDLoc dl(Op);
15108       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15109                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15110                                   DAG.getIntPtrConstant(0, dl));
15111       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15112                          Op.getOperand(2));
15113     }
15114     default:
15115       break;
15116     }
15117   }
15118
15119   switch (IntNo) {
15120   default: return SDValue();    // Don't custom lower most intrinsics.
15121
15122   case Intrinsic::x86_avx2_permd:
15123   case Intrinsic::x86_avx2_permps:
15124     // Operands intentionally swapped. Mask is last operand to intrinsic,
15125     // but second operand for node/instruction.
15126     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15127                        Op.getOperand(2), Op.getOperand(1));
15128
15129   case Intrinsic::x86_avx512_mask_valign_q_512:
15130   case Intrinsic::x86_avx512_mask_valign_d_512:
15131     // Vector source operands are swapped.
15132     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15133                                             Op.getValueType(), Op.getOperand(2),
15134                                             Op.getOperand(1),
15135                                             Op.getOperand(3)),
15136                                 Op.getOperand(5), Op.getOperand(4),
15137                                 Subtarget, DAG);
15138
15139   // ptest and testp intrinsics. The intrinsic these come from are designed to
15140   // return an integer value, not just an instruction so lower it to the ptest
15141   // or testp pattern and a setcc for the result.
15142   case Intrinsic::x86_sse41_ptestz:
15143   case Intrinsic::x86_sse41_ptestc:
15144   case Intrinsic::x86_sse41_ptestnzc:
15145   case Intrinsic::x86_avx_ptestz_256:
15146   case Intrinsic::x86_avx_ptestc_256:
15147   case Intrinsic::x86_avx_ptestnzc_256:
15148   case Intrinsic::x86_avx_vtestz_ps:
15149   case Intrinsic::x86_avx_vtestc_ps:
15150   case Intrinsic::x86_avx_vtestnzc_ps:
15151   case Intrinsic::x86_avx_vtestz_pd:
15152   case Intrinsic::x86_avx_vtestc_pd:
15153   case Intrinsic::x86_avx_vtestnzc_pd:
15154   case Intrinsic::x86_avx_vtestz_ps_256:
15155   case Intrinsic::x86_avx_vtestc_ps_256:
15156   case Intrinsic::x86_avx_vtestnzc_ps_256:
15157   case Intrinsic::x86_avx_vtestz_pd_256:
15158   case Intrinsic::x86_avx_vtestc_pd_256:
15159   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15160     bool IsTestPacked = false;
15161     unsigned X86CC;
15162     switch (IntNo) {
15163     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15164     case Intrinsic::x86_avx_vtestz_ps:
15165     case Intrinsic::x86_avx_vtestz_pd:
15166     case Intrinsic::x86_avx_vtestz_ps_256:
15167     case Intrinsic::x86_avx_vtestz_pd_256:
15168       IsTestPacked = true; // Fallthrough
15169     case Intrinsic::x86_sse41_ptestz:
15170     case Intrinsic::x86_avx_ptestz_256:
15171       // ZF = 1
15172       X86CC = X86::COND_E;
15173       break;
15174     case Intrinsic::x86_avx_vtestc_ps:
15175     case Intrinsic::x86_avx_vtestc_pd:
15176     case Intrinsic::x86_avx_vtestc_ps_256:
15177     case Intrinsic::x86_avx_vtestc_pd_256:
15178       IsTestPacked = true; // Fallthrough
15179     case Intrinsic::x86_sse41_ptestc:
15180     case Intrinsic::x86_avx_ptestc_256:
15181       // CF = 1
15182       X86CC = X86::COND_B;
15183       break;
15184     case Intrinsic::x86_avx_vtestnzc_ps:
15185     case Intrinsic::x86_avx_vtestnzc_pd:
15186     case Intrinsic::x86_avx_vtestnzc_ps_256:
15187     case Intrinsic::x86_avx_vtestnzc_pd_256:
15188       IsTestPacked = true; // Fallthrough
15189     case Intrinsic::x86_sse41_ptestnzc:
15190     case Intrinsic::x86_avx_ptestnzc_256:
15191       // ZF and CF = 0
15192       X86CC = X86::COND_A;
15193       break;
15194     }
15195
15196     SDValue LHS = Op.getOperand(1);
15197     SDValue RHS = Op.getOperand(2);
15198     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15199     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15200     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15201     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15202     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15203   }
15204   case Intrinsic::x86_avx512_kortestz_w:
15205   case Intrinsic::x86_avx512_kortestc_w: {
15206     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15207     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15208     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15209     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15210     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15211     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15212     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15213   }
15214
15215   case Intrinsic::x86_sse42_pcmpistria128:
15216   case Intrinsic::x86_sse42_pcmpestria128:
15217   case Intrinsic::x86_sse42_pcmpistric128:
15218   case Intrinsic::x86_sse42_pcmpestric128:
15219   case Intrinsic::x86_sse42_pcmpistrio128:
15220   case Intrinsic::x86_sse42_pcmpestrio128:
15221   case Intrinsic::x86_sse42_pcmpistris128:
15222   case Intrinsic::x86_sse42_pcmpestris128:
15223   case Intrinsic::x86_sse42_pcmpistriz128:
15224   case Intrinsic::x86_sse42_pcmpestriz128: {
15225     unsigned Opcode;
15226     unsigned X86CC;
15227     switch (IntNo) {
15228     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15229     case Intrinsic::x86_sse42_pcmpistria128:
15230       Opcode = X86ISD::PCMPISTRI;
15231       X86CC = X86::COND_A;
15232       break;
15233     case Intrinsic::x86_sse42_pcmpestria128:
15234       Opcode = X86ISD::PCMPESTRI;
15235       X86CC = X86::COND_A;
15236       break;
15237     case Intrinsic::x86_sse42_pcmpistric128:
15238       Opcode = X86ISD::PCMPISTRI;
15239       X86CC = X86::COND_B;
15240       break;
15241     case Intrinsic::x86_sse42_pcmpestric128:
15242       Opcode = X86ISD::PCMPESTRI;
15243       X86CC = X86::COND_B;
15244       break;
15245     case Intrinsic::x86_sse42_pcmpistrio128:
15246       Opcode = X86ISD::PCMPISTRI;
15247       X86CC = X86::COND_O;
15248       break;
15249     case Intrinsic::x86_sse42_pcmpestrio128:
15250       Opcode = X86ISD::PCMPESTRI;
15251       X86CC = X86::COND_O;
15252       break;
15253     case Intrinsic::x86_sse42_pcmpistris128:
15254       Opcode = X86ISD::PCMPISTRI;
15255       X86CC = X86::COND_S;
15256       break;
15257     case Intrinsic::x86_sse42_pcmpestris128:
15258       Opcode = X86ISD::PCMPESTRI;
15259       X86CC = X86::COND_S;
15260       break;
15261     case Intrinsic::x86_sse42_pcmpistriz128:
15262       Opcode = X86ISD::PCMPISTRI;
15263       X86CC = X86::COND_E;
15264       break;
15265     case Intrinsic::x86_sse42_pcmpestriz128:
15266       Opcode = X86ISD::PCMPESTRI;
15267       X86CC = X86::COND_E;
15268       break;
15269     }
15270     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15271     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15272     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15273     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15274                                 DAG.getConstant(X86CC, dl, MVT::i8),
15275                                 SDValue(PCMP.getNode(), 1));
15276     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15277   }
15278
15279   case Intrinsic::x86_sse42_pcmpistri128:
15280   case Intrinsic::x86_sse42_pcmpestri128: {
15281     unsigned Opcode;
15282     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15283       Opcode = X86ISD::PCMPISTRI;
15284     else
15285       Opcode = X86ISD::PCMPESTRI;
15286
15287     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15288     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15289     return DAG.getNode(Opcode, dl, VTs, NewOps);
15290   }
15291
15292   case Intrinsic::x86_seh_lsda: {
15293     // Compute the symbol for the LSDA. We know it'll get emitted later.
15294     MachineFunction &MF = DAG.getMachineFunction();
15295     SDValue Op1 = Op.getOperand(1);
15296     Op1->dump();
15297     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15298     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15299         GlobalValue::getRealLinkageName(Fn->getName()));
15300     StringRef Name = LSDASym->getName();
15301     assert(Name.data()[Name.size()] == '\0' && "not null terminated");
15302
15303     // Generate a simple absolute symbol reference. This intrinsic is only
15304     // supported on 32-bit Windows, which isn't PIC.
15305     SDValue Result =
15306         DAG.getTargetExternalSymbol(Name.data(), VT, X86II::MO_NOPREFIX);
15307     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15308   }
15309   }
15310 }
15311
15312 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15313                               SDValue Src, SDValue Mask, SDValue Base,
15314                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15315                               const X86Subtarget * Subtarget) {
15316   SDLoc dl(Op);
15317   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15318   assert(C && "Invalid scale type");
15319   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15320   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15321                              Index.getSimpleValueType().getVectorNumElements());
15322   SDValue MaskInReg;
15323   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15324   if (MaskC)
15325     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15326   else
15327     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15328   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15329   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15330   SDValue Segment = DAG.getRegister(0, MVT::i32);
15331   if (Src.getOpcode() == ISD::UNDEF)
15332     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15333   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15334   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15335   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15336   return DAG.getMergeValues(RetOps, dl);
15337 }
15338
15339 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15340                                SDValue Src, SDValue Mask, SDValue Base,
15341                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15342   SDLoc dl(Op);
15343   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15344   assert(C && "Invalid scale type");
15345   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15346   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15347   SDValue Segment = DAG.getRegister(0, MVT::i32);
15348   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15349                              Index.getSimpleValueType().getVectorNumElements());
15350   SDValue MaskInReg;
15351   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15352   if (MaskC)
15353     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15354   else
15355     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15356   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15357   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15358   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15359   return SDValue(Res, 1);
15360 }
15361
15362 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15363                                SDValue Mask, SDValue Base, SDValue Index,
15364                                SDValue ScaleOp, SDValue Chain) {
15365   SDLoc dl(Op);
15366   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15367   assert(C && "Invalid scale type");
15368   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15369   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15370   SDValue Segment = DAG.getRegister(0, MVT::i32);
15371   EVT MaskVT =
15372     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15373   SDValue MaskInReg;
15374   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15375   if (MaskC)
15376     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15377   else
15378     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15379   //SDVTList VTs = DAG.getVTList(MVT::Other);
15380   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15381   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15382   return SDValue(Res, 0);
15383 }
15384
15385 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15386 // read performance monitor counters (x86_rdpmc).
15387 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15388                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15389                               SmallVectorImpl<SDValue> &Results) {
15390   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15391   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15392   SDValue LO, HI;
15393
15394   // The ECX register is used to select the index of the performance counter
15395   // to read.
15396   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15397                                    N->getOperand(2));
15398   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15399
15400   // Reads the content of a 64-bit performance counter and returns it in the
15401   // registers EDX:EAX.
15402   if (Subtarget->is64Bit()) {
15403     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15404     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15405                             LO.getValue(2));
15406   } else {
15407     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15408     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15409                             LO.getValue(2));
15410   }
15411   Chain = HI.getValue(1);
15412
15413   if (Subtarget->is64Bit()) {
15414     // The EAX register is loaded with the low-order 32 bits. The EDX register
15415     // is loaded with the supported high-order bits of the counter.
15416     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15417                               DAG.getConstant(32, DL, MVT::i8));
15418     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15419     Results.push_back(Chain);
15420     return;
15421   }
15422
15423   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15424   SDValue Ops[] = { LO, HI };
15425   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15426   Results.push_back(Pair);
15427   Results.push_back(Chain);
15428 }
15429
15430 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15431 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15432 // also used to custom lower READCYCLECOUNTER nodes.
15433 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15434                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15435                               SmallVectorImpl<SDValue> &Results) {
15436   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15437   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15438   SDValue LO, HI;
15439
15440   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15441   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15442   // and the EAX register is loaded with the low-order 32 bits.
15443   if (Subtarget->is64Bit()) {
15444     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15445     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15446                             LO.getValue(2));
15447   } else {
15448     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15449     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15450                             LO.getValue(2));
15451   }
15452   SDValue Chain = HI.getValue(1);
15453
15454   if (Opcode == X86ISD::RDTSCP_DAG) {
15455     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15456
15457     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15458     // the ECX register. Add 'ecx' explicitly to the chain.
15459     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15460                                      HI.getValue(2));
15461     // Explicitly store the content of ECX at the location passed in input
15462     // to the 'rdtscp' intrinsic.
15463     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15464                          MachinePointerInfo(), false, false, 0);
15465   }
15466
15467   if (Subtarget->is64Bit()) {
15468     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15469     // the EAX register is loaded with the low-order 32 bits.
15470     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15471                               DAG.getConstant(32, DL, MVT::i8));
15472     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15473     Results.push_back(Chain);
15474     return;
15475   }
15476
15477   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15478   SDValue Ops[] = { LO, HI };
15479   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15480   Results.push_back(Pair);
15481   Results.push_back(Chain);
15482 }
15483
15484 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15485                                      SelectionDAG &DAG) {
15486   SmallVector<SDValue, 2> Results;
15487   SDLoc DL(Op);
15488   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15489                           Results);
15490   return DAG.getMergeValues(Results, DL);
15491 }
15492
15493
15494 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15495                                       SelectionDAG &DAG) {
15496   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15497
15498   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15499   if (!IntrData)
15500     return SDValue();
15501
15502   SDLoc dl(Op);
15503   switch(IntrData->Type) {
15504   default:
15505     llvm_unreachable("Unknown Intrinsic Type");
15506     break;
15507   case RDSEED:
15508   case RDRAND: {
15509     // Emit the node with the right value type.
15510     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15511     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15512
15513     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15514     // Otherwise return the value from Rand, which is always 0, casted to i32.
15515     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15516                       DAG.getConstant(1, dl, Op->getValueType(1)),
15517                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15518                       SDValue(Result.getNode(), 1) };
15519     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15520                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15521                                   Ops);
15522
15523     // Return { result, isValid, chain }.
15524     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15525                        SDValue(Result.getNode(), 2));
15526   }
15527   case GATHER: {
15528   //gather(v1, mask, index, base, scale);
15529     SDValue Chain = Op.getOperand(0);
15530     SDValue Src   = Op.getOperand(2);
15531     SDValue Base  = Op.getOperand(3);
15532     SDValue Index = Op.getOperand(4);
15533     SDValue Mask  = Op.getOperand(5);
15534     SDValue Scale = Op.getOperand(6);
15535     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15536                          Chain, Subtarget);
15537   }
15538   case SCATTER: {
15539   //scatter(base, mask, index, v1, scale);
15540     SDValue Chain = Op.getOperand(0);
15541     SDValue Base  = Op.getOperand(2);
15542     SDValue Mask  = Op.getOperand(3);
15543     SDValue Index = Op.getOperand(4);
15544     SDValue Src   = Op.getOperand(5);
15545     SDValue Scale = Op.getOperand(6);
15546     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15547                           Scale, Chain);
15548   }
15549   case PREFETCH: {
15550     SDValue Hint = Op.getOperand(6);
15551     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15552     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15553     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15554     SDValue Chain = Op.getOperand(0);
15555     SDValue Mask  = Op.getOperand(2);
15556     SDValue Index = Op.getOperand(3);
15557     SDValue Base  = Op.getOperand(4);
15558     SDValue Scale = Op.getOperand(5);
15559     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15560   }
15561   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15562   case RDTSC: {
15563     SmallVector<SDValue, 2> Results;
15564     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15565                             Results);
15566     return DAG.getMergeValues(Results, dl);
15567   }
15568   // Read Performance Monitoring Counters.
15569   case RDPMC: {
15570     SmallVector<SDValue, 2> Results;
15571     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15572     return DAG.getMergeValues(Results, dl);
15573   }
15574   // XTEST intrinsics.
15575   case XTEST: {
15576     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15577     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15578     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15579                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15580                                 InTrans);
15581     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15582     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15583                        Ret, SDValue(InTrans.getNode(), 1));
15584   }
15585   // ADC/ADCX/SBB
15586   case ADX: {
15587     SmallVector<SDValue, 2> Results;
15588     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15589     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15590     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15591                                 DAG.getConstant(-1, dl, MVT::i8));
15592     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15593                               Op.getOperand(4), GenCF.getValue(1));
15594     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15595                                  Op.getOperand(5), MachinePointerInfo(),
15596                                  false, false, 0);
15597     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15598                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15599                                 Res.getValue(1));
15600     Results.push_back(SetCC);
15601     Results.push_back(Store);
15602     return DAG.getMergeValues(Results, dl);
15603   }
15604   case COMPRESS_TO_MEM: {
15605     SDLoc dl(Op);
15606     SDValue Mask = Op.getOperand(4);
15607     SDValue DataToCompress = Op.getOperand(3);
15608     SDValue Addr = Op.getOperand(2);
15609     SDValue Chain = Op.getOperand(0);
15610
15611     if (isAllOnes(Mask)) // return just a store
15612       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15613                           MachinePointerInfo(), false, false, 0);
15614
15615     EVT VT = DataToCompress.getValueType();
15616     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15617                                   VT.getVectorNumElements());
15618     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15619                                      Mask.getValueType().getSizeInBits());
15620     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15621                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15622                                 DAG.getIntPtrConstant(0, dl));
15623
15624     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15625                                       DataToCompress, DAG.getUNDEF(VT));
15626     return DAG.getStore(Chain, dl, Compressed, Addr,
15627                         MachinePointerInfo(), false, false, 0);
15628   }
15629   case EXPAND_FROM_MEM: {
15630     SDLoc dl(Op);
15631     SDValue Mask = Op.getOperand(4);
15632     SDValue PathThru = Op.getOperand(3);
15633     SDValue Addr = Op.getOperand(2);
15634     SDValue Chain = Op.getOperand(0);
15635     EVT VT = Op.getValueType();
15636
15637     if (isAllOnes(Mask)) // return just a load
15638       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15639                          false, 0);
15640     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15641                                   VT.getVectorNumElements());
15642     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15643                                      Mask.getValueType().getSizeInBits());
15644     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15645                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15646                                 DAG.getIntPtrConstant(0, dl));
15647
15648     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15649                                    false, false, false, 0);
15650
15651     SDValue Results[] = {
15652         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15653         Chain};
15654     return DAG.getMergeValues(Results, dl);
15655   }
15656   }
15657 }
15658
15659 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15660                                            SelectionDAG &DAG) const {
15661   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15662   MFI->setReturnAddressIsTaken(true);
15663
15664   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15665     return SDValue();
15666
15667   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15668   SDLoc dl(Op);
15669   EVT PtrVT = getPointerTy();
15670
15671   if (Depth > 0) {
15672     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15673     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15674     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15675     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15676                        DAG.getNode(ISD::ADD, dl, PtrVT,
15677                                    FrameAddr, Offset),
15678                        MachinePointerInfo(), false, false, false, 0);
15679   }
15680
15681   // Just load the return address.
15682   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15683   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15684                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15685 }
15686
15687 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15688   MachineFunction &MF = DAG.getMachineFunction();
15689   MachineFrameInfo *MFI = MF.getFrameInfo();
15690   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15691   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15692   EVT VT = Op.getValueType();
15693
15694   MFI->setFrameAddressIsTaken(true);
15695
15696   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15697     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15698     // is not possible to crawl up the stack without looking at the unwind codes
15699     // simultaneously.
15700     int FrameAddrIndex = FuncInfo->getFAIndex();
15701     if (!FrameAddrIndex) {
15702       // Set up a frame object for the return address.
15703       unsigned SlotSize = RegInfo->getSlotSize();
15704       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15705           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
15706       FuncInfo->setFAIndex(FrameAddrIndex);
15707     }
15708     return DAG.getFrameIndex(FrameAddrIndex, VT);
15709   }
15710
15711   unsigned FrameReg =
15712       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15713   SDLoc dl(Op);  // FIXME probably not meaningful
15714   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15715   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15716           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15717          "Invalid Frame Register!");
15718   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15719   while (Depth--)
15720     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15721                             MachinePointerInfo(),
15722                             false, false, false, 0);
15723   return FrameAddr;
15724 }
15725
15726 // FIXME? Maybe this could be a TableGen attribute on some registers and
15727 // this table could be generated automatically from RegInfo.
15728 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15729                                               EVT VT) const {
15730   unsigned Reg = StringSwitch<unsigned>(RegName)
15731                        .Case("esp", X86::ESP)
15732                        .Case("rsp", X86::RSP)
15733                        .Default(0);
15734   if (Reg)
15735     return Reg;
15736   report_fatal_error("Invalid register name global variable");
15737 }
15738
15739 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15740                                                      SelectionDAG &DAG) const {
15741   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15742   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15743 }
15744
15745 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15746   SDValue Chain     = Op.getOperand(0);
15747   SDValue Offset    = Op.getOperand(1);
15748   SDValue Handler   = Op.getOperand(2);
15749   SDLoc dl      (Op);
15750
15751   EVT PtrVT = getPointerTy();
15752   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15753   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15754   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15755           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15756          "Invalid Frame Register!");
15757   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15758   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15759
15760   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15761                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15762                                                        dl));
15763   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15764   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15765                        false, false, 0);
15766   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15767
15768   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15769                      DAG.getRegister(StoreAddrReg, PtrVT));
15770 }
15771
15772 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15773                                                SelectionDAG &DAG) const {
15774   SDLoc DL(Op);
15775   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15776                      DAG.getVTList(MVT::i32, MVT::Other),
15777                      Op.getOperand(0), Op.getOperand(1));
15778 }
15779
15780 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15781                                                 SelectionDAG &DAG) const {
15782   SDLoc DL(Op);
15783   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15784                      Op.getOperand(0), Op.getOperand(1));
15785 }
15786
15787 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15788   return Op.getOperand(0);
15789 }
15790
15791 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15792                                                 SelectionDAG &DAG) const {
15793   SDValue Root = Op.getOperand(0);
15794   SDValue Trmp = Op.getOperand(1); // trampoline
15795   SDValue FPtr = Op.getOperand(2); // nested function
15796   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15797   SDLoc dl (Op);
15798
15799   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15800   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15801
15802   if (Subtarget->is64Bit()) {
15803     SDValue OutChains[6];
15804
15805     // Large code-model.
15806     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15807     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15808
15809     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15810     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15811
15812     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15813
15814     // Load the pointer to the nested function into R11.
15815     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15816     SDValue Addr = Trmp;
15817     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15818                                 Addr, MachinePointerInfo(TrmpAddr),
15819                                 false, false, 0);
15820
15821     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15822                        DAG.getConstant(2, dl, MVT::i64));
15823     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15824                                 MachinePointerInfo(TrmpAddr, 2),
15825                                 false, false, 2);
15826
15827     // Load the 'nest' parameter value into R10.
15828     // R10 is specified in X86CallingConv.td
15829     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15830     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15831                        DAG.getConstant(10, dl, MVT::i64));
15832     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15833                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15834                                 false, false, 0);
15835
15836     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15837                        DAG.getConstant(12, dl, MVT::i64));
15838     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15839                                 MachinePointerInfo(TrmpAddr, 12),
15840                                 false, false, 2);
15841
15842     // Jump to the nested function.
15843     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15844     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15845                        DAG.getConstant(20, dl, MVT::i64));
15846     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15847                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15848                                 false, false, 0);
15849
15850     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15851     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15852                        DAG.getConstant(22, dl, MVT::i64));
15853     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15854                                 Addr, MachinePointerInfo(TrmpAddr, 22),
15855                                 false, false, 0);
15856
15857     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15858   } else {
15859     const Function *Func =
15860       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15861     CallingConv::ID CC = Func->getCallingConv();
15862     unsigned NestReg;
15863
15864     switch (CC) {
15865     default:
15866       llvm_unreachable("Unsupported calling convention");
15867     case CallingConv::C:
15868     case CallingConv::X86_StdCall: {
15869       // Pass 'nest' parameter in ECX.
15870       // Must be kept in sync with X86CallingConv.td
15871       NestReg = X86::ECX;
15872
15873       // Check that ECX wasn't needed by an 'inreg' parameter.
15874       FunctionType *FTy = Func->getFunctionType();
15875       const AttributeSet &Attrs = Func->getAttributes();
15876
15877       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15878         unsigned InRegCount = 0;
15879         unsigned Idx = 1;
15880
15881         for (FunctionType::param_iterator I = FTy->param_begin(),
15882              E = FTy->param_end(); I != E; ++I, ++Idx)
15883           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15884             // FIXME: should only count parameters that are lowered to integers.
15885             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15886
15887         if (InRegCount > 2) {
15888           report_fatal_error("Nest register in use - reduce number of inreg"
15889                              " parameters!");
15890         }
15891       }
15892       break;
15893     }
15894     case CallingConv::X86_FastCall:
15895     case CallingConv::X86_ThisCall:
15896     case CallingConv::Fast:
15897       // Pass 'nest' parameter in EAX.
15898       // Must be kept in sync with X86CallingConv.td
15899       NestReg = X86::EAX;
15900       break;
15901     }
15902
15903     SDValue OutChains[4];
15904     SDValue Addr, Disp;
15905
15906     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15907                        DAG.getConstant(10, dl, MVT::i32));
15908     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15909
15910     // This is storing the opcode for MOV32ri.
15911     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15912     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15913     OutChains[0] = DAG.getStore(Root, dl,
15914                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15915                                 Trmp, MachinePointerInfo(TrmpAddr),
15916                                 false, false, 0);
15917
15918     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15919                        DAG.getConstant(1, dl, MVT::i32));
15920     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15921                                 MachinePointerInfo(TrmpAddr, 1),
15922                                 false, false, 1);
15923
15924     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15925     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15926                        DAG.getConstant(5, dl, MVT::i32));
15927     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15928                                 Addr, MachinePointerInfo(TrmpAddr, 5),
15929                                 false, false, 1);
15930
15931     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15932                        DAG.getConstant(6, dl, MVT::i32));
15933     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15934                                 MachinePointerInfo(TrmpAddr, 6),
15935                                 false, false, 1);
15936
15937     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15938   }
15939 }
15940
15941 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15942                                             SelectionDAG &DAG) const {
15943   /*
15944    The rounding mode is in bits 11:10 of FPSR, and has the following
15945    settings:
15946      00 Round to nearest
15947      01 Round to -inf
15948      10 Round to +inf
15949      11 Round to 0
15950
15951   FLT_ROUNDS, on the other hand, expects the following:
15952     -1 Undefined
15953      0 Round to 0
15954      1 Round to nearest
15955      2 Round to +inf
15956      3 Round to -inf
15957
15958   To perform the conversion, we do:
15959     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15960   */
15961
15962   MachineFunction &MF = DAG.getMachineFunction();
15963   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15964   unsigned StackAlignment = TFI.getStackAlignment();
15965   MVT VT = Op.getSimpleValueType();
15966   SDLoc DL(Op);
15967
15968   // Save FP Control Word to stack slot
15969   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15970   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15971
15972   MachineMemOperand *MMO =
15973    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15974                            MachineMemOperand::MOStore, 2, 2);
15975
15976   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15977   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15978                                           DAG.getVTList(MVT::Other),
15979                                           Ops, MVT::i16, MMO);
15980
15981   // Load FP Control Word from stack slot
15982   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15983                             MachinePointerInfo(), false, false, false, 0);
15984
15985   // Transform as necessary
15986   SDValue CWD1 =
15987     DAG.getNode(ISD::SRL, DL, MVT::i16,
15988                 DAG.getNode(ISD::AND, DL, MVT::i16,
15989                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
15990                 DAG.getConstant(11, DL, MVT::i8));
15991   SDValue CWD2 =
15992     DAG.getNode(ISD::SRL, DL, MVT::i16,
15993                 DAG.getNode(ISD::AND, DL, MVT::i16,
15994                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
15995                 DAG.getConstant(9, DL, MVT::i8));
15996
15997   SDValue RetVal =
15998     DAG.getNode(ISD::AND, DL, MVT::i16,
15999                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16000                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16001                             DAG.getConstant(1, DL, MVT::i16)),
16002                 DAG.getConstant(3, DL, MVT::i16));
16003
16004   return DAG.getNode((VT.getSizeInBits() < 16 ?
16005                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16006 }
16007
16008 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16009   MVT VT = Op.getSimpleValueType();
16010   EVT OpVT = VT;
16011   unsigned NumBits = VT.getSizeInBits();
16012   SDLoc dl(Op);
16013
16014   Op = Op.getOperand(0);
16015   if (VT == MVT::i8) {
16016     // Zero extend to i32 since there is not an i8 bsr.
16017     OpVT = MVT::i32;
16018     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16019   }
16020
16021   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16022   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16023   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16024
16025   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16026   SDValue Ops[] = {
16027     Op,
16028     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16029     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16030     Op.getValue(1)
16031   };
16032   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16033
16034   // Finally xor with NumBits-1.
16035   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16036                    DAG.getConstant(NumBits - 1, dl, OpVT));
16037
16038   if (VT == MVT::i8)
16039     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16040   return Op;
16041 }
16042
16043 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16044   MVT VT = Op.getSimpleValueType();
16045   EVT OpVT = VT;
16046   unsigned NumBits = VT.getSizeInBits();
16047   SDLoc dl(Op);
16048
16049   Op = Op.getOperand(0);
16050   if (VT == MVT::i8) {
16051     // Zero extend to i32 since there is not an i8 bsr.
16052     OpVT = MVT::i32;
16053     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16054   }
16055
16056   // Issue a bsr (scan bits in reverse).
16057   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16058   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16059
16060   // And xor with NumBits-1.
16061   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16062                    DAG.getConstant(NumBits - 1, dl, OpVT));
16063
16064   if (VT == MVT::i8)
16065     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16066   return Op;
16067 }
16068
16069 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16070   MVT VT = Op.getSimpleValueType();
16071   unsigned NumBits = VT.getSizeInBits();
16072   SDLoc dl(Op);
16073   Op = Op.getOperand(0);
16074
16075   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16076   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16077   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16078
16079   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16080   SDValue Ops[] = {
16081     Op,
16082     DAG.getConstant(NumBits, dl, VT),
16083     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16084     Op.getValue(1)
16085   };
16086   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16087 }
16088
16089 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16090 // ones, and then concatenate the result back.
16091 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16092   MVT VT = Op.getSimpleValueType();
16093
16094   assert(VT.is256BitVector() && VT.isInteger() &&
16095          "Unsupported value type for operation");
16096
16097   unsigned NumElems = VT.getVectorNumElements();
16098   SDLoc dl(Op);
16099
16100   // Extract the LHS vectors
16101   SDValue LHS = Op.getOperand(0);
16102   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16103   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16104
16105   // Extract the RHS vectors
16106   SDValue RHS = Op.getOperand(1);
16107   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16108   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16109
16110   MVT EltVT = VT.getVectorElementType();
16111   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16112
16113   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16114                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16115                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16116 }
16117
16118 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16119   assert(Op.getSimpleValueType().is256BitVector() &&
16120          Op.getSimpleValueType().isInteger() &&
16121          "Only handle AVX 256-bit vector integer operation");
16122   return Lower256IntArith(Op, DAG);
16123 }
16124
16125 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16126   assert(Op.getSimpleValueType().is256BitVector() &&
16127          Op.getSimpleValueType().isInteger() &&
16128          "Only handle AVX 256-bit vector integer operation");
16129   return Lower256IntArith(Op, DAG);
16130 }
16131
16132 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16133                         SelectionDAG &DAG) {
16134   SDLoc dl(Op);
16135   MVT VT = Op.getSimpleValueType();
16136
16137   // Decompose 256-bit ops into smaller 128-bit ops.
16138   if (VT.is256BitVector() && !Subtarget->hasInt256())
16139     return Lower256IntArith(Op, DAG);
16140
16141   SDValue A = Op.getOperand(0);
16142   SDValue B = Op.getOperand(1);
16143
16144   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16145   // pairs, multiply and truncate.
16146   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16147     if (Subtarget->hasInt256()) {
16148       if (VT == MVT::v32i8) {
16149         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16150         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16151         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16152         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16153         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16154         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16155         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16156         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16157                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16158                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16159       }
16160
16161       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16162       return DAG.getNode(
16163           ISD::TRUNCATE, dl, VT,
16164           DAG.getNode(ISD::MUL, dl, ExVT,
16165                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16166                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16167     }
16168
16169     assert(VT == MVT::v16i8 &&
16170            "Pre-AVX2 support only supports v16i8 multiplication");
16171     MVT ExVT = MVT::v8i16;
16172
16173     // Extract the lo parts and sign extend to i16
16174     SDValue ALo, BLo;
16175     if (Subtarget->hasSSE41()) {
16176       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16177       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16178     } else {
16179       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16180                               -1, 4, -1, 5, -1, 6, -1, 7};
16181       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16182       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16183       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16184       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16185       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16186       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16187     }
16188
16189     // Extract the hi parts and sign extend to i16
16190     SDValue AHi, BHi;
16191     if (Subtarget->hasSSE41()) {
16192       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16193                               -1, -1, -1, -1, -1, -1, -1, -1};
16194       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16195       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16196       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16197       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16198     } else {
16199       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16200                               -1, 12, -1, 13, -1, 14, -1, 15};
16201       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16202       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16203       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16204       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16205       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16206       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16207     }
16208
16209     // Multiply, mask the lower 8bits of the lo/hi results and pack
16210     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16211     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16212     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16213     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16214     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16215   }
16216
16217   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16218   if (VT == MVT::v4i32) {
16219     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16220            "Should not custom lower when pmuldq is available!");
16221
16222     // Extract the odd parts.
16223     static const int UnpackMask[] = { 1, -1, 3, -1 };
16224     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16225     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16226
16227     // Multiply the even parts.
16228     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16229     // Now multiply odd parts.
16230     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16231
16232     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16233     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16234
16235     // Merge the two vectors back together with a shuffle. This expands into 2
16236     // shuffles.
16237     static const int ShufMask[] = { 0, 4, 2, 6 };
16238     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16239   }
16240
16241   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16242          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16243
16244   //  Ahi = psrlqi(a, 32);
16245   //  Bhi = psrlqi(b, 32);
16246   //
16247   //  AloBlo = pmuludq(a, b);
16248   //  AloBhi = pmuludq(a, Bhi);
16249   //  AhiBlo = pmuludq(Ahi, b);
16250
16251   //  AloBhi = psllqi(AloBhi, 32);
16252   //  AhiBlo = psllqi(AhiBlo, 32);
16253   //  return AloBlo + AloBhi + AhiBlo;
16254
16255   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16256   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16257
16258   // Bit cast to 32-bit vectors for MULUDQ
16259   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16260                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16261   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16262   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16263   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16264   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16265
16266   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16267   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16268   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16269
16270   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16271   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16272
16273   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16274   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16275 }
16276
16277 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16278   assert(Subtarget->isTargetWin64() && "Unexpected target");
16279   EVT VT = Op.getValueType();
16280   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16281          "Unexpected return type for lowering");
16282
16283   RTLIB::Libcall LC;
16284   bool isSigned;
16285   switch (Op->getOpcode()) {
16286   default: llvm_unreachable("Unexpected request for libcall!");
16287   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16288   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16289   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16290   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16291   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16292   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16293   }
16294
16295   SDLoc dl(Op);
16296   SDValue InChain = DAG.getEntryNode();
16297
16298   TargetLowering::ArgListTy Args;
16299   TargetLowering::ArgListEntry Entry;
16300   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16301     EVT ArgVT = Op->getOperand(i).getValueType();
16302     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16303            "Unexpected argument type for lowering");
16304     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16305     Entry.Node = StackPtr;
16306     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16307                            false, false, 16);
16308     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16309     Entry.Ty = PointerType::get(ArgTy,0);
16310     Entry.isSExt = false;
16311     Entry.isZExt = false;
16312     Args.push_back(Entry);
16313   }
16314
16315   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16316                                          getPointerTy());
16317
16318   TargetLowering::CallLoweringInfo CLI(DAG);
16319   CLI.setDebugLoc(dl).setChain(InChain)
16320     .setCallee(getLibcallCallingConv(LC),
16321                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16322                Callee, std::move(Args), 0)
16323     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16324
16325   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16326   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16327 }
16328
16329 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16330                              SelectionDAG &DAG) {
16331   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16332   EVT VT = Op0.getValueType();
16333   SDLoc dl(Op);
16334
16335   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16336          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16337
16338   // PMULxD operations multiply each even value (starting at 0) of LHS with
16339   // the related value of RHS and produce a widen result.
16340   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16341   // => <2 x i64> <ae|cg>
16342   //
16343   // In other word, to have all the results, we need to perform two PMULxD:
16344   // 1. one with the even values.
16345   // 2. one with the odd values.
16346   // To achieve #2, with need to place the odd values at an even position.
16347   //
16348   // Place the odd value at an even position (basically, shift all values 1
16349   // step to the left):
16350   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16351   // <a|b|c|d> => <b|undef|d|undef>
16352   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16353   // <e|f|g|h> => <f|undef|h|undef>
16354   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16355
16356   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16357   // ints.
16358   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16359   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16360   unsigned Opcode =
16361       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16362   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16363   // => <2 x i64> <ae|cg>
16364   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16365                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16366   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16367   // => <2 x i64> <bf|dh>
16368   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16369                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16370
16371   // Shuffle it back into the right order.
16372   SDValue Highs, Lows;
16373   if (VT == MVT::v8i32) {
16374     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16375     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16376     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16377     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16378   } else {
16379     const int HighMask[] = {1, 5, 3, 7};
16380     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16381     const int LowMask[] = {0, 4, 2, 6};
16382     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16383   }
16384
16385   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16386   // unsigned multiply.
16387   if (IsSigned && !Subtarget->hasSSE41()) {
16388     SDValue ShAmt =
16389         DAG.getConstant(31, dl,
16390                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16391     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16392                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16393     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16394                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16395
16396     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16397     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16398   }
16399
16400   // The first result of MUL_LOHI is actually the low value, followed by the
16401   // high value.
16402   SDValue Ops[] = {Lows, Highs};
16403   return DAG.getMergeValues(Ops, dl);
16404 }
16405
16406 // Return true if the requred (according to Opcode) shift-imm form is natively
16407 // supported by the Subtarget
16408 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget, 
16409                                         unsigned Opcode) {
16410   if (VT.getScalarSizeInBits() < 16)
16411     return false;
16412  
16413   if (VT.is512BitVector() &&
16414       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16415     return true;
16416
16417   bool LShift = VT.is128BitVector() || 
16418     (VT.is256BitVector() && Subtarget->hasInt256());
16419
16420   bool AShift = LShift && (Subtarget->hasVLX() ||
16421     (VT != MVT::v2i64 && VT != MVT::v4i64));
16422   return (Opcode == ISD::SRA) ? AShift : LShift;
16423 }
16424
16425 // The shift amount is a variable, but it is the same for all vector lanes.
16426 // These instrcutions are defined together with shift-immediate.
16427 static 
16428 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget, 
16429                                       unsigned Opcode) {
16430   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16431 }
16432
16433 // Return true if the requred (according to Opcode) variable-shift form is
16434 // natively supported by the Subtarget
16435 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget, 
16436                                     unsigned Opcode) {
16437
16438   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16439     return false;
16440
16441   // vXi16 supported only on AVX-512, BWI
16442   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16443     return false;
16444
16445   if (VT.is512BitVector() || Subtarget->hasVLX())
16446     return true;
16447
16448   bool LShift = VT.is128BitVector() || VT.is256BitVector();
16449   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
16450   return (Opcode == ISD::SRA) ? AShift : LShift;
16451 }
16452
16453 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16454                                          const X86Subtarget *Subtarget) {
16455   MVT VT = Op.getSimpleValueType();
16456   SDLoc dl(Op);
16457   SDValue R = Op.getOperand(0);
16458   SDValue Amt = Op.getOperand(1);
16459
16460   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16461     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16462
16463   // Optimize shl/srl/sra with constant shift amount.
16464   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16465     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16466       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16467
16468       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
16469         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16470
16471       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16472         unsigned NumElts = VT.getVectorNumElements();
16473         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16474
16475         if (Op.getOpcode() == ISD::SHL) {
16476           // Make a large shift.
16477           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16478                                                    R, ShiftAmt, DAG);
16479           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16480           // Zero out the rightmost bits.
16481           SmallVector<SDValue, 32> V(
16482               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16483           return DAG.getNode(ISD::AND, dl, VT, SHL,
16484                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16485         }
16486         if (Op.getOpcode() == ISD::SRL) {
16487           // Make a large shift.
16488           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16489                                                    R, ShiftAmt, DAG);
16490           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16491           // Zero out the leftmost bits.
16492           SmallVector<SDValue, 32> V(
16493               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16494           return DAG.getNode(ISD::AND, dl, VT, SRL,
16495                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16496         }
16497         if (Op.getOpcode() == ISD::SRA) {
16498           if (ShiftAmt == 7) {
16499             // R s>> 7  ===  R s< 0
16500             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16501             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16502           }
16503
16504           // R s>> a === ((R u>> a) ^ m) - m
16505           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16506           SmallVector<SDValue, 32> V(NumElts,
16507                                      DAG.getConstant(128 >> ShiftAmt, dl,
16508                                                      MVT::i8));
16509           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16510           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16511           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16512           return Res;
16513         }
16514         llvm_unreachable("Unknown shift opcode.");
16515       }
16516     }
16517   }
16518
16519   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16520   if (!Subtarget->is64Bit() &&
16521       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16522       Amt.getOpcode() == ISD::BITCAST &&
16523       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16524     Amt = Amt.getOperand(0);
16525     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16526                      VT.getVectorNumElements();
16527     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16528     uint64_t ShiftAmt = 0;
16529     for (unsigned i = 0; i != Ratio; ++i) {
16530       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16531       if (!C)
16532         return SDValue();
16533       // 6 == Log2(64)
16534       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16535     }
16536     // Check remaining shift amounts.
16537     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16538       uint64_t ShAmt = 0;
16539       for (unsigned j = 0; j != Ratio; ++j) {
16540         ConstantSDNode *C =
16541           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16542         if (!C)
16543           return SDValue();
16544         // 6 == Log2(64)
16545         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16546       }
16547       if (ShAmt != ShiftAmt)
16548         return SDValue();
16549     }
16550     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16551   }
16552
16553   return SDValue();
16554 }
16555
16556 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16557                                         const X86Subtarget* Subtarget) {
16558   MVT VT = Op.getSimpleValueType();
16559   SDLoc dl(Op);
16560   SDValue R = Op.getOperand(0);
16561   SDValue Amt = Op.getOperand(1);
16562
16563   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16564     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16565
16566   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
16567     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
16568
16569   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
16570     SDValue BaseShAmt;
16571     EVT EltVT = VT.getVectorElementType();
16572
16573     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16574       // Check if this build_vector node is doing a splat.
16575       // If so, then set BaseShAmt equal to the splat value.
16576       BaseShAmt = BV->getSplatValue();
16577       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16578         BaseShAmt = SDValue();
16579     } else {
16580       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16581         Amt = Amt.getOperand(0);
16582
16583       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16584       if (SVN && SVN->isSplat()) {
16585         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16586         SDValue InVec = Amt.getOperand(0);
16587         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16588           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16589                  "Unexpected shuffle index found!");
16590           BaseShAmt = InVec.getOperand(SplatIdx);
16591         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16592            if (ConstantSDNode *C =
16593                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16594              if (C->getZExtValue() == SplatIdx)
16595                BaseShAmt = InVec.getOperand(1);
16596            }
16597         }
16598
16599         if (!BaseShAmt)
16600           // Avoid introducing an extract element from a shuffle.
16601           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16602                                   DAG.getIntPtrConstant(SplatIdx, dl));
16603       }
16604     }
16605
16606     if (BaseShAmt.getNode()) {
16607       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16608       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16609         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16610       else if (EltVT.bitsLT(MVT::i32))
16611         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16612
16613       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
16614     }
16615   }
16616
16617   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16618   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16619       Amt.getOpcode() == ISD::BITCAST &&
16620       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16621     Amt = Amt.getOperand(0);
16622     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16623                      VT.getVectorNumElements();
16624     std::vector<SDValue> Vals(Ratio);
16625     for (unsigned i = 0; i != Ratio; ++i)
16626       Vals[i] = Amt.getOperand(i);
16627     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16628       for (unsigned j = 0; j != Ratio; ++j)
16629         if (Vals[j] != Amt.getOperand(i + j))
16630           return SDValue();
16631     }
16632     return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
16633   }
16634   return SDValue();
16635 }
16636
16637 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16638                           SelectionDAG &DAG) {
16639   MVT VT = Op.getSimpleValueType();
16640   SDLoc dl(Op);
16641   SDValue R = Op.getOperand(0);
16642   SDValue Amt = Op.getOperand(1);
16643
16644   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16645   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16646
16647   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16648     return V;
16649
16650   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16651       return V;
16652
16653   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
16654     return Op;
16655
16656   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16657   // shifts per-lane and then shuffle the partial results back together.
16658   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16659     // Splat the shift amounts so the scalar shifts above will catch it.
16660     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16661     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16662     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16663     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16664     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16665   }
16666
16667   // If possible, lower this packed shift into a vector multiply instead of
16668   // expanding it into a sequence of scalar shifts.
16669   // Do this only if the vector shift count is a constant build_vector.
16670   if (Op.getOpcode() == ISD::SHL &&
16671       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16672        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16673       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16674     SmallVector<SDValue, 8> Elts;
16675     EVT SVT = VT.getScalarType();
16676     unsigned SVTBits = SVT.getSizeInBits();
16677     const APInt &One = APInt(SVTBits, 1);
16678     unsigned NumElems = VT.getVectorNumElements();
16679
16680     for (unsigned i=0; i !=NumElems; ++i) {
16681       SDValue Op = Amt->getOperand(i);
16682       if (Op->getOpcode() == ISD::UNDEF) {
16683         Elts.push_back(Op);
16684         continue;
16685       }
16686
16687       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16688       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16689       uint64_t ShAmt = C.getZExtValue();
16690       if (ShAmt >= SVTBits) {
16691         Elts.push_back(DAG.getUNDEF(SVT));
16692         continue;
16693       }
16694       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16695     }
16696     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16697     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16698   }
16699
16700   // Lower SHL with variable shift amount.
16701   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16702     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16703
16704     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16705                      DAG.getConstant(0x3f800000U, dl, VT));
16706     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16707     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16708     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16709   }
16710
16711   // If possible, lower this shift as a sequence of two shifts by
16712   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16713   // Example:
16714   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16715   //
16716   // Could be rewritten as:
16717   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16718   //
16719   // The advantage is that the two shifts from the example would be
16720   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16721   // the vector shift into four scalar shifts plus four pairs of vector
16722   // insert/extract.
16723   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16724       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16725     unsigned TargetOpcode = X86ISD::MOVSS;
16726     bool CanBeSimplified;
16727     // The splat value for the first packed shift (the 'X' from the example).
16728     SDValue Amt1 = Amt->getOperand(0);
16729     // The splat value for the second packed shift (the 'Y' from the example).
16730     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16731                                         Amt->getOperand(2);
16732
16733     // See if it is possible to replace this node with a sequence of
16734     // two shifts followed by a MOVSS/MOVSD
16735     if (VT == MVT::v4i32) {
16736       // Check if it is legal to use a MOVSS.
16737       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16738                         Amt2 == Amt->getOperand(3);
16739       if (!CanBeSimplified) {
16740         // Otherwise, check if we can still simplify this node using a MOVSD.
16741         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16742                           Amt->getOperand(2) == Amt->getOperand(3);
16743         TargetOpcode = X86ISD::MOVSD;
16744         Amt2 = Amt->getOperand(2);
16745       }
16746     } else {
16747       // Do similar checks for the case where the machine value type
16748       // is MVT::v8i16.
16749       CanBeSimplified = Amt1 == Amt->getOperand(1);
16750       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16751         CanBeSimplified = Amt2 == Amt->getOperand(i);
16752
16753       if (!CanBeSimplified) {
16754         TargetOpcode = X86ISD::MOVSD;
16755         CanBeSimplified = true;
16756         Amt2 = Amt->getOperand(4);
16757         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16758           CanBeSimplified = Amt1 == Amt->getOperand(i);
16759         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16760           CanBeSimplified = Amt2 == Amt->getOperand(j);
16761       }
16762     }
16763
16764     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16765         isa<ConstantSDNode>(Amt2)) {
16766       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16767       EVT CastVT = MVT::v4i32;
16768       SDValue Splat1 =
16769         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16770       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16771       SDValue Splat2 =
16772         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16773       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16774       if (TargetOpcode == X86ISD::MOVSD)
16775         CastVT = MVT::v2i64;
16776       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16777       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16778       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16779                                             BitCast1, DAG);
16780       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16781     }
16782   }
16783
16784   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16785     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16786     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16787
16788     SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16789     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16790     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16791
16792     // r = VSELECT(r, shl(r, 4), a);
16793     SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16794     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16795
16796     // a += a
16797     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16798     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16799     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16800
16801     // r = VSELECT(r, shl(r, 2), a);
16802     M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16803     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16804
16805     // a += a
16806     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16807     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16808     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16809
16810     // return VSELECT(r, r+r, a);
16811     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16812                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16813     return R;
16814   }
16815
16816   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16817   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16818   // solution better.
16819   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16820     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16821     unsigned ExtOpc =
16822         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16823     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16824     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16825     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16826                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16827   }
16828
16829   // Decompose 256-bit shifts into smaller 128-bit shifts.
16830   if (VT.is256BitVector()) {
16831     unsigned NumElems = VT.getVectorNumElements();
16832     MVT EltVT = VT.getVectorElementType();
16833     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16834
16835     // Extract the two vectors
16836     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16837     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16838
16839     // Recreate the shift amount vectors
16840     SDValue Amt1, Amt2;
16841     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16842       // Constant shift amount
16843       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16844       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16845       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16846
16847       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16848       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16849     } else {
16850       // Variable shift amount
16851       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16852       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16853     }
16854
16855     // Issue new vector shifts for the smaller types
16856     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16857     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16858
16859     // Concatenate the result back
16860     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16861   }
16862
16863   return SDValue();
16864 }
16865
16866 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16867   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16868   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16869   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16870   // has only one use.
16871   SDNode *N = Op.getNode();
16872   SDValue LHS = N->getOperand(0);
16873   SDValue RHS = N->getOperand(1);
16874   unsigned BaseOp = 0;
16875   unsigned Cond = 0;
16876   SDLoc DL(Op);
16877   switch (Op.getOpcode()) {
16878   default: llvm_unreachable("Unknown ovf instruction!");
16879   case ISD::SADDO:
16880     // A subtract of one will be selected as a INC. Note that INC doesn't
16881     // set CF, so we can't do this for UADDO.
16882     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16883       if (C->isOne()) {
16884         BaseOp = X86ISD::INC;
16885         Cond = X86::COND_O;
16886         break;
16887       }
16888     BaseOp = X86ISD::ADD;
16889     Cond = X86::COND_O;
16890     break;
16891   case ISD::UADDO:
16892     BaseOp = X86ISD::ADD;
16893     Cond = X86::COND_B;
16894     break;
16895   case ISD::SSUBO:
16896     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16897     // set CF, so we can't do this for USUBO.
16898     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16899       if (C->isOne()) {
16900         BaseOp = X86ISD::DEC;
16901         Cond = X86::COND_O;
16902         break;
16903       }
16904     BaseOp = X86ISD::SUB;
16905     Cond = X86::COND_O;
16906     break;
16907   case ISD::USUBO:
16908     BaseOp = X86ISD::SUB;
16909     Cond = X86::COND_B;
16910     break;
16911   case ISD::SMULO:
16912     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16913     Cond = X86::COND_O;
16914     break;
16915   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16916     if (N->getValueType(0) == MVT::i8) {
16917       BaseOp = X86ISD::UMUL8;
16918       Cond = X86::COND_O;
16919       break;
16920     }
16921     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16922                                  MVT::i32);
16923     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16924
16925     SDValue SetCC =
16926       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16927                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
16928                   SDValue(Sum.getNode(), 2));
16929
16930     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16931   }
16932   }
16933
16934   // Also sets EFLAGS.
16935   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16936   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16937
16938   SDValue SetCC =
16939     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16940                 DAG.getConstant(Cond, DL, MVT::i32),
16941                 SDValue(Sum.getNode(), 1));
16942
16943   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16944 }
16945
16946 /// Returns true if the operand type is exactly twice the native width, and
16947 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16948 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16949 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16950 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16951   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16952
16953   if (OpWidth == 64)
16954     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16955   else if (OpWidth == 128)
16956     return Subtarget->hasCmpxchg16b();
16957   else
16958     return false;
16959 }
16960
16961 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16962   return needsCmpXchgNb(SI->getValueOperand()->getType());
16963 }
16964
16965 // Note: this turns large loads into lock cmpxchg8b/16b.
16966 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16967 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16968   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16969   return needsCmpXchgNb(PTy->getElementType());
16970 }
16971
16972 TargetLoweringBase::AtomicRMWExpansionKind
16973 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16974   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16975   const Type *MemType = AI->getType();
16976
16977   // If the operand is too big, we must see if cmpxchg8/16b is available
16978   // and default to library calls otherwise.
16979   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16980     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16981                                    : AtomicRMWExpansionKind::None;
16982   }
16983
16984   AtomicRMWInst::BinOp Op = AI->getOperation();
16985   switch (Op) {
16986   default:
16987     llvm_unreachable("Unknown atomic operation");
16988   case AtomicRMWInst::Xchg:
16989   case AtomicRMWInst::Add:
16990   case AtomicRMWInst::Sub:
16991     // It's better to use xadd, xsub or xchg for these in all cases.
16992     return AtomicRMWExpansionKind::None;
16993   case AtomicRMWInst::Or:
16994   case AtomicRMWInst::And:
16995   case AtomicRMWInst::Xor:
16996     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16997     // prefix to a normal instruction for these operations.
16998     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16999                             : AtomicRMWExpansionKind::None;
17000   case AtomicRMWInst::Nand:
17001   case AtomicRMWInst::Max:
17002   case AtomicRMWInst::Min:
17003   case AtomicRMWInst::UMax:
17004   case AtomicRMWInst::UMin:
17005     // These always require a non-trivial set of data operations on x86. We must
17006     // use a cmpxchg loop.
17007     return AtomicRMWExpansionKind::CmpXChg;
17008   }
17009 }
17010
17011 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17012   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17013   // no-sse2). There isn't any reason to disable it if the target processor
17014   // supports it.
17015   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17016 }
17017
17018 LoadInst *
17019 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17020   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17021   const Type *MemType = AI->getType();
17022   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17023   // there is no benefit in turning such RMWs into loads, and it is actually
17024   // harmful as it introduces a mfence.
17025   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17026     return nullptr;
17027
17028   auto Builder = IRBuilder<>(AI);
17029   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17030   auto SynchScope = AI->getSynchScope();
17031   // We must restrict the ordering to avoid generating loads with Release or
17032   // ReleaseAcquire orderings.
17033   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17034   auto Ptr = AI->getPointerOperand();
17035
17036   // Before the load we need a fence. Here is an example lifted from
17037   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17038   // is required:
17039   // Thread 0:
17040   //   x.store(1, relaxed);
17041   //   r1 = y.fetch_add(0, release);
17042   // Thread 1:
17043   //   y.fetch_add(42, acquire);
17044   //   r2 = x.load(relaxed);
17045   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17046   // lowered to just a load without a fence. A mfence flushes the store buffer,
17047   // making the optimization clearly correct.
17048   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17049   // otherwise, we might be able to be more agressive on relaxed idempotent
17050   // rmw. In practice, they do not look useful, so we don't try to be
17051   // especially clever.
17052   if (SynchScope == SingleThread)
17053     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17054     // the IR level, so we must wrap it in an intrinsic.
17055     return nullptr;
17056
17057   if (!hasMFENCE(*Subtarget))
17058     // FIXME: it might make sense to use a locked operation here but on a
17059     // different cache-line to prevent cache-line bouncing. In practice it
17060     // is probably a small win, and x86 processors without mfence are rare
17061     // enough that we do not bother.
17062     return nullptr;
17063
17064   Function *MFence =
17065       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17066   Builder.CreateCall(MFence, {});
17067
17068   // Finally we can emit the atomic load.
17069   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17070           AI->getType()->getPrimitiveSizeInBits());
17071   Loaded->setAtomic(Order, SynchScope);
17072   AI->replaceAllUsesWith(Loaded);
17073   AI->eraseFromParent();
17074   return Loaded;
17075 }
17076
17077 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17078                                  SelectionDAG &DAG) {
17079   SDLoc dl(Op);
17080   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17081     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17082   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17083     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17084
17085   // The only fence that needs an instruction is a sequentially-consistent
17086   // cross-thread fence.
17087   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17088     if (hasMFENCE(*Subtarget))
17089       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17090
17091     SDValue Chain = Op.getOperand(0);
17092     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17093     SDValue Ops[] = {
17094       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17095       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17096       DAG.getRegister(0, MVT::i32),            // Index
17097       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17098       DAG.getRegister(0, MVT::i32),            // Segment.
17099       Zero,
17100       Chain
17101     };
17102     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17103     return SDValue(Res, 0);
17104   }
17105
17106   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17107   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17108 }
17109
17110 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17111                              SelectionDAG &DAG) {
17112   MVT T = Op.getSimpleValueType();
17113   SDLoc DL(Op);
17114   unsigned Reg = 0;
17115   unsigned size = 0;
17116   switch(T.SimpleTy) {
17117   default: llvm_unreachable("Invalid value type!");
17118   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17119   case MVT::i16: Reg = X86::AX;  size = 2; break;
17120   case MVT::i32: Reg = X86::EAX; size = 4; break;
17121   case MVT::i64:
17122     assert(Subtarget->is64Bit() && "Node not type legal!");
17123     Reg = X86::RAX; size = 8;
17124     break;
17125   }
17126   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17127                                   Op.getOperand(2), SDValue());
17128   SDValue Ops[] = { cpIn.getValue(0),
17129                     Op.getOperand(1),
17130                     Op.getOperand(3),
17131                     DAG.getTargetConstant(size, DL, MVT::i8),
17132                     cpIn.getValue(1) };
17133   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17134   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17135   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17136                                            Ops, T, MMO);
17137
17138   SDValue cpOut =
17139     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17140   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17141                                       MVT::i32, cpOut.getValue(2));
17142   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17143                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17144                                 EFLAGS);
17145
17146   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17147   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17148   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17149   return SDValue();
17150 }
17151
17152 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17153                             SelectionDAG &DAG) {
17154   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17155   MVT DstVT = Op.getSimpleValueType();
17156
17157   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17158     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17159     if (DstVT != MVT::f64)
17160       // This conversion needs to be expanded.
17161       return SDValue();
17162
17163     SDValue InVec = Op->getOperand(0);
17164     SDLoc dl(Op);
17165     unsigned NumElts = SrcVT.getVectorNumElements();
17166     EVT SVT = SrcVT.getVectorElementType();
17167
17168     // Widen the vector in input in the case of MVT::v2i32.
17169     // Example: from MVT::v2i32 to MVT::v4i32.
17170     SmallVector<SDValue, 16> Elts;
17171     for (unsigned i = 0, e = NumElts; i != e; ++i)
17172       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17173                                  DAG.getIntPtrConstant(i, dl)));
17174
17175     // Explicitly mark the extra elements as Undef.
17176     Elts.append(NumElts, DAG.getUNDEF(SVT));
17177
17178     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17179     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17180     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17181     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17182                        DAG.getIntPtrConstant(0, dl));
17183   }
17184
17185   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17186          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17187   assert((DstVT == MVT::i64 ||
17188           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17189          "Unexpected custom BITCAST");
17190   // i64 <=> MMX conversions are Legal.
17191   if (SrcVT==MVT::i64 && DstVT.isVector())
17192     return Op;
17193   if (DstVT==MVT::i64 && SrcVT.isVector())
17194     return Op;
17195   // MMX <=> MMX conversions are Legal.
17196   if (SrcVT.isVector() && DstVT.isVector())
17197     return Op;
17198   // All other conversions need to be expanded.
17199   return SDValue();
17200 }
17201
17202 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17203                           SelectionDAG &DAG) {
17204   SDNode *Node = Op.getNode();
17205   SDLoc dl(Node);
17206
17207   Op = Op.getOperand(0);
17208   EVT VT = Op.getValueType();
17209   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17210          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17211
17212   unsigned NumElts = VT.getVectorNumElements();
17213   EVT EltVT = VT.getVectorElementType();
17214   unsigned Len = EltVT.getSizeInBits();
17215
17216   // This is the vectorized version of the "best" algorithm from
17217   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17218   // with a minor tweak to use a series of adds + shifts instead of vector
17219   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17220   //
17221   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17222   //  v8i32 => Always profitable
17223   //
17224   // FIXME: There a couple of possible improvements:
17225   //
17226   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17227   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17228   //
17229   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17230          "CTPOP not implemented for this vector element type.");
17231
17232   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17233   // extra legalization.
17234   bool NeedsBitcast = EltVT == MVT::i32;
17235   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17236
17237   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17238                                   EltVT);
17239   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17240                                   EltVT);
17241   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17242                                   EltVT);
17243
17244   // v = v - ((v >> 1) & 0x55555555...)
17245   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17246   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17247   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17248   if (NeedsBitcast)
17249     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17250
17251   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17252   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17253   if (NeedsBitcast)
17254     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17255
17256   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17257   if (VT != And.getValueType())
17258     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17259   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17260
17261   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17262   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17263   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17264   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17265   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17266
17267   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17268   if (NeedsBitcast) {
17269     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17270     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17271     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17272   }
17273
17274   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17275   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17276   if (VT != AndRHS.getValueType()) {
17277     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17278     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17279   }
17280   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17281
17282   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17283   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17284   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17285   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17286   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17287
17288   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17289   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17290   if (NeedsBitcast) {
17291     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17292     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17293   }
17294   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17295   if (VT != And.getValueType())
17296     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17297
17298   // The algorithm mentioned above uses:
17299   //    v = (v * 0x01010101...) >> (Len - 8)
17300   //
17301   // Change it to use vector adds + vector shifts which yield faster results on
17302   // Haswell than using vector integer multiplication.
17303   //
17304   // For i32 elements:
17305   //    v = v + (v >> 8)
17306   //    v = v + (v >> 16)
17307   //
17308   // For i64 elements:
17309   //    v = v + (v >> 8)
17310   //    v = v + (v >> 16)
17311   //    v = v + (v >> 32)
17312   //
17313   Add = And;
17314   SmallVector<SDValue, 8> Csts;
17315   for (unsigned i = 8; i <= Len/2; i *= 2) {
17316     Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17317     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17318     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17319     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17320     Csts.clear();
17321   }
17322
17323   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17324   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17325                                   EltVT);
17326   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17327   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17328   if (NeedsBitcast) {
17329     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17330     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17331   }
17332   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17333   if (VT != And.getValueType())
17334     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17335
17336   return And;
17337 }
17338
17339 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17340   SDNode *Node = Op.getNode();
17341   SDLoc dl(Node);
17342   EVT T = Node->getValueType(0);
17343   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17344                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17345   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17346                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17347                        Node->getOperand(0),
17348                        Node->getOperand(1), negOp,
17349                        cast<AtomicSDNode>(Node)->getMemOperand(),
17350                        cast<AtomicSDNode>(Node)->getOrdering(),
17351                        cast<AtomicSDNode>(Node)->getSynchScope());
17352 }
17353
17354 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17355   SDNode *Node = Op.getNode();
17356   SDLoc dl(Node);
17357   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17358
17359   // Convert seq_cst store -> xchg
17360   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17361   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17362   //        (The only way to get a 16-byte store is cmpxchg16b)
17363   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17364   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17365       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17366     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17367                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17368                                  Node->getOperand(0),
17369                                  Node->getOperand(1), Node->getOperand(2),
17370                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17371                                  cast<AtomicSDNode>(Node)->getOrdering(),
17372                                  cast<AtomicSDNode>(Node)->getSynchScope());
17373     return Swap.getValue(1);
17374   }
17375   // Other atomic stores have a simple pattern.
17376   return Op;
17377 }
17378
17379 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17380   EVT VT = Op.getNode()->getSimpleValueType(0);
17381
17382   // Let legalize expand this if it isn't a legal type yet.
17383   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17384     return SDValue();
17385
17386   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17387
17388   unsigned Opc;
17389   bool ExtraOp = false;
17390   switch (Op.getOpcode()) {
17391   default: llvm_unreachable("Invalid code");
17392   case ISD::ADDC: Opc = X86ISD::ADD; break;
17393   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17394   case ISD::SUBC: Opc = X86ISD::SUB; break;
17395   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17396   }
17397
17398   if (!ExtraOp)
17399     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17400                        Op.getOperand(1));
17401   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17402                      Op.getOperand(1), Op.getOperand(2));
17403 }
17404
17405 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17406                             SelectionDAG &DAG) {
17407   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17408
17409   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17410   // which returns the values as { float, float } (in XMM0) or
17411   // { double, double } (which is returned in XMM0, XMM1).
17412   SDLoc dl(Op);
17413   SDValue Arg = Op.getOperand(0);
17414   EVT ArgVT = Arg.getValueType();
17415   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17416
17417   TargetLowering::ArgListTy Args;
17418   TargetLowering::ArgListEntry Entry;
17419
17420   Entry.Node = Arg;
17421   Entry.Ty = ArgTy;
17422   Entry.isSExt = false;
17423   Entry.isZExt = false;
17424   Args.push_back(Entry);
17425
17426   bool isF64 = ArgVT == MVT::f64;
17427   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17428   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17429   // the results are returned via SRet in memory.
17430   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17431   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17432   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17433
17434   Type *RetTy = isF64
17435     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17436     : (Type*)VectorType::get(ArgTy, 4);
17437
17438   TargetLowering::CallLoweringInfo CLI(DAG);
17439   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17440     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17441
17442   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17443
17444   if (isF64)
17445     // Returned in xmm0 and xmm1.
17446     return CallResult.first;
17447
17448   // Returned in bits 0:31 and 32:64 xmm0.
17449   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17450                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17451   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17452                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17453   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17454   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17455 }
17456
17457 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17458                              SelectionDAG &DAG) {
17459   assert(Subtarget->hasAVX512() &&
17460          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17461
17462   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17463   EVT VT = N->getValue().getValueType();
17464   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17465   SDLoc dl(Op);
17466
17467   // X86 scatter kills mask register, so its type should be added to
17468   // the list of return values
17469   if (N->getNumValues() == 1) {
17470     SDValue Index = N->getIndex();
17471     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17472         !Index.getValueType().is512BitVector())
17473       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17474
17475     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17476     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17477                       N->getOperand(3), Index };
17478
17479     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17480     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17481     return SDValue(NewScatter.getNode(), 0);
17482   }
17483   return Op;
17484 }
17485
17486 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17487                             SelectionDAG &DAG) {
17488   assert(Subtarget->hasAVX512() &&
17489          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17490
17491   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17492   EVT VT = Op.getValueType();
17493   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17494   SDLoc dl(Op);
17495
17496   SDValue Index = N->getIndex();
17497   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17498       !Index.getValueType().is512BitVector()) {
17499     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17500     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17501                       N->getOperand(3), Index };
17502     DAG.UpdateNodeOperands(N, Ops);
17503   }
17504   return Op;
17505 }
17506
17507 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17508                                                     SelectionDAG &DAG) const {
17509   // TODO: Eventually, the lowering of these nodes should be informed by or
17510   // deferred to the GC strategy for the function in which they appear. For
17511   // now, however, they must be lowered to something. Since they are logically
17512   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17513   // require special handling for these nodes), lower them as literal NOOPs for
17514   // the time being.
17515   SmallVector<SDValue, 2> Ops;
17516
17517   Ops.push_back(Op.getOperand(0));
17518   if (Op->getGluedNode())
17519     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17520
17521   SDLoc OpDL(Op);
17522   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17523   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17524
17525   return NOOP;
17526 }
17527
17528 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17529                                                   SelectionDAG &DAG) const {
17530   // TODO: Eventually, the lowering of these nodes should be informed by or
17531   // deferred to the GC strategy for the function in which they appear. For
17532   // now, however, they must be lowered to something. Since they are logically
17533   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17534   // require special handling for these nodes), lower them as literal NOOPs for
17535   // the time being.
17536   SmallVector<SDValue, 2> Ops;
17537
17538   Ops.push_back(Op.getOperand(0));
17539   if (Op->getGluedNode())
17540     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17541
17542   SDLoc OpDL(Op);
17543   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17544   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17545
17546   return NOOP;
17547 }
17548
17549 /// LowerOperation - Provide custom lowering hooks for some operations.
17550 ///
17551 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17552   switch (Op.getOpcode()) {
17553   default: llvm_unreachable("Should not custom lower this!");
17554   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17555   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17556     return LowerCMP_SWAP(Op, Subtarget, DAG);
17557   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17558   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17559   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17560   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17561   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17562   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17563   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17564   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17565   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17566   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17567   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17568   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17569   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17570   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17571   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17572   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17573   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17574   case ISD::SHL_PARTS:
17575   case ISD::SRA_PARTS:
17576   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17577   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17578   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17579   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17580   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17581   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17582   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17583   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17584   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17585   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17586   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17587   case ISD::FABS:
17588   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17589   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17590   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17591   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17592   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17593   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17594   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17595   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17596   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17597   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17598   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17599   case ISD::INTRINSIC_VOID:
17600   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17601   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17602   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17603   case ISD::FRAME_TO_ARGS_OFFSET:
17604                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17605   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17606   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17607   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17608   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17609   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17610   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17611   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17612   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17613   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17614   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17615   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17616   case ISD::UMUL_LOHI:
17617   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17618   case ISD::SRA:
17619   case ISD::SRL:
17620   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17621   case ISD::SADDO:
17622   case ISD::UADDO:
17623   case ISD::SSUBO:
17624   case ISD::USUBO:
17625   case ISD::SMULO:
17626   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17627   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17628   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17629   case ISD::ADDC:
17630   case ISD::ADDE:
17631   case ISD::SUBC:
17632   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17633   case ISD::ADD:                return LowerADD(Op, DAG);
17634   case ISD::SUB:                return LowerSUB(Op, DAG);
17635   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17636   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
17637   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
17638   case ISD::GC_TRANSITION_START:
17639                                 return LowerGC_TRANSITION_START(Op, DAG);
17640   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
17641   }
17642 }
17643
17644 /// ReplaceNodeResults - Replace a node with an illegal result type
17645 /// with a new node built out of custom code.
17646 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17647                                            SmallVectorImpl<SDValue>&Results,
17648                                            SelectionDAG &DAG) const {
17649   SDLoc dl(N);
17650   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17651   switch (N->getOpcode()) {
17652   default:
17653     llvm_unreachable("Do not know how to custom type legalize this operation!");
17654   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17655   case X86ISD::FMINC:
17656   case X86ISD::FMIN:
17657   case X86ISD::FMAXC:
17658   case X86ISD::FMAX: {
17659     EVT VT = N->getValueType(0);
17660     if (VT != MVT::v2f32)
17661       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17662     SDValue UNDEF = DAG.getUNDEF(VT);
17663     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17664                               N->getOperand(0), UNDEF);
17665     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17666                               N->getOperand(1), UNDEF);
17667     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17668     return;
17669   }
17670   case ISD::SIGN_EXTEND_INREG:
17671   case ISD::ADDC:
17672   case ISD::ADDE:
17673   case ISD::SUBC:
17674   case ISD::SUBE:
17675     // We don't want to expand or promote these.
17676     return;
17677   case ISD::SDIV:
17678   case ISD::UDIV:
17679   case ISD::SREM:
17680   case ISD::UREM:
17681   case ISD::SDIVREM:
17682   case ISD::UDIVREM: {
17683     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17684     Results.push_back(V);
17685     return;
17686   }
17687   case ISD::FP_TO_SINT:
17688     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
17689     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17690     if (N->getOperand(0).getValueType() == MVT::f16)
17691       break;
17692     // fallthrough
17693   case ISD::FP_TO_UINT: {
17694     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17695
17696     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17697       return;
17698
17699     std::pair<SDValue,SDValue> Vals =
17700         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17701     SDValue FIST = Vals.first, StackSlot = Vals.second;
17702     if (FIST.getNode()) {
17703       EVT VT = N->getValueType(0);
17704       // Return a load from the stack slot.
17705       if (StackSlot.getNode())
17706         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17707                                       MachinePointerInfo(),
17708                                       false, false, false, 0));
17709       else
17710         Results.push_back(FIST);
17711     }
17712     return;
17713   }
17714   case ISD::UINT_TO_FP: {
17715     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17716     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17717         N->getValueType(0) != MVT::v2f32)
17718       return;
17719     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17720                                  N->getOperand(0));
17721     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17722                                      MVT::f64);
17723     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17724     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17725                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17726     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17727     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17728     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17729     return;
17730   }
17731   case ISD::FP_ROUND: {
17732     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17733         return;
17734     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17735     Results.push_back(V);
17736     return;
17737   }
17738   case ISD::FP_EXTEND: {
17739     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17740     // No other ValueType for FP_EXTEND should reach this point.
17741     assert(N->getValueType(0) == MVT::v2f32 &&
17742            "Do not know how to legalize this Node");
17743     return;
17744   }
17745   case ISD::INTRINSIC_W_CHAIN: {
17746     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17747     switch (IntNo) {
17748     default : llvm_unreachable("Do not know how to custom type "
17749                                "legalize this intrinsic operation!");
17750     case Intrinsic::x86_rdtsc:
17751       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17752                                      Results);
17753     case Intrinsic::x86_rdtscp:
17754       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17755                                      Results);
17756     case Intrinsic::x86_rdpmc:
17757       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17758     }
17759   }
17760   case ISD::READCYCLECOUNTER: {
17761     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17762                                    Results);
17763   }
17764   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17765     EVT T = N->getValueType(0);
17766     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17767     bool Regs64bit = T == MVT::i128;
17768     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17769     SDValue cpInL, cpInH;
17770     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17771                         DAG.getConstant(0, dl, HalfT));
17772     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17773                         DAG.getConstant(1, dl, HalfT));
17774     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17775                              Regs64bit ? X86::RAX : X86::EAX,
17776                              cpInL, SDValue());
17777     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17778                              Regs64bit ? X86::RDX : X86::EDX,
17779                              cpInH, cpInL.getValue(1));
17780     SDValue swapInL, swapInH;
17781     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17782                           DAG.getConstant(0, dl, HalfT));
17783     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17784                           DAG.getConstant(1, dl, HalfT));
17785     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17786                                Regs64bit ? X86::RBX : X86::EBX,
17787                                swapInL, cpInH.getValue(1));
17788     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17789                                Regs64bit ? X86::RCX : X86::ECX,
17790                                swapInH, swapInL.getValue(1));
17791     SDValue Ops[] = { swapInH.getValue(0),
17792                       N->getOperand(1),
17793                       swapInH.getValue(1) };
17794     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17795     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17796     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17797                                   X86ISD::LCMPXCHG8_DAG;
17798     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17799     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17800                                         Regs64bit ? X86::RAX : X86::EAX,
17801                                         HalfT, Result.getValue(1));
17802     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17803                                         Regs64bit ? X86::RDX : X86::EDX,
17804                                         HalfT, cpOutL.getValue(2));
17805     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17806
17807     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17808                                         MVT::i32, cpOutH.getValue(2));
17809     SDValue Success =
17810         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17811                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17812     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17813
17814     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17815     Results.push_back(Success);
17816     Results.push_back(EFLAGS.getValue(1));
17817     return;
17818   }
17819   case ISD::ATOMIC_SWAP:
17820   case ISD::ATOMIC_LOAD_ADD:
17821   case ISD::ATOMIC_LOAD_SUB:
17822   case ISD::ATOMIC_LOAD_AND:
17823   case ISD::ATOMIC_LOAD_OR:
17824   case ISD::ATOMIC_LOAD_XOR:
17825   case ISD::ATOMIC_LOAD_NAND:
17826   case ISD::ATOMIC_LOAD_MIN:
17827   case ISD::ATOMIC_LOAD_MAX:
17828   case ISD::ATOMIC_LOAD_UMIN:
17829   case ISD::ATOMIC_LOAD_UMAX:
17830   case ISD::ATOMIC_LOAD: {
17831     // Delegate to generic TypeLegalization. Situations we can really handle
17832     // should have already been dealt with by AtomicExpandPass.cpp.
17833     break;
17834   }
17835   case ISD::BITCAST: {
17836     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17837     EVT DstVT = N->getValueType(0);
17838     EVT SrcVT = N->getOperand(0)->getValueType(0);
17839
17840     if (SrcVT != MVT::f64 ||
17841         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17842       return;
17843
17844     unsigned NumElts = DstVT.getVectorNumElements();
17845     EVT SVT = DstVT.getVectorElementType();
17846     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17847     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17848                                    MVT::v2f64, N->getOperand(0));
17849     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17850
17851     if (ExperimentalVectorWideningLegalization) {
17852       // If we are legalizing vectors by widening, we already have the desired
17853       // legal vector type, just return it.
17854       Results.push_back(ToVecInt);
17855       return;
17856     }
17857
17858     SmallVector<SDValue, 8> Elts;
17859     for (unsigned i = 0, e = NumElts; i != e; ++i)
17860       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17861                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
17862
17863     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17864   }
17865   }
17866 }
17867
17868 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17869   switch ((X86ISD::NodeType)Opcode) {
17870   case X86ISD::FIRST_NUMBER:       break;
17871   case X86ISD::BSF:                return "X86ISD::BSF";
17872   case X86ISD::BSR:                return "X86ISD::BSR";
17873   case X86ISD::SHLD:               return "X86ISD::SHLD";
17874   case X86ISD::SHRD:               return "X86ISD::SHRD";
17875   case X86ISD::FAND:               return "X86ISD::FAND";
17876   case X86ISD::FANDN:              return "X86ISD::FANDN";
17877   case X86ISD::FOR:                return "X86ISD::FOR";
17878   case X86ISD::FXOR:               return "X86ISD::FXOR";
17879   case X86ISD::FSRL:               return "X86ISD::FSRL";
17880   case X86ISD::FILD:               return "X86ISD::FILD";
17881   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17882   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17883   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17884   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17885   case X86ISD::FLD:                return "X86ISD::FLD";
17886   case X86ISD::FST:                return "X86ISD::FST";
17887   case X86ISD::CALL:               return "X86ISD::CALL";
17888   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17889   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17890   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17891   case X86ISD::BT:                 return "X86ISD::BT";
17892   case X86ISD::CMP:                return "X86ISD::CMP";
17893   case X86ISD::COMI:               return "X86ISD::COMI";
17894   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17895   case X86ISD::CMPM:               return "X86ISD::CMPM";
17896   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17897   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
17898   case X86ISD::SETCC:              return "X86ISD::SETCC";
17899   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17900   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17901   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
17902   case X86ISD::CMOV:               return "X86ISD::CMOV";
17903   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17904   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17905   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17906   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17907   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17908   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17909   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17910   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
17911   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
17912   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
17913   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17914   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17915   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17916   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17917   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17918   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
17919   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17920   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17921   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17922   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17923   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17924   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
17925   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17926   case X86ISD::HADD:               return "X86ISD::HADD";
17927   case X86ISD::HSUB:               return "X86ISD::HSUB";
17928   case X86ISD::FHADD:              return "X86ISD::FHADD";
17929   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17930   case X86ISD::UMAX:               return "X86ISD::UMAX";
17931   case X86ISD::UMIN:               return "X86ISD::UMIN";
17932   case X86ISD::SMAX:               return "X86ISD::SMAX";
17933   case X86ISD::SMIN:               return "X86ISD::SMIN";
17934   case X86ISD::FMAX:               return "X86ISD::FMAX";
17935   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
17936   case X86ISD::FMIN:               return "X86ISD::FMIN";
17937   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
17938   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17939   case X86ISD::FMINC:              return "X86ISD::FMINC";
17940   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17941   case X86ISD::FRCP:               return "X86ISD::FRCP";
17942   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17943   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17944   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17945   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17946   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17947   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17948   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17949   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17950   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17951   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17952   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17953   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17954   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17955   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17956   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17957   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17958   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17959   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17960   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17961   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17962   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17963   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17964   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17965   case X86ISD::VSHL:               return "X86ISD::VSHL";
17966   case X86ISD::VSRL:               return "X86ISD::VSRL";
17967   case X86ISD::VSRA:               return "X86ISD::VSRA";
17968   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17969   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17970   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17971   case X86ISD::CMPP:               return "X86ISD::CMPP";
17972   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17973   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17974   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17975   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17976   case X86ISD::ADD:                return "X86ISD::ADD";
17977   case X86ISD::SUB:                return "X86ISD::SUB";
17978   case X86ISD::ADC:                return "X86ISD::ADC";
17979   case X86ISD::SBB:                return "X86ISD::SBB";
17980   case X86ISD::SMUL:               return "X86ISD::SMUL";
17981   case X86ISD::UMUL:               return "X86ISD::UMUL";
17982   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17983   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17984   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17985   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17986   case X86ISD::INC:                return "X86ISD::INC";
17987   case X86ISD::DEC:                return "X86ISD::DEC";
17988   case X86ISD::OR:                 return "X86ISD::OR";
17989   case X86ISD::XOR:                return "X86ISD::XOR";
17990   case X86ISD::AND:                return "X86ISD::AND";
17991   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17992   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17993   case X86ISD::PTEST:              return "X86ISD::PTEST";
17994   case X86ISD::TESTP:              return "X86ISD::TESTP";
17995   case X86ISD::TESTM:              return "X86ISD::TESTM";
17996   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17997   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17998   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17999   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
18000   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
18001   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
18002   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
18003   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
18004   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
18005   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
18006   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
18007   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
18008   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
18009   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
18010   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
18011   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
18012   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
18013   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
18014   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
18015   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
18016   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
18017   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18018   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18019   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
18020   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18021   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
18022   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18023   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18024   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18025   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18026   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18027   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18028   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18029   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18030   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18031   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
18032   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
18033   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
18034   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
18035   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
18036   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
18037   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18038   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18039   case X86ISD::SAHF:               return "X86ISD::SAHF";
18040   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18041   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18042   case X86ISD::FMADD:              return "X86ISD::FMADD";
18043   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18044   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18045   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18046   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18047   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18048   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18049   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18050   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18051   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18052   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18053   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18054   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18055   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18056   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18057   case X86ISD::XTEST:              return "X86ISD::XTEST";
18058   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18059   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18060   case X86ISD::SELECT:             return "X86ISD::SELECT";
18061   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18062   case X86ISD::RCP28:              return "X86ISD::RCP28";
18063   case X86ISD::EXP2:               return "X86ISD::EXP2";
18064   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18065   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18066   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18067   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18068   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18069   case X86ISD::ADDS:               return "X86ISD::ADDS";
18070   case X86ISD::SUBS:               return "X86ISD::SUBS";
18071   }
18072   return nullptr;
18073 }
18074
18075 // isLegalAddressingMode - Return true if the addressing mode represented
18076 // by AM is legal for this target, for a load/store of the specified type.
18077 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18078                                               Type *Ty) const {
18079   // X86 supports extremely general addressing modes.
18080   CodeModel::Model M = getTargetMachine().getCodeModel();
18081   Reloc::Model R = getTargetMachine().getRelocationModel();
18082
18083   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18084   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18085     return false;
18086
18087   if (AM.BaseGV) {
18088     unsigned GVFlags =
18089       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18090
18091     // If a reference to this global requires an extra load, we can't fold it.
18092     if (isGlobalStubReference(GVFlags))
18093       return false;
18094
18095     // If BaseGV requires a register for the PIC base, we cannot also have a
18096     // BaseReg specified.
18097     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18098       return false;
18099
18100     // If lower 4G is not available, then we must use rip-relative addressing.
18101     if ((M != CodeModel::Small || R != Reloc::Static) &&
18102         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18103       return false;
18104   }
18105
18106   switch (AM.Scale) {
18107   case 0:
18108   case 1:
18109   case 2:
18110   case 4:
18111   case 8:
18112     // These scales always work.
18113     break;
18114   case 3:
18115   case 5:
18116   case 9:
18117     // These scales are formed with basereg+scalereg.  Only accept if there is
18118     // no basereg yet.
18119     if (AM.HasBaseReg)
18120       return false;
18121     break;
18122   default:  // Other stuff never works.
18123     return false;
18124   }
18125
18126   return true;
18127 }
18128
18129 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18130   unsigned Bits = Ty->getScalarSizeInBits();
18131
18132   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18133   // particularly cheaper than those without.
18134   if (Bits == 8)
18135     return false;
18136
18137   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18138   // variable shifts just as cheap as scalar ones.
18139   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18140     return false;
18141
18142   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18143   // fully general vector.
18144   return true;
18145 }
18146
18147 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18148   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18149     return false;
18150   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18151   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18152   return NumBits1 > NumBits2;
18153 }
18154
18155 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18156   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18157     return false;
18158
18159   if (!isTypeLegal(EVT::getEVT(Ty1)))
18160     return false;
18161
18162   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18163
18164   // Assuming the caller doesn't have a zeroext or signext return parameter,
18165   // truncation all the way down to i1 is valid.
18166   return true;
18167 }
18168
18169 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18170   return isInt<32>(Imm);
18171 }
18172
18173 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18174   // Can also use sub to handle negated immediates.
18175   return isInt<32>(Imm);
18176 }
18177
18178 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18179   if (!VT1.isInteger() || !VT2.isInteger())
18180     return false;
18181   unsigned NumBits1 = VT1.getSizeInBits();
18182   unsigned NumBits2 = VT2.getSizeInBits();
18183   return NumBits1 > NumBits2;
18184 }
18185
18186 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18187   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18188   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18189 }
18190
18191 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18192   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18193   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18194 }
18195
18196 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18197   EVT VT1 = Val.getValueType();
18198   if (isZExtFree(VT1, VT2))
18199     return true;
18200
18201   if (Val.getOpcode() != ISD::LOAD)
18202     return false;
18203
18204   if (!VT1.isSimple() || !VT1.isInteger() ||
18205       !VT2.isSimple() || !VT2.isInteger())
18206     return false;
18207
18208   switch (VT1.getSimpleVT().SimpleTy) {
18209   default: break;
18210   case MVT::i8:
18211   case MVT::i16:
18212   case MVT::i32:
18213     // X86 has 8, 16, and 32-bit zero-extending loads.
18214     return true;
18215   }
18216
18217   return false;
18218 }
18219
18220 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18221
18222 bool
18223 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18224   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18225     return false;
18226
18227   VT = VT.getScalarType();
18228
18229   if (!VT.isSimple())
18230     return false;
18231
18232   switch (VT.getSimpleVT().SimpleTy) {
18233   case MVT::f32:
18234   case MVT::f64:
18235     return true;
18236   default:
18237     break;
18238   }
18239
18240   return false;
18241 }
18242
18243 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18244   // i16 instructions are longer (0x66 prefix) and potentially slower.
18245   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18246 }
18247
18248 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18249 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18250 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18251 /// are assumed to be legal.
18252 bool
18253 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18254                                       EVT VT) const {
18255   if (!VT.isSimple())
18256     return false;
18257
18258   // Not for i1 vectors
18259   if (VT.getScalarType() == MVT::i1)
18260     return false;
18261
18262   // Very little shuffling can be done for 64-bit vectors right now.
18263   if (VT.getSizeInBits() == 64)
18264     return false;
18265
18266   // We only care that the types being shuffled are legal. The lowering can
18267   // handle any possible shuffle mask that results.
18268   return isTypeLegal(VT.getSimpleVT());
18269 }
18270
18271 bool
18272 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18273                                           EVT VT) const {
18274   // Just delegate to the generic legality, clear masks aren't special.
18275   return isShuffleMaskLegal(Mask, VT);
18276 }
18277
18278 //===----------------------------------------------------------------------===//
18279 //                           X86 Scheduler Hooks
18280 //===----------------------------------------------------------------------===//
18281
18282 /// Utility function to emit xbegin specifying the start of an RTM region.
18283 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18284                                      const TargetInstrInfo *TII) {
18285   DebugLoc DL = MI->getDebugLoc();
18286
18287   const BasicBlock *BB = MBB->getBasicBlock();
18288   MachineFunction::iterator I = MBB;
18289   ++I;
18290
18291   // For the v = xbegin(), we generate
18292   //
18293   // thisMBB:
18294   //  xbegin sinkMBB
18295   //
18296   // mainMBB:
18297   //  eax = -1
18298   //
18299   // sinkMBB:
18300   //  v = eax
18301
18302   MachineBasicBlock *thisMBB = MBB;
18303   MachineFunction *MF = MBB->getParent();
18304   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18305   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18306   MF->insert(I, mainMBB);
18307   MF->insert(I, sinkMBB);
18308
18309   // Transfer the remainder of BB and its successor edges to sinkMBB.
18310   sinkMBB->splice(sinkMBB->begin(), MBB,
18311                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18312   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18313
18314   // thisMBB:
18315   //  xbegin sinkMBB
18316   //  # fallthrough to mainMBB
18317   //  # abortion to sinkMBB
18318   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18319   thisMBB->addSuccessor(mainMBB);
18320   thisMBB->addSuccessor(sinkMBB);
18321
18322   // mainMBB:
18323   //  EAX = -1
18324   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18325   mainMBB->addSuccessor(sinkMBB);
18326
18327   // sinkMBB:
18328   // EAX is live into the sinkMBB
18329   sinkMBB->addLiveIn(X86::EAX);
18330   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18331           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18332     .addReg(X86::EAX);
18333
18334   MI->eraseFromParent();
18335   return sinkMBB;
18336 }
18337
18338 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18339 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18340 // in the .td file.
18341 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18342                                        const TargetInstrInfo *TII) {
18343   unsigned Opc;
18344   switch (MI->getOpcode()) {
18345   default: llvm_unreachable("illegal opcode!");
18346   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18347   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18348   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18349   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18350   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18351   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18352   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18353   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18354   }
18355
18356   DebugLoc dl = MI->getDebugLoc();
18357   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18358
18359   unsigned NumArgs = MI->getNumOperands();
18360   for (unsigned i = 1; i < NumArgs; ++i) {
18361     MachineOperand &Op = MI->getOperand(i);
18362     if (!(Op.isReg() && Op.isImplicit()))
18363       MIB.addOperand(Op);
18364   }
18365   if (MI->hasOneMemOperand())
18366     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18367
18368   BuildMI(*BB, MI, dl,
18369     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18370     .addReg(X86::XMM0);
18371
18372   MI->eraseFromParent();
18373   return BB;
18374 }
18375
18376 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18377 // defs in an instruction pattern
18378 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18379                                        const TargetInstrInfo *TII) {
18380   unsigned Opc;
18381   switch (MI->getOpcode()) {
18382   default: llvm_unreachable("illegal opcode!");
18383   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18384   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18385   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18386   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18387   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18388   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18389   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18390   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18391   }
18392
18393   DebugLoc dl = MI->getDebugLoc();
18394   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18395
18396   unsigned NumArgs = MI->getNumOperands(); // remove the results
18397   for (unsigned i = 1; i < NumArgs; ++i) {
18398     MachineOperand &Op = MI->getOperand(i);
18399     if (!(Op.isReg() && Op.isImplicit()))
18400       MIB.addOperand(Op);
18401   }
18402   if (MI->hasOneMemOperand())
18403     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18404
18405   BuildMI(*BB, MI, dl,
18406     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18407     .addReg(X86::ECX);
18408
18409   MI->eraseFromParent();
18410   return BB;
18411 }
18412
18413 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18414                                       const X86Subtarget *Subtarget) {
18415   DebugLoc dl = MI->getDebugLoc();
18416   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18417   // Address into RAX/EAX, other two args into ECX, EDX.
18418   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18419   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18420   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18421   for (int i = 0; i < X86::AddrNumOperands; ++i)
18422     MIB.addOperand(MI->getOperand(i));
18423
18424   unsigned ValOps = X86::AddrNumOperands;
18425   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18426     .addReg(MI->getOperand(ValOps).getReg());
18427   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18428     .addReg(MI->getOperand(ValOps+1).getReg());
18429
18430   // The instruction doesn't actually take any operands though.
18431   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18432
18433   MI->eraseFromParent(); // The pseudo is gone now.
18434   return BB;
18435 }
18436
18437 MachineBasicBlock *
18438 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18439                                                  MachineBasicBlock *MBB) const {
18440   // Emit va_arg instruction on X86-64.
18441
18442   // Operands to this pseudo-instruction:
18443   // 0  ) Output        : destination address (reg)
18444   // 1-5) Input         : va_list address (addr, i64mem)
18445   // 6  ) ArgSize       : Size (in bytes) of vararg type
18446   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18447   // 8  ) Align         : Alignment of type
18448   // 9  ) EFLAGS (implicit-def)
18449
18450   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18451   static_assert(X86::AddrNumOperands == 5,
18452                 "VAARG_64 assumes 5 address operands");
18453
18454   unsigned DestReg = MI->getOperand(0).getReg();
18455   MachineOperand &Base = MI->getOperand(1);
18456   MachineOperand &Scale = MI->getOperand(2);
18457   MachineOperand &Index = MI->getOperand(3);
18458   MachineOperand &Disp = MI->getOperand(4);
18459   MachineOperand &Segment = MI->getOperand(5);
18460   unsigned ArgSize = MI->getOperand(6).getImm();
18461   unsigned ArgMode = MI->getOperand(7).getImm();
18462   unsigned Align = MI->getOperand(8).getImm();
18463
18464   // Memory Reference
18465   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18466   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18467   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18468
18469   // Machine Information
18470   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18471   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18472   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18473   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18474   DebugLoc DL = MI->getDebugLoc();
18475
18476   // struct va_list {
18477   //   i32   gp_offset
18478   //   i32   fp_offset
18479   //   i64   overflow_area (address)
18480   //   i64   reg_save_area (address)
18481   // }
18482   // sizeof(va_list) = 24
18483   // alignment(va_list) = 8
18484
18485   unsigned TotalNumIntRegs = 6;
18486   unsigned TotalNumXMMRegs = 8;
18487   bool UseGPOffset = (ArgMode == 1);
18488   bool UseFPOffset = (ArgMode == 2);
18489   unsigned MaxOffset = TotalNumIntRegs * 8 +
18490                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18491
18492   /* Align ArgSize to a multiple of 8 */
18493   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18494   bool NeedsAlign = (Align > 8);
18495
18496   MachineBasicBlock *thisMBB = MBB;
18497   MachineBasicBlock *overflowMBB;
18498   MachineBasicBlock *offsetMBB;
18499   MachineBasicBlock *endMBB;
18500
18501   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18502   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18503   unsigned OffsetReg = 0;
18504
18505   if (!UseGPOffset && !UseFPOffset) {
18506     // If we only pull from the overflow region, we don't create a branch.
18507     // We don't need to alter control flow.
18508     OffsetDestReg = 0; // unused
18509     OverflowDestReg = DestReg;
18510
18511     offsetMBB = nullptr;
18512     overflowMBB = thisMBB;
18513     endMBB = thisMBB;
18514   } else {
18515     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18516     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18517     // If not, pull from overflow_area. (branch to overflowMBB)
18518     //
18519     //       thisMBB
18520     //         |     .
18521     //         |        .
18522     //     offsetMBB   overflowMBB
18523     //         |        .
18524     //         |     .
18525     //        endMBB
18526
18527     // Registers for the PHI in endMBB
18528     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18529     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18530
18531     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18532     MachineFunction *MF = MBB->getParent();
18533     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18534     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18535     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18536
18537     MachineFunction::iterator MBBIter = MBB;
18538     ++MBBIter;
18539
18540     // Insert the new basic blocks
18541     MF->insert(MBBIter, offsetMBB);
18542     MF->insert(MBBIter, overflowMBB);
18543     MF->insert(MBBIter, endMBB);
18544
18545     // Transfer the remainder of MBB and its successor edges to endMBB.
18546     endMBB->splice(endMBB->begin(), thisMBB,
18547                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18548     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18549
18550     // Make offsetMBB and overflowMBB successors of thisMBB
18551     thisMBB->addSuccessor(offsetMBB);
18552     thisMBB->addSuccessor(overflowMBB);
18553
18554     // endMBB is a successor of both offsetMBB and overflowMBB
18555     offsetMBB->addSuccessor(endMBB);
18556     overflowMBB->addSuccessor(endMBB);
18557
18558     // Load the offset value into a register
18559     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18560     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18561       .addOperand(Base)
18562       .addOperand(Scale)
18563       .addOperand(Index)
18564       .addDisp(Disp, UseFPOffset ? 4 : 0)
18565       .addOperand(Segment)
18566       .setMemRefs(MMOBegin, MMOEnd);
18567
18568     // Check if there is enough room left to pull this argument.
18569     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18570       .addReg(OffsetReg)
18571       .addImm(MaxOffset + 8 - ArgSizeA8);
18572
18573     // Branch to "overflowMBB" if offset >= max
18574     // Fall through to "offsetMBB" otherwise
18575     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18576       .addMBB(overflowMBB);
18577   }
18578
18579   // In offsetMBB, emit code to use the reg_save_area.
18580   if (offsetMBB) {
18581     assert(OffsetReg != 0);
18582
18583     // Read the reg_save_area address.
18584     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18585     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18586       .addOperand(Base)
18587       .addOperand(Scale)
18588       .addOperand(Index)
18589       .addDisp(Disp, 16)
18590       .addOperand(Segment)
18591       .setMemRefs(MMOBegin, MMOEnd);
18592
18593     // Zero-extend the offset
18594     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18595       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18596         .addImm(0)
18597         .addReg(OffsetReg)
18598         .addImm(X86::sub_32bit);
18599
18600     // Add the offset to the reg_save_area to get the final address.
18601     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18602       .addReg(OffsetReg64)
18603       .addReg(RegSaveReg);
18604
18605     // Compute the offset for the next argument
18606     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18607     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18608       .addReg(OffsetReg)
18609       .addImm(UseFPOffset ? 16 : 8);
18610
18611     // Store it back into the va_list.
18612     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18613       .addOperand(Base)
18614       .addOperand(Scale)
18615       .addOperand(Index)
18616       .addDisp(Disp, UseFPOffset ? 4 : 0)
18617       .addOperand(Segment)
18618       .addReg(NextOffsetReg)
18619       .setMemRefs(MMOBegin, MMOEnd);
18620
18621     // Jump to endMBB
18622     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18623       .addMBB(endMBB);
18624   }
18625
18626   //
18627   // Emit code to use overflow area
18628   //
18629
18630   // Load the overflow_area address into a register.
18631   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18632   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18633     .addOperand(Base)
18634     .addOperand(Scale)
18635     .addOperand(Index)
18636     .addDisp(Disp, 8)
18637     .addOperand(Segment)
18638     .setMemRefs(MMOBegin, MMOEnd);
18639
18640   // If we need to align it, do so. Otherwise, just copy the address
18641   // to OverflowDestReg.
18642   if (NeedsAlign) {
18643     // Align the overflow address
18644     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18645     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18646
18647     // aligned_addr = (addr + (align-1)) & ~(align-1)
18648     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18649       .addReg(OverflowAddrReg)
18650       .addImm(Align-1);
18651
18652     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18653       .addReg(TmpReg)
18654       .addImm(~(uint64_t)(Align-1));
18655   } else {
18656     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18657       .addReg(OverflowAddrReg);
18658   }
18659
18660   // Compute the next overflow address after this argument.
18661   // (the overflow address should be kept 8-byte aligned)
18662   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18663   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18664     .addReg(OverflowDestReg)
18665     .addImm(ArgSizeA8);
18666
18667   // Store the new overflow address.
18668   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18669     .addOperand(Base)
18670     .addOperand(Scale)
18671     .addOperand(Index)
18672     .addDisp(Disp, 8)
18673     .addOperand(Segment)
18674     .addReg(NextAddrReg)
18675     .setMemRefs(MMOBegin, MMOEnd);
18676
18677   // If we branched, emit the PHI to the front of endMBB.
18678   if (offsetMBB) {
18679     BuildMI(*endMBB, endMBB->begin(), DL,
18680             TII->get(X86::PHI), DestReg)
18681       .addReg(OffsetDestReg).addMBB(offsetMBB)
18682       .addReg(OverflowDestReg).addMBB(overflowMBB);
18683   }
18684
18685   // Erase the pseudo instruction
18686   MI->eraseFromParent();
18687
18688   return endMBB;
18689 }
18690
18691 MachineBasicBlock *
18692 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18693                                                  MachineInstr *MI,
18694                                                  MachineBasicBlock *MBB) const {
18695   // Emit code to save XMM registers to the stack. The ABI says that the
18696   // number of registers to save is given in %al, so it's theoretically
18697   // possible to do an indirect jump trick to avoid saving all of them,
18698   // however this code takes a simpler approach and just executes all
18699   // of the stores if %al is non-zero. It's less code, and it's probably
18700   // easier on the hardware branch predictor, and stores aren't all that
18701   // expensive anyway.
18702
18703   // Create the new basic blocks. One block contains all the XMM stores,
18704   // and one block is the final destination regardless of whether any
18705   // stores were performed.
18706   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18707   MachineFunction *F = MBB->getParent();
18708   MachineFunction::iterator MBBIter = MBB;
18709   ++MBBIter;
18710   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18711   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18712   F->insert(MBBIter, XMMSaveMBB);
18713   F->insert(MBBIter, EndMBB);
18714
18715   // Transfer the remainder of MBB and its successor edges to EndMBB.
18716   EndMBB->splice(EndMBB->begin(), MBB,
18717                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18718   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18719
18720   // The original block will now fall through to the XMM save block.
18721   MBB->addSuccessor(XMMSaveMBB);
18722   // The XMMSaveMBB will fall through to the end block.
18723   XMMSaveMBB->addSuccessor(EndMBB);
18724
18725   // Now add the instructions.
18726   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18727   DebugLoc DL = MI->getDebugLoc();
18728
18729   unsigned CountReg = MI->getOperand(0).getReg();
18730   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18731   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18732
18733   if (!Subtarget->isTargetWin64()) {
18734     // If %al is 0, branch around the XMM save block.
18735     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18736     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18737     MBB->addSuccessor(EndMBB);
18738   }
18739
18740   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18741   // that was just emitted, but clearly shouldn't be "saved".
18742   assert((MI->getNumOperands() <= 3 ||
18743           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18744           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18745          && "Expected last argument to be EFLAGS");
18746   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18747   // In the XMM save block, save all the XMM argument registers.
18748   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18749     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18750     MachineMemOperand *MMO =
18751       F->getMachineMemOperand(
18752           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18753         MachineMemOperand::MOStore,
18754         /*Size=*/16, /*Align=*/16);
18755     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18756       .addFrameIndex(RegSaveFrameIndex)
18757       .addImm(/*Scale=*/1)
18758       .addReg(/*IndexReg=*/0)
18759       .addImm(/*Disp=*/Offset)
18760       .addReg(/*Segment=*/0)
18761       .addReg(MI->getOperand(i).getReg())
18762       .addMemOperand(MMO);
18763   }
18764
18765   MI->eraseFromParent();   // The pseudo instruction is gone now.
18766
18767   return EndMBB;
18768 }
18769
18770 // The EFLAGS operand of SelectItr might be missing a kill marker
18771 // because there were multiple uses of EFLAGS, and ISel didn't know
18772 // which to mark. Figure out whether SelectItr should have had a
18773 // kill marker, and set it if it should. Returns the correct kill
18774 // marker value.
18775 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18776                                      MachineBasicBlock* BB,
18777                                      const TargetRegisterInfo* TRI) {
18778   // Scan forward through BB for a use/def of EFLAGS.
18779   MachineBasicBlock::iterator miI(std::next(SelectItr));
18780   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18781     const MachineInstr& mi = *miI;
18782     if (mi.readsRegister(X86::EFLAGS))
18783       return false;
18784     if (mi.definesRegister(X86::EFLAGS))
18785       break; // Should have kill-flag - update below.
18786   }
18787
18788   // If we hit the end of the block, check whether EFLAGS is live into a
18789   // successor.
18790   if (miI == BB->end()) {
18791     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18792                                           sEnd = BB->succ_end();
18793          sItr != sEnd; ++sItr) {
18794       MachineBasicBlock* succ = *sItr;
18795       if (succ->isLiveIn(X86::EFLAGS))
18796         return false;
18797     }
18798   }
18799
18800   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18801   // out. SelectMI should have a kill flag on EFLAGS.
18802   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18803   return true;
18804 }
18805
18806 MachineBasicBlock *
18807 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18808                                      MachineBasicBlock *BB) const {
18809   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18810   DebugLoc DL = MI->getDebugLoc();
18811
18812   // To "insert" a SELECT_CC instruction, we actually have to insert the
18813   // diamond control-flow pattern.  The incoming instruction knows the
18814   // destination vreg to set, the condition code register to branch on, the
18815   // true/false values to select between, and a branch opcode to use.
18816   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18817   MachineFunction::iterator It = BB;
18818   ++It;
18819
18820   //  thisMBB:
18821   //  ...
18822   //   TrueVal = ...
18823   //   cmpTY ccX, r1, r2
18824   //   bCC copy1MBB
18825   //   fallthrough --> copy0MBB
18826   MachineBasicBlock *thisMBB = BB;
18827   MachineFunction *F = BB->getParent();
18828
18829   // We also lower double CMOVs:
18830   //   (CMOV (CMOV F, T, cc1), T, cc2)
18831   // to two successives branches.  For that, we look for another CMOV as the
18832   // following instruction.
18833   //
18834   // Without this, we would add a PHI between the two jumps, which ends up
18835   // creating a few copies all around. For instance, for
18836   //
18837   //    (sitofp (zext (fcmp une)))
18838   //
18839   // we would generate:
18840   //
18841   //         ucomiss %xmm1, %xmm0
18842   //         movss  <1.0f>, %xmm0
18843   //         movaps  %xmm0, %xmm1
18844   //         jne     .LBB5_2
18845   //         xorps   %xmm1, %xmm1
18846   // .LBB5_2:
18847   //         jp      .LBB5_4
18848   //         movaps  %xmm1, %xmm0
18849   // .LBB5_4:
18850   //         retq
18851   //
18852   // because this custom-inserter would have generated:
18853   //
18854   //   A
18855   //   | \
18856   //   |  B
18857   //   | /
18858   //   C
18859   //   | \
18860   //   |  D
18861   //   | /
18862   //   E
18863   //
18864   // A: X = ...; Y = ...
18865   // B: empty
18866   // C: Z = PHI [X, A], [Y, B]
18867   // D: empty
18868   // E: PHI [X, C], [Z, D]
18869   //
18870   // If we lower both CMOVs in a single step, we can instead generate:
18871   //
18872   //   A
18873   //   | \
18874   //   |  C
18875   //   | /|
18876   //   |/ |
18877   //   |  |
18878   //   |  D
18879   //   | /
18880   //   E
18881   //
18882   // A: X = ...; Y = ...
18883   // D: empty
18884   // E: PHI [X, A], [X, C], [Y, D]
18885   //
18886   // Which, in our sitofp/fcmp example, gives us something like:
18887   //
18888   //         ucomiss %xmm1, %xmm0
18889   //         movss  <1.0f>, %xmm0
18890   //         jne     .LBB5_4
18891   //         jp      .LBB5_4
18892   //         xorps   %xmm0, %xmm0
18893   // .LBB5_4:
18894   //         retq
18895   //
18896   MachineInstr *NextCMOV = nullptr;
18897   MachineBasicBlock::iterator NextMIIt =
18898       std::next(MachineBasicBlock::iterator(MI));
18899   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18900       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18901       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18902     NextCMOV = &*NextMIIt;
18903
18904   MachineBasicBlock *jcc1MBB = nullptr;
18905
18906   // If we have a double CMOV, we lower it to two successive branches to
18907   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18908   if (NextCMOV) {
18909     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18910     F->insert(It, jcc1MBB);
18911     jcc1MBB->addLiveIn(X86::EFLAGS);
18912   }
18913
18914   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18915   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18916   F->insert(It, copy0MBB);
18917   F->insert(It, sinkMBB);
18918
18919   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18920   // live into the sink and copy blocks.
18921   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18922
18923   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18924   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18925       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18926     copy0MBB->addLiveIn(X86::EFLAGS);
18927     sinkMBB->addLiveIn(X86::EFLAGS);
18928   }
18929
18930   // Transfer the remainder of BB and its successor edges to sinkMBB.
18931   sinkMBB->splice(sinkMBB->begin(), BB,
18932                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18933   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18934
18935   // Add the true and fallthrough blocks as its successors.
18936   if (NextCMOV) {
18937     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18938     BB->addSuccessor(jcc1MBB);
18939
18940     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18941     // jump to the sinkMBB.
18942     jcc1MBB->addSuccessor(copy0MBB);
18943     jcc1MBB->addSuccessor(sinkMBB);
18944   } else {
18945     BB->addSuccessor(copy0MBB);
18946   }
18947
18948   // The true block target of the first (or only) branch is always sinkMBB.
18949   BB->addSuccessor(sinkMBB);
18950
18951   // Create the conditional branch instruction.
18952   unsigned Opc =
18953     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18954   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18955
18956   if (NextCMOV) {
18957     unsigned Opc2 = X86::GetCondBranchFromCond(
18958         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18959     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18960   }
18961
18962   //  copy0MBB:
18963   //   %FalseValue = ...
18964   //   # fallthrough to sinkMBB
18965   copy0MBB->addSuccessor(sinkMBB);
18966
18967   //  sinkMBB:
18968   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18969   //  ...
18970   MachineInstrBuilder MIB =
18971       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18972               MI->getOperand(0).getReg())
18973           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18974           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18975
18976   // If we have a double CMOV, the second Jcc provides the same incoming
18977   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18978   if (NextCMOV) {
18979     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18980     // Copy the PHI result to the register defined by the second CMOV.
18981     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18982             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18983         .addReg(MI->getOperand(0).getReg());
18984     NextCMOV->eraseFromParent();
18985   }
18986
18987   MI->eraseFromParent();   // The pseudo instruction is gone now.
18988   return sinkMBB;
18989 }
18990
18991 MachineBasicBlock *
18992 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18993                                         MachineBasicBlock *BB) const {
18994   MachineFunction *MF = BB->getParent();
18995   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18996   DebugLoc DL = MI->getDebugLoc();
18997   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18998
18999   assert(MF->shouldSplitStack());
19000
19001   const bool Is64Bit = Subtarget->is64Bit();
19002   const bool IsLP64 = Subtarget->isTarget64BitLP64();
19003
19004   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19005   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19006
19007   // BB:
19008   //  ... [Till the alloca]
19009   // If stacklet is not large enough, jump to mallocMBB
19010   //
19011   // bumpMBB:
19012   //  Allocate by subtracting from RSP
19013   //  Jump to continueMBB
19014   //
19015   // mallocMBB:
19016   //  Allocate by call to runtime
19017   //
19018   // continueMBB:
19019   //  ...
19020   //  [rest of original BB]
19021   //
19022
19023   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19024   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19025   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19026
19027   MachineRegisterInfo &MRI = MF->getRegInfo();
19028   const TargetRegisterClass *AddrRegClass =
19029     getRegClassFor(getPointerTy());
19030
19031   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19032     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19033     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19034     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19035     sizeVReg = MI->getOperand(1).getReg(),
19036     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19037
19038   MachineFunction::iterator MBBIter = BB;
19039   ++MBBIter;
19040
19041   MF->insert(MBBIter, bumpMBB);
19042   MF->insert(MBBIter, mallocMBB);
19043   MF->insert(MBBIter, continueMBB);
19044
19045   continueMBB->splice(continueMBB->begin(), BB,
19046                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19047   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19048
19049   // Add code to the main basic block to check if the stack limit has been hit,
19050   // and if so, jump to mallocMBB otherwise to bumpMBB.
19051   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19052   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19053     .addReg(tmpSPVReg).addReg(sizeVReg);
19054   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19055     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19056     .addReg(SPLimitVReg);
19057   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19058
19059   // bumpMBB simply decreases the stack pointer, since we know the current
19060   // stacklet has enough space.
19061   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19062     .addReg(SPLimitVReg);
19063   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19064     .addReg(SPLimitVReg);
19065   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19066
19067   // Calls into a routine in libgcc to allocate more space from the heap.
19068   const uint32_t *RegMask =
19069       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19070   if (IsLP64) {
19071     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19072       .addReg(sizeVReg);
19073     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19074       .addExternalSymbol("__morestack_allocate_stack_space")
19075       .addRegMask(RegMask)
19076       .addReg(X86::RDI, RegState::Implicit)
19077       .addReg(X86::RAX, RegState::ImplicitDefine);
19078   } else if (Is64Bit) {
19079     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19080       .addReg(sizeVReg);
19081     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19082       .addExternalSymbol("__morestack_allocate_stack_space")
19083       .addRegMask(RegMask)
19084       .addReg(X86::EDI, RegState::Implicit)
19085       .addReg(X86::EAX, RegState::ImplicitDefine);
19086   } else {
19087     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19088       .addImm(12);
19089     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19090     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19091       .addExternalSymbol("__morestack_allocate_stack_space")
19092       .addRegMask(RegMask)
19093       .addReg(X86::EAX, RegState::ImplicitDefine);
19094   }
19095
19096   if (!Is64Bit)
19097     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19098       .addImm(16);
19099
19100   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19101     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19102   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19103
19104   // Set up the CFG correctly.
19105   BB->addSuccessor(bumpMBB);
19106   BB->addSuccessor(mallocMBB);
19107   mallocMBB->addSuccessor(continueMBB);
19108   bumpMBB->addSuccessor(continueMBB);
19109
19110   // Take care of the PHI nodes.
19111   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19112           MI->getOperand(0).getReg())
19113     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19114     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19115
19116   // Delete the original pseudo instruction.
19117   MI->eraseFromParent();
19118
19119   // And we're done.
19120   return continueMBB;
19121 }
19122
19123 MachineBasicBlock *
19124 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19125                                         MachineBasicBlock *BB) const {
19126   DebugLoc DL = MI->getDebugLoc();
19127
19128   assert(!Subtarget->isTargetMachO());
19129
19130   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19131
19132   MI->eraseFromParent();   // The pseudo instruction is gone now.
19133   return BB;
19134 }
19135
19136 MachineBasicBlock *
19137 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19138                                       MachineBasicBlock *BB) const {
19139   // This is pretty easy.  We're taking the value that we received from
19140   // our load from the relocation, sticking it in either RDI (x86-64)
19141   // or EAX and doing an indirect call.  The return value will then
19142   // be in the normal return register.
19143   MachineFunction *F = BB->getParent();
19144   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19145   DebugLoc DL = MI->getDebugLoc();
19146
19147   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19148   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19149
19150   // Get a register mask for the lowered call.
19151   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19152   // proper register mask.
19153   const uint32_t *RegMask =
19154       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19155   if (Subtarget->is64Bit()) {
19156     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19157                                       TII->get(X86::MOV64rm), X86::RDI)
19158     .addReg(X86::RIP)
19159     .addImm(0).addReg(0)
19160     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19161                       MI->getOperand(3).getTargetFlags())
19162     .addReg(0);
19163     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19164     addDirectMem(MIB, X86::RDI);
19165     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19166   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19167     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19168                                       TII->get(X86::MOV32rm), X86::EAX)
19169     .addReg(0)
19170     .addImm(0).addReg(0)
19171     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19172                       MI->getOperand(3).getTargetFlags())
19173     .addReg(0);
19174     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19175     addDirectMem(MIB, X86::EAX);
19176     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19177   } else {
19178     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19179                                       TII->get(X86::MOV32rm), X86::EAX)
19180     .addReg(TII->getGlobalBaseReg(F))
19181     .addImm(0).addReg(0)
19182     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19183                       MI->getOperand(3).getTargetFlags())
19184     .addReg(0);
19185     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19186     addDirectMem(MIB, X86::EAX);
19187     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19188   }
19189
19190   MI->eraseFromParent(); // The pseudo instruction is gone now.
19191   return BB;
19192 }
19193
19194 MachineBasicBlock *
19195 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19196                                     MachineBasicBlock *MBB) const {
19197   DebugLoc DL = MI->getDebugLoc();
19198   MachineFunction *MF = MBB->getParent();
19199   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19200   MachineRegisterInfo &MRI = MF->getRegInfo();
19201
19202   const BasicBlock *BB = MBB->getBasicBlock();
19203   MachineFunction::iterator I = MBB;
19204   ++I;
19205
19206   // Memory Reference
19207   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19208   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19209
19210   unsigned DstReg;
19211   unsigned MemOpndSlot = 0;
19212
19213   unsigned CurOp = 0;
19214
19215   DstReg = MI->getOperand(CurOp++).getReg();
19216   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19217   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19218   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19219   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19220
19221   MemOpndSlot = CurOp;
19222
19223   MVT PVT = getPointerTy();
19224   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19225          "Invalid Pointer Size!");
19226
19227   // For v = setjmp(buf), we generate
19228   //
19229   // thisMBB:
19230   //  buf[LabelOffset] = restoreMBB
19231   //  SjLjSetup restoreMBB
19232   //
19233   // mainMBB:
19234   //  v_main = 0
19235   //
19236   // sinkMBB:
19237   //  v = phi(main, restore)
19238   //
19239   // restoreMBB:
19240   //  if base pointer being used, load it from frame
19241   //  v_restore = 1
19242
19243   MachineBasicBlock *thisMBB = MBB;
19244   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19245   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19246   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19247   MF->insert(I, mainMBB);
19248   MF->insert(I, sinkMBB);
19249   MF->push_back(restoreMBB);
19250
19251   MachineInstrBuilder MIB;
19252
19253   // Transfer the remainder of BB and its successor edges to sinkMBB.
19254   sinkMBB->splice(sinkMBB->begin(), MBB,
19255                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19256   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19257
19258   // thisMBB:
19259   unsigned PtrStoreOpc = 0;
19260   unsigned LabelReg = 0;
19261   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19262   Reloc::Model RM = MF->getTarget().getRelocationModel();
19263   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19264                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19265
19266   // Prepare IP either in reg or imm.
19267   if (!UseImmLabel) {
19268     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19269     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19270     LabelReg = MRI.createVirtualRegister(PtrRC);
19271     if (Subtarget->is64Bit()) {
19272       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19273               .addReg(X86::RIP)
19274               .addImm(0)
19275               .addReg(0)
19276               .addMBB(restoreMBB)
19277               .addReg(0);
19278     } else {
19279       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19280       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19281               .addReg(XII->getGlobalBaseReg(MF))
19282               .addImm(0)
19283               .addReg(0)
19284               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19285               .addReg(0);
19286     }
19287   } else
19288     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19289   // Store IP
19290   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19291   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19292     if (i == X86::AddrDisp)
19293       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19294     else
19295       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19296   }
19297   if (!UseImmLabel)
19298     MIB.addReg(LabelReg);
19299   else
19300     MIB.addMBB(restoreMBB);
19301   MIB.setMemRefs(MMOBegin, MMOEnd);
19302   // Setup
19303   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19304           .addMBB(restoreMBB);
19305
19306   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19307   MIB.addRegMask(RegInfo->getNoPreservedMask());
19308   thisMBB->addSuccessor(mainMBB);
19309   thisMBB->addSuccessor(restoreMBB);
19310
19311   // mainMBB:
19312   //  EAX = 0
19313   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19314   mainMBB->addSuccessor(sinkMBB);
19315
19316   // sinkMBB:
19317   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19318           TII->get(X86::PHI), DstReg)
19319     .addReg(mainDstReg).addMBB(mainMBB)
19320     .addReg(restoreDstReg).addMBB(restoreMBB);
19321
19322   // restoreMBB:
19323   if (RegInfo->hasBasePointer(*MF)) {
19324     const bool Uses64BitFramePtr =
19325         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19326     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19327     X86FI->setRestoreBasePointer(MF);
19328     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19329     unsigned BasePtr = RegInfo->getBaseRegister();
19330     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19331     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19332                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19333       .setMIFlag(MachineInstr::FrameSetup);
19334   }
19335   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19336   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19337   restoreMBB->addSuccessor(sinkMBB);
19338
19339   MI->eraseFromParent();
19340   return sinkMBB;
19341 }
19342
19343 MachineBasicBlock *
19344 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19345                                      MachineBasicBlock *MBB) const {
19346   DebugLoc DL = MI->getDebugLoc();
19347   MachineFunction *MF = MBB->getParent();
19348   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19349   MachineRegisterInfo &MRI = MF->getRegInfo();
19350
19351   // Memory Reference
19352   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19353   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19354
19355   MVT PVT = getPointerTy();
19356   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19357          "Invalid Pointer Size!");
19358
19359   const TargetRegisterClass *RC =
19360     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19361   unsigned Tmp = MRI.createVirtualRegister(RC);
19362   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19363   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19364   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19365   unsigned SP = RegInfo->getStackRegister();
19366
19367   MachineInstrBuilder MIB;
19368
19369   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19370   const int64_t SPOffset = 2 * PVT.getStoreSize();
19371
19372   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19373   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19374
19375   // Reload FP
19376   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19377   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19378     MIB.addOperand(MI->getOperand(i));
19379   MIB.setMemRefs(MMOBegin, MMOEnd);
19380   // Reload IP
19381   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19382   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19383     if (i == X86::AddrDisp)
19384       MIB.addDisp(MI->getOperand(i), LabelOffset);
19385     else
19386       MIB.addOperand(MI->getOperand(i));
19387   }
19388   MIB.setMemRefs(MMOBegin, MMOEnd);
19389   // Reload SP
19390   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19391   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19392     if (i == X86::AddrDisp)
19393       MIB.addDisp(MI->getOperand(i), SPOffset);
19394     else
19395       MIB.addOperand(MI->getOperand(i));
19396   }
19397   MIB.setMemRefs(MMOBegin, MMOEnd);
19398   // Jump
19399   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19400
19401   MI->eraseFromParent();
19402   return MBB;
19403 }
19404
19405 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19406 // accumulator loops. Writing back to the accumulator allows the coalescer
19407 // to remove extra copies in the loop.
19408 MachineBasicBlock *
19409 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19410                                  MachineBasicBlock *MBB) const {
19411   MachineOperand &AddendOp = MI->getOperand(3);
19412
19413   // Bail out early if the addend isn't a register - we can't switch these.
19414   if (!AddendOp.isReg())
19415     return MBB;
19416
19417   MachineFunction &MF = *MBB->getParent();
19418   MachineRegisterInfo &MRI = MF.getRegInfo();
19419
19420   // Check whether the addend is defined by a PHI:
19421   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19422   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19423   if (!AddendDef.isPHI())
19424     return MBB;
19425
19426   // Look for the following pattern:
19427   // loop:
19428   //   %addend = phi [%entry, 0], [%loop, %result]
19429   //   ...
19430   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19431
19432   // Replace with:
19433   //   loop:
19434   //   %addend = phi [%entry, 0], [%loop, %result]
19435   //   ...
19436   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19437
19438   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19439     assert(AddendDef.getOperand(i).isReg());
19440     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19441     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19442     if (&PHISrcInst == MI) {
19443       // Found a matching instruction.
19444       unsigned NewFMAOpc = 0;
19445       switch (MI->getOpcode()) {
19446         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19447         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19448         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19449         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19450         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19451         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19452         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19453         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19454         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19455         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19456         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19457         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19458         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19459         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19460         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19461         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19462         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19463         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19464         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19465         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19466
19467         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19468         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19469         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19470         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19471         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19472         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19473         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19474         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19475         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19476         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19477         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19478         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19479         default: llvm_unreachable("Unrecognized FMA variant.");
19480       }
19481
19482       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19483       MachineInstrBuilder MIB =
19484         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19485         .addOperand(MI->getOperand(0))
19486         .addOperand(MI->getOperand(3))
19487         .addOperand(MI->getOperand(2))
19488         .addOperand(MI->getOperand(1));
19489       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19490       MI->eraseFromParent();
19491     }
19492   }
19493
19494   return MBB;
19495 }
19496
19497 MachineBasicBlock *
19498 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19499                                                MachineBasicBlock *BB) const {
19500   switch (MI->getOpcode()) {
19501   default: llvm_unreachable("Unexpected instr type to insert");
19502   case X86::TAILJMPd64:
19503   case X86::TAILJMPr64:
19504   case X86::TAILJMPm64:
19505   case X86::TAILJMPd64_REX:
19506   case X86::TAILJMPr64_REX:
19507   case X86::TAILJMPm64_REX:
19508     llvm_unreachable("TAILJMP64 would not be touched here.");
19509   case X86::TCRETURNdi64:
19510   case X86::TCRETURNri64:
19511   case X86::TCRETURNmi64:
19512     return BB;
19513   case X86::WIN_ALLOCA:
19514     return EmitLoweredWinAlloca(MI, BB);
19515   case X86::SEG_ALLOCA_32:
19516   case X86::SEG_ALLOCA_64:
19517     return EmitLoweredSegAlloca(MI, BB);
19518   case X86::TLSCall_32:
19519   case X86::TLSCall_64:
19520     return EmitLoweredTLSCall(MI, BB);
19521   case X86::CMOV_GR8:
19522   case X86::CMOV_FR32:
19523   case X86::CMOV_FR64:
19524   case X86::CMOV_V4F32:
19525   case X86::CMOV_V2F64:
19526   case X86::CMOV_V2I64:
19527   case X86::CMOV_V8F32:
19528   case X86::CMOV_V4F64:
19529   case X86::CMOV_V4I64:
19530   case X86::CMOV_V16F32:
19531   case X86::CMOV_V8F64:
19532   case X86::CMOV_V8I64:
19533   case X86::CMOV_GR16:
19534   case X86::CMOV_GR32:
19535   case X86::CMOV_RFP32:
19536   case X86::CMOV_RFP64:
19537   case X86::CMOV_RFP80:
19538   case X86::CMOV_V8I1:
19539   case X86::CMOV_V16I1:
19540   case X86::CMOV_V32I1:
19541   case X86::CMOV_V64I1:
19542     return EmitLoweredSelect(MI, BB);
19543
19544   case X86::FP32_TO_INT16_IN_MEM:
19545   case X86::FP32_TO_INT32_IN_MEM:
19546   case X86::FP32_TO_INT64_IN_MEM:
19547   case X86::FP64_TO_INT16_IN_MEM:
19548   case X86::FP64_TO_INT32_IN_MEM:
19549   case X86::FP64_TO_INT64_IN_MEM:
19550   case X86::FP80_TO_INT16_IN_MEM:
19551   case X86::FP80_TO_INT32_IN_MEM:
19552   case X86::FP80_TO_INT64_IN_MEM: {
19553     MachineFunction *F = BB->getParent();
19554     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19555     DebugLoc DL = MI->getDebugLoc();
19556
19557     // Change the floating point control register to use "round towards zero"
19558     // mode when truncating to an integer value.
19559     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19560     addFrameReference(BuildMI(*BB, MI, DL,
19561                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19562
19563     // Load the old value of the high byte of the control word...
19564     unsigned OldCW =
19565       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19566     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19567                       CWFrameIdx);
19568
19569     // Set the high part to be round to zero...
19570     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19571       .addImm(0xC7F);
19572
19573     // Reload the modified control word now...
19574     addFrameReference(BuildMI(*BB, MI, DL,
19575                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19576
19577     // Restore the memory image of control word to original value
19578     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19579       .addReg(OldCW);
19580
19581     // Get the X86 opcode to use.
19582     unsigned Opc;
19583     switch (MI->getOpcode()) {
19584     default: llvm_unreachable("illegal opcode!");
19585     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19586     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19587     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19588     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19589     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19590     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19591     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19592     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19593     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19594     }
19595
19596     X86AddressMode AM;
19597     MachineOperand &Op = MI->getOperand(0);
19598     if (Op.isReg()) {
19599       AM.BaseType = X86AddressMode::RegBase;
19600       AM.Base.Reg = Op.getReg();
19601     } else {
19602       AM.BaseType = X86AddressMode::FrameIndexBase;
19603       AM.Base.FrameIndex = Op.getIndex();
19604     }
19605     Op = MI->getOperand(1);
19606     if (Op.isImm())
19607       AM.Scale = Op.getImm();
19608     Op = MI->getOperand(2);
19609     if (Op.isImm())
19610       AM.IndexReg = Op.getImm();
19611     Op = MI->getOperand(3);
19612     if (Op.isGlobal()) {
19613       AM.GV = Op.getGlobal();
19614     } else {
19615       AM.Disp = Op.getImm();
19616     }
19617     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19618                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19619
19620     // Reload the original control word now.
19621     addFrameReference(BuildMI(*BB, MI, DL,
19622                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19623
19624     MI->eraseFromParent();   // The pseudo instruction is gone now.
19625     return BB;
19626   }
19627     // String/text processing lowering.
19628   case X86::PCMPISTRM128REG:
19629   case X86::VPCMPISTRM128REG:
19630   case X86::PCMPISTRM128MEM:
19631   case X86::VPCMPISTRM128MEM:
19632   case X86::PCMPESTRM128REG:
19633   case X86::VPCMPESTRM128REG:
19634   case X86::PCMPESTRM128MEM:
19635   case X86::VPCMPESTRM128MEM:
19636     assert(Subtarget->hasSSE42() &&
19637            "Target must have SSE4.2 or AVX features enabled");
19638     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19639
19640   // String/text processing lowering.
19641   case X86::PCMPISTRIREG:
19642   case X86::VPCMPISTRIREG:
19643   case X86::PCMPISTRIMEM:
19644   case X86::VPCMPISTRIMEM:
19645   case X86::PCMPESTRIREG:
19646   case X86::VPCMPESTRIREG:
19647   case X86::PCMPESTRIMEM:
19648   case X86::VPCMPESTRIMEM:
19649     assert(Subtarget->hasSSE42() &&
19650            "Target must have SSE4.2 or AVX features enabled");
19651     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19652
19653   // Thread synchronization.
19654   case X86::MONITOR:
19655     return EmitMonitor(MI, BB, Subtarget);
19656
19657   // xbegin
19658   case X86::XBEGIN:
19659     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19660
19661   case X86::VASTART_SAVE_XMM_REGS:
19662     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19663
19664   case X86::VAARG_64:
19665     return EmitVAARG64WithCustomInserter(MI, BB);
19666
19667   case X86::EH_SjLj_SetJmp32:
19668   case X86::EH_SjLj_SetJmp64:
19669     return emitEHSjLjSetJmp(MI, BB);
19670
19671   case X86::EH_SjLj_LongJmp32:
19672   case X86::EH_SjLj_LongJmp64:
19673     return emitEHSjLjLongJmp(MI, BB);
19674
19675   case TargetOpcode::STATEPOINT:
19676     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19677     // this point in the process.  We diverge later.
19678     return emitPatchPoint(MI, BB);
19679
19680   case TargetOpcode::STACKMAP:
19681   case TargetOpcode::PATCHPOINT:
19682     return emitPatchPoint(MI, BB);
19683
19684   case X86::VFMADDPDr213r:
19685   case X86::VFMADDPSr213r:
19686   case X86::VFMADDSDr213r:
19687   case X86::VFMADDSSr213r:
19688   case X86::VFMSUBPDr213r:
19689   case X86::VFMSUBPSr213r:
19690   case X86::VFMSUBSDr213r:
19691   case X86::VFMSUBSSr213r:
19692   case X86::VFNMADDPDr213r:
19693   case X86::VFNMADDPSr213r:
19694   case X86::VFNMADDSDr213r:
19695   case X86::VFNMADDSSr213r:
19696   case X86::VFNMSUBPDr213r:
19697   case X86::VFNMSUBPSr213r:
19698   case X86::VFNMSUBSDr213r:
19699   case X86::VFNMSUBSSr213r:
19700   case X86::VFMADDSUBPDr213r:
19701   case X86::VFMADDSUBPSr213r:
19702   case X86::VFMSUBADDPDr213r:
19703   case X86::VFMSUBADDPSr213r:
19704   case X86::VFMADDPDr213rY:
19705   case X86::VFMADDPSr213rY:
19706   case X86::VFMSUBPDr213rY:
19707   case X86::VFMSUBPSr213rY:
19708   case X86::VFNMADDPDr213rY:
19709   case X86::VFNMADDPSr213rY:
19710   case X86::VFNMSUBPDr213rY:
19711   case X86::VFNMSUBPSr213rY:
19712   case X86::VFMADDSUBPDr213rY:
19713   case X86::VFMADDSUBPSr213rY:
19714   case X86::VFMSUBADDPDr213rY:
19715   case X86::VFMSUBADDPSr213rY:
19716     return emitFMA3Instr(MI, BB);
19717   }
19718 }
19719
19720 //===----------------------------------------------------------------------===//
19721 //                           X86 Optimization Hooks
19722 //===----------------------------------------------------------------------===//
19723
19724 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19725                                                       APInt &KnownZero,
19726                                                       APInt &KnownOne,
19727                                                       const SelectionDAG &DAG,
19728                                                       unsigned Depth) const {
19729   unsigned BitWidth = KnownZero.getBitWidth();
19730   unsigned Opc = Op.getOpcode();
19731   assert((Opc >= ISD::BUILTIN_OP_END ||
19732           Opc == ISD::INTRINSIC_WO_CHAIN ||
19733           Opc == ISD::INTRINSIC_W_CHAIN ||
19734           Opc == ISD::INTRINSIC_VOID) &&
19735          "Should use MaskedValueIsZero if you don't know whether Op"
19736          " is a target node!");
19737
19738   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19739   switch (Opc) {
19740   default: break;
19741   case X86ISD::ADD:
19742   case X86ISD::SUB:
19743   case X86ISD::ADC:
19744   case X86ISD::SBB:
19745   case X86ISD::SMUL:
19746   case X86ISD::UMUL:
19747   case X86ISD::INC:
19748   case X86ISD::DEC:
19749   case X86ISD::OR:
19750   case X86ISD::XOR:
19751   case X86ISD::AND:
19752     // These nodes' second result is a boolean.
19753     if (Op.getResNo() == 0)
19754       break;
19755     // Fallthrough
19756   case X86ISD::SETCC:
19757     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19758     break;
19759   case ISD::INTRINSIC_WO_CHAIN: {
19760     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19761     unsigned NumLoBits = 0;
19762     switch (IntId) {
19763     default: break;
19764     case Intrinsic::x86_sse_movmsk_ps:
19765     case Intrinsic::x86_avx_movmsk_ps_256:
19766     case Intrinsic::x86_sse2_movmsk_pd:
19767     case Intrinsic::x86_avx_movmsk_pd_256:
19768     case Intrinsic::x86_mmx_pmovmskb:
19769     case Intrinsic::x86_sse2_pmovmskb_128:
19770     case Intrinsic::x86_avx2_pmovmskb: {
19771       // High bits of movmskp{s|d}, pmovmskb are known zero.
19772       switch (IntId) {
19773         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19774         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19775         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19776         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19777         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19778         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19779         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19780         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19781       }
19782       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19783       break;
19784     }
19785     }
19786     break;
19787   }
19788   }
19789 }
19790
19791 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19792   SDValue Op,
19793   const SelectionDAG &,
19794   unsigned Depth) const {
19795   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19796   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19797     return Op.getValueType().getScalarType().getSizeInBits();
19798
19799   // Fallback case.
19800   return 1;
19801 }
19802
19803 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19804 /// node is a GlobalAddress + offset.
19805 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19806                                        const GlobalValue* &GA,
19807                                        int64_t &Offset) const {
19808   if (N->getOpcode() == X86ISD::Wrapper) {
19809     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19810       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19811       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19812       return true;
19813     }
19814   }
19815   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19816 }
19817
19818 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19819 /// same as extracting the high 128-bit part of 256-bit vector and then
19820 /// inserting the result into the low part of a new 256-bit vector
19821 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19822   EVT VT = SVOp->getValueType(0);
19823   unsigned NumElems = VT.getVectorNumElements();
19824
19825   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19826   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19827     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19828         SVOp->getMaskElt(j) >= 0)
19829       return false;
19830
19831   return true;
19832 }
19833
19834 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19835 /// same as extracting the low 128-bit part of 256-bit vector and then
19836 /// inserting the result into the high part of a new 256-bit vector
19837 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19838   EVT VT = SVOp->getValueType(0);
19839   unsigned NumElems = VT.getVectorNumElements();
19840
19841   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19842   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19843     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19844         SVOp->getMaskElt(j) >= 0)
19845       return false;
19846
19847   return true;
19848 }
19849
19850 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19851 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19852                                         TargetLowering::DAGCombinerInfo &DCI,
19853                                         const X86Subtarget* Subtarget) {
19854   SDLoc dl(N);
19855   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19856   SDValue V1 = SVOp->getOperand(0);
19857   SDValue V2 = SVOp->getOperand(1);
19858   EVT VT = SVOp->getValueType(0);
19859   unsigned NumElems = VT.getVectorNumElements();
19860
19861   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19862       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19863     //
19864     //                   0,0,0,...
19865     //                      |
19866     //    V      UNDEF    BUILD_VECTOR    UNDEF
19867     //     \      /           \           /
19868     //  CONCAT_VECTOR         CONCAT_VECTOR
19869     //         \                  /
19870     //          \                /
19871     //          RESULT: V + zero extended
19872     //
19873     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19874         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19875         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19876       return SDValue();
19877
19878     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19879       return SDValue();
19880
19881     // To match the shuffle mask, the first half of the mask should
19882     // be exactly the first vector, and all the rest a splat with the
19883     // first element of the second one.
19884     for (unsigned i = 0; i != NumElems/2; ++i)
19885       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19886           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19887         return SDValue();
19888
19889     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19890     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19891       if (Ld->hasNUsesOfValue(1, 0)) {
19892         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19893         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19894         SDValue ResNode =
19895           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19896                                   Ld->getMemoryVT(),
19897                                   Ld->getPointerInfo(),
19898                                   Ld->getAlignment(),
19899                                   false/*isVolatile*/, true/*ReadMem*/,
19900                                   false/*WriteMem*/);
19901
19902         // Make sure the newly-created LOAD is in the same position as Ld in
19903         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19904         // and update uses of Ld's output chain to use the TokenFactor.
19905         if (Ld->hasAnyUseOfValue(1)) {
19906           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19907                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19908           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19909           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19910                                  SDValue(ResNode.getNode(), 1));
19911         }
19912
19913         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19914       }
19915     }
19916
19917     // Emit a zeroed vector and insert the desired subvector on its
19918     // first half.
19919     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19920     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19921     return DCI.CombineTo(N, InsV);
19922   }
19923
19924   //===--------------------------------------------------------------------===//
19925   // Combine some shuffles into subvector extracts and inserts:
19926   //
19927
19928   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19929   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19930     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19931     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19932     return DCI.CombineTo(N, InsV);
19933   }
19934
19935   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19936   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19937     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19938     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19939     return DCI.CombineTo(N, InsV);
19940   }
19941
19942   return SDValue();
19943 }
19944
19945 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19946 /// possible.
19947 ///
19948 /// This is the leaf of the recursive combinine below. When we have found some
19949 /// chain of single-use x86 shuffle instructions and accumulated the combined
19950 /// shuffle mask represented by them, this will try to pattern match that mask
19951 /// into either a single instruction if there is a special purpose instruction
19952 /// for this operation, or into a PSHUFB instruction which is a fully general
19953 /// instruction but should only be used to replace chains over a certain depth.
19954 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19955                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19956                                    TargetLowering::DAGCombinerInfo &DCI,
19957                                    const X86Subtarget *Subtarget) {
19958   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19959
19960   // Find the operand that enters the chain. Note that multiple uses are OK
19961   // here, we're not going to remove the operand we find.
19962   SDValue Input = Op.getOperand(0);
19963   while (Input.getOpcode() == ISD::BITCAST)
19964     Input = Input.getOperand(0);
19965
19966   MVT VT = Input.getSimpleValueType();
19967   MVT RootVT = Root.getSimpleValueType();
19968   SDLoc DL(Root);
19969
19970   // Just remove no-op shuffle masks.
19971   if (Mask.size() == 1) {
19972     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19973                   /*AddTo*/ true);
19974     return true;
19975   }
19976
19977   // Use the float domain if the operand type is a floating point type.
19978   bool FloatDomain = VT.isFloatingPoint();
19979
19980   // For floating point shuffles, we don't have free copies in the shuffle
19981   // instructions or the ability to load as part of the instruction, so
19982   // canonicalize their shuffles to UNPCK or MOV variants.
19983   //
19984   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19985   // vectors because it can have a load folded into it that UNPCK cannot. This
19986   // doesn't preclude something switching to the shorter encoding post-RA.
19987   //
19988   // FIXME: Should teach these routines about AVX vector widths.
19989   if (FloatDomain && VT.getSizeInBits() == 128) {
19990     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19991       bool Lo = Mask.equals({0, 0});
19992       unsigned Shuffle;
19993       MVT ShuffleVT;
19994       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19995       // is no slower than UNPCKLPD but has the option to fold the input operand
19996       // into even an unaligned memory load.
19997       if (Lo && Subtarget->hasSSE3()) {
19998         Shuffle = X86ISD::MOVDDUP;
19999         ShuffleVT = MVT::v2f64;
20000       } else {
20001         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20002         // than the UNPCK variants.
20003         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20004         ShuffleVT = MVT::v4f32;
20005       }
20006       if (Depth == 1 && Root->getOpcode() == Shuffle)
20007         return false; // Nothing to do!
20008       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20009       DCI.AddToWorklist(Op.getNode());
20010       if (Shuffle == X86ISD::MOVDDUP)
20011         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20012       else
20013         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20014       DCI.AddToWorklist(Op.getNode());
20015       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20016                     /*AddTo*/ true);
20017       return true;
20018     }
20019     if (Subtarget->hasSSE3() &&
20020         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20021       bool Lo = Mask.equals({0, 0, 2, 2});
20022       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20023       MVT ShuffleVT = MVT::v4f32;
20024       if (Depth == 1 && Root->getOpcode() == Shuffle)
20025         return false; // Nothing to do!
20026       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20027       DCI.AddToWorklist(Op.getNode());
20028       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20029       DCI.AddToWorklist(Op.getNode());
20030       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20031                     /*AddTo*/ true);
20032       return true;
20033     }
20034     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20035       bool Lo = Mask.equals({0, 0, 1, 1});
20036       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20037       MVT ShuffleVT = MVT::v4f32;
20038       if (Depth == 1 && Root->getOpcode() == Shuffle)
20039         return false; // Nothing to do!
20040       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20041       DCI.AddToWorklist(Op.getNode());
20042       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20043       DCI.AddToWorklist(Op.getNode());
20044       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20045                     /*AddTo*/ true);
20046       return true;
20047     }
20048   }
20049
20050   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20051   // variants as none of these have single-instruction variants that are
20052   // superior to the UNPCK formulation.
20053   if (!FloatDomain && VT.getSizeInBits() == 128 &&
20054       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20055        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20056        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20057        Mask.equals(
20058            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20059     bool Lo = Mask[0] == 0;
20060     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20061     if (Depth == 1 && Root->getOpcode() == Shuffle)
20062       return false; // Nothing to do!
20063     MVT ShuffleVT;
20064     switch (Mask.size()) {
20065     case 8:
20066       ShuffleVT = MVT::v8i16;
20067       break;
20068     case 16:
20069       ShuffleVT = MVT::v16i8;
20070       break;
20071     default:
20072       llvm_unreachable("Impossible mask size!");
20073     };
20074     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20075     DCI.AddToWorklist(Op.getNode());
20076     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20077     DCI.AddToWorklist(Op.getNode());
20078     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20079                   /*AddTo*/ true);
20080     return true;
20081   }
20082
20083   // Don't try to re-form single instruction chains under any circumstances now
20084   // that we've done encoding canonicalization for them.
20085   if (Depth < 2)
20086     return false;
20087
20088   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20089   // can replace them with a single PSHUFB instruction profitably. Intel's
20090   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20091   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20092   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20093     SmallVector<SDValue, 16> PSHUFBMask;
20094     int NumBytes = VT.getSizeInBits() / 8;
20095     int Ratio = NumBytes / Mask.size();
20096     for (int i = 0; i < NumBytes; ++i) {
20097       if (Mask[i / Ratio] == SM_SentinelUndef) {
20098         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20099         continue;
20100       }
20101       int M = Mask[i / Ratio] != SM_SentinelZero
20102                   ? Ratio * Mask[i / Ratio] + i % Ratio
20103                   : 255;
20104       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20105     }
20106     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20107     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20108     DCI.AddToWorklist(Op.getNode());
20109     SDValue PSHUFBMaskOp =
20110         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20111     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20112     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20113     DCI.AddToWorklist(Op.getNode());
20114     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20115                   /*AddTo*/ true);
20116     return true;
20117   }
20118
20119   // Failed to find any combines.
20120   return false;
20121 }
20122
20123 /// \brief Fully generic combining of x86 shuffle instructions.
20124 ///
20125 /// This should be the last combine run over the x86 shuffle instructions. Once
20126 /// they have been fully optimized, this will recursively consider all chains
20127 /// of single-use shuffle instructions, build a generic model of the cumulative
20128 /// shuffle operation, and check for simpler instructions which implement this
20129 /// operation. We use this primarily for two purposes:
20130 ///
20131 /// 1) Collapse generic shuffles to specialized single instructions when
20132 ///    equivalent. In most cases, this is just an encoding size win, but
20133 ///    sometimes we will collapse multiple generic shuffles into a single
20134 ///    special-purpose shuffle.
20135 /// 2) Look for sequences of shuffle instructions with 3 or more total
20136 ///    instructions, and replace them with the slightly more expensive SSSE3
20137 ///    PSHUFB instruction if available. We do this as the last combining step
20138 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20139 ///    a suitable short sequence of other instructions. The PHUFB will either
20140 ///    use a register or have to read from memory and so is slightly (but only
20141 ///    slightly) more expensive than the other shuffle instructions.
20142 ///
20143 /// Because this is inherently a quadratic operation (for each shuffle in
20144 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20145 /// This should never be an issue in practice as the shuffle lowering doesn't
20146 /// produce sequences of more than 8 instructions.
20147 ///
20148 /// FIXME: We will currently miss some cases where the redundant shuffling
20149 /// would simplify under the threshold for PSHUFB formation because of
20150 /// combine-ordering. To fix this, we should do the redundant instruction
20151 /// combining in this recursive walk.
20152 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20153                                           ArrayRef<int> RootMask,
20154                                           int Depth, bool HasPSHUFB,
20155                                           SelectionDAG &DAG,
20156                                           TargetLowering::DAGCombinerInfo &DCI,
20157                                           const X86Subtarget *Subtarget) {
20158   // Bound the depth of our recursive combine because this is ultimately
20159   // quadratic in nature.
20160   if (Depth > 8)
20161     return false;
20162
20163   // Directly rip through bitcasts to find the underlying operand.
20164   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20165     Op = Op.getOperand(0);
20166
20167   MVT VT = Op.getSimpleValueType();
20168   if (!VT.isVector())
20169     return false; // Bail if we hit a non-vector.
20170
20171   assert(Root.getSimpleValueType().isVector() &&
20172          "Shuffles operate on vector types!");
20173   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20174          "Can only combine shuffles of the same vector register size.");
20175
20176   if (!isTargetShuffle(Op.getOpcode()))
20177     return false;
20178   SmallVector<int, 16> OpMask;
20179   bool IsUnary;
20180   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20181   // We only can combine unary shuffles which we can decode the mask for.
20182   if (!HaveMask || !IsUnary)
20183     return false;
20184
20185   assert(VT.getVectorNumElements() == OpMask.size() &&
20186          "Different mask size from vector size!");
20187   assert(((RootMask.size() > OpMask.size() &&
20188            RootMask.size() % OpMask.size() == 0) ||
20189           (OpMask.size() > RootMask.size() &&
20190            OpMask.size() % RootMask.size() == 0) ||
20191           OpMask.size() == RootMask.size()) &&
20192          "The smaller number of elements must divide the larger.");
20193   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20194   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20195   assert(((RootRatio == 1 && OpRatio == 1) ||
20196           (RootRatio == 1) != (OpRatio == 1)) &&
20197          "Must not have a ratio for both incoming and op masks!");
20198
20199   SmallVector<int, 16> Mask;
20200   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20201
20202   // Merge this shuffle operation's mask into our accumulated mask. Note that
20203   // this shuffle's mask will be the first applied to the input, followed by the
20204   // root mask to get us all the way to the root value arrangement. The reason
20205   // for this order is that we are recursing up the operation chain.
20206   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20207     int RootIdx = i / RootRatio;
20208     if (RootMask[RootIdx] < 0) {
20209       // This is a zero or undef lane, we're done.
20210       Mask.push_back(RootMask[RootIdx]);
20211       continue;
20212     }
20213
20214     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20215     int OpIdx = RootMaskedIdx / OpRatio;
20216     if (OpMask[OpIdx] < 0) {
20217       // The incoming lanes are zero or undef, it doesn't matter which ones we
20218       // are using.
20219       Mask.push_back(OpMask[OpIdx]);
20220       continue;
20221     }
20222
20223     // Ok, we have non-zero lanes, map them through.
20224     Mask.push_back(OpMask[OpIdx] * OpRatio +
20225                    RootMaskedIdx % OpRatio);
20226   }
20227
20228   // See if we can recurse into the operand to combine more things.
20229   switch (Op.getOpcode()) {
20230     case X86ISD::PSHUFB:
20231       HasPSHUFB = true;
20232     case X86ISD::PSHUFD:
20233     case X86ISD::PSHUFHW:
20234     case X86ISD::PSHUFLW:
20235       if (Op.getOperand(0).hasOneUse() &&
20236           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20237                                         HasPSHUFB, DAG, DCI, Subtarget))
20238         return true;
20239       break;
20240
20241     case X86ISD::UNPCKL:
20242     case X86ISD::UNPCKH:
20243       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20244       // We can't check for single use, we have to check that this shuffle is the only user.
20245       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20246           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20247                                         HasPSHUFB, DAG, DCI, Subtarget))
20248           return true;
20249       break;
20250   }
20251
20252   // Minor canonicalization of the accumulated shuffle mask to make it easier
20253   // to match below. All this does is detect masks with squential pairs of
20254   // elements, and shrink them to the half-width mask. It does this in a loop
20255   // so it will reduce the size of the mask to the minimal width mask which
20256   // performs an equivalent shuffle.
20257   SmallVector<int, 16> WidenedMask;
20258   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20259     Mask = std::move(WidenedMask);
20260     WidenedMask.clear();
20261   }
20262
20263   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20264                                 Subtarget);
20265 }
20266
20267 /// \brief Get the PSHUF-style mask from PSHUF node.
20268 ///
20269 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20270 /// PSHUF-style masks that can be reused with such instructions.
20271 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20272   MVT VT = N.getSimpleValueType();
20273   SmallVector<int, 4> Mask;
20274   bool IsUnary;
20275   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20276   (void)HaveMask;
20277   assert(HaveMask);
20278
20279   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20280   // matter. Check that the upper masks are repeats and remove them.
20281   if (VT.getSizeInBits() > 128) {
20282     int LaneElts = 128 / VT.getScalarSizeInBits();
20283 #ifndef NDEBUG
20284     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20285       for (int j = 0; j < LaneElts; ++j)
20286         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20287                "Mask doesn't repeat in high 128-bit lanes!");
20288 #endif
20289     Mask.resize(LaneElts);
20290   }
20291
20292   switch (N.getOpcode()) {
20293   case X86ISD::PSHUFD:
20294     return Mask;
20295   case X86ISD::PSHUFLW:
20296     Mask.resize(4);
20297     return Mask;
20298   case X86ISD::PSHUFHW:
20299     Mask.erase(Mask.begin(), Mask.begin() + 4);
20300     for (int &M : Mask)
20301       M -= 4;
20302     return Mask;
20303   default:
20304     llvm_unreachable("No valid shuffle instruction found!");
20305   }
20306 }
20307
20308 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20309 ///
20310 /// We walk up the chain and look for a combinable shuffle, skipping over
20311 /// shuffles that we could hoist this shuffle's transformation past without
20312 /// altering anything.
20313 static SDValue
20314 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20315                              SelectionDAG &DAG,
20316                              TargetLowering::DAGCombinerInfo &DCI) {
20317   assert(N.getOpcode() == X86ISD::PSHUFD &&
20318          "Called with something other than an x86 128-bit half shuffle!");
20319   SDLoc DL(N);
20320
20321   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20322   // of the shuffles in the chain so that we can form a fresh chain to replace
20323   // this one.
20324   SmallVector<SDValue, 8> Chain;
20325   SDValue V = N.getOperand(0);
20326   for (; V.hasOneUse(); V = V.getOperand(0)) {
20327     switch (V.getOpcode()) {
20328     default:
20329       return SDValue(); // Nothing combined!
20330
20331     case ISD::BITCAST:
20332       // Skip bitcasts as we always know the type for the target specific
20333       // instructions.
20334       continue;
20335
20336     case X86ISD::PSHUFD:
20337       // Found another dword shuffle.
20338       break;
20339
20340     case X86ISD::PSHUFLW:
20341       // Check that the low words (being shuffled) are the identity in the
20342       // dword shuffle, and the high words are self-contained.
20343       if (Mask[0] != 0 || Mask[1] != 1 ||
20344           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20345         return SDValue();
20346
20347       Chain.push_back(V);
20348       continue;
20349
20350     case X86ISD::PSHUFHW:
20351       // Check that the high words (being shuffled) are the identity in the
20352       // dword shuffle, and the low words are self-contained.
20353       if (Mask[2] != 2 || Mask[3] != 3 ||
20354           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20355         return SDValue();
20356
20357       Chain.push_back(V);
20358       continue;
20359
20360     case X86ISD::UNPCKL:
20361     case X86ISD::UNPCKH:
20362       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20363       // shuffle into a preceding word shuffle.
20364       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20365           V.getSimpleValueType().getScalarType() != MVT::i16)
20366         return SDValue();
20367
20368       // Search for a half-shuffle which we can combine with.
20369       unsigned CombineOp =
20370           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20371       if (V.getOperand(0) != V.getOperand(1) ||
20372           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20373         return SDValue();
20374       Chain.push_back(V);
20375       V = V.getOperand(0);
20376       do {
20377         switch (V.getOpcode()) {
20378         default:
20379           return SDValue(); // Nothing to combine.
20380
20381         case X86ISD::PSHUFLW:
20382         case X86ISD::PSHUFHW:
20383           if (V.getOpcode() == CombineOp)
20384             break;
20385
20386           Chain.push_back(V);
20387
20388           // Fallthrough!
20389         case ISD::BITCAST:
20390           V = V.getOperand(0);
20391           continue;
20392         }
20393         break;
20394       } while (V.hasOneUse());
20395       break;
20396     }
20397     // Break out of the loop if we break out of the switch.
20398     break;
20399   }
20400
20401   if (!V.hasOneUse())
20402     // We fell out of the loop without finding a viable combining instruction.
20403     return SDValue();
20404
20405   // Merge this node's mask and our incoming mask.
20406   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20407   for (int &M : Mask)
20408     M = VMask[M];
20409   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20410                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20411
20412   // Rebuild the chain around this new shuffle.
20413   while (!Chain.empty()) {
20414     SDValue W = Chain.pop_back_val();
20415
20416     if (V.getValueType() != W.getOperand(0).getValueType())
20417       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20418
20419     switch (W.getOpcode()) {
20420     default:
20421       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20422
20423     case X86ISD::UNPCKL:
20424     case X86ISD::UNPCKH:
20425       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20426       break;
20427
20428     case X86ISD::PSHUFD:
20429     case X86ISD::PSHUFLW:
20430     case X86ISD::PSHUFHW:
20431       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20432       break;
20433     }
20434   }
20435   if (V.getValueType() != N.getValueType())
20436     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20437
20438   // Return the new chain to replace N.
20439   return V;
20440 }
20441
20442 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20443 ///
20444 /// We walk up the chain, skipping shuffles of the other half and looking
20445 /// through shuffles which switch halves trying to find a shuffle of the same
20446 /// pair of dwords.
20447 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20448                                         SelectionDAG &DAG,
20449                                         TargetLowering::DAGCombinerInfo &DCI) {
20450   assert(
20451       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20452       "Called with something other than an x86 128-bit half shuffle!");
20453   SDLoc DL(N);
20454   unsigned CombineOpcode = N.getOpcode();
20455
20456   // Walk up a single-use chain looking for a combinable shuffle.
20457   SDValue V = N.getOperand(0);
20458   for (; V.hasOneUse(); V = V.getOperand(0)) {
20459     switch (V.getOpcode()) {
20460     default:
20461       return false; // Nothing combined!
20462
20463     case ISD::BITCAST:
20464       // Skip bitcasts as we always know the type for the target specific
20465       // instructions.
20466       continue;
20467
20468     case X86ISD::PSHUFLW:
20469     case X86ISD::PSHUFHW:
20470       if (V.getOpcode() == CombineOpcode)
20471         break;
20472
20473       // Other-half shuffles are no-ops.
20474       continue;
20475     }
20476     // Break out of the loop if we break out of the switch.
20477     break;
20478   }
20479
20480   if (!V.hasOneUse())
20481     // We fell out of the loop without finding a viable combining instruction.
20482     return false;
20483
20484   // Combine away the bottom node as its shuffle will be accumulated into
20485   // a preceding shuffle.
20486   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20487
20488   // Record the old value.
20489   SDValue Old = V;
20490
20491   // Merge this node's mask and our incoming mask (adjusted to account for all
20492   // the pshufd instructions encountered).
20493   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20494   for (int &M : Mask)
20495     M = VMask[M];
20496   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20497                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20498
20499   // Check that the shuffles didn't cancel each other out. If not, we need to
20500   // combine to the new one.
20501   if (Old != V)
20502     // Replace the combinable shuffle with the combined one, updating all users
20503     // so that we re-evaluate the chain here.
20504     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20505
20506   return true;
20507 }
20508
20509 /// \brief Try to combine x86 target specific shuffles.
20510 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20511                                            TargetLowering::DAGCombinerInfo &DCI,
20512                                            const X86Subtarget *Subtarget) {
20513   SDLoc DL(N);
20514   MVT VT = N.getSimpleValueType();
20515   SmallVector<int, 4> Mask;
20516
20517   switch (N.getOpcode()) {
20518   case X86ISD::PSHUFD:
20519   case X86ISD::PSHUFLW:
20520   case X86ISD::PSHUFHW:
20521     Mask = getPSHUFShuffleMask(N);
20522     assert(Mask.size() == 4);
20523     break;
20524   default:
20525     return SDValue();
20526   }
20527
20528   // Nuke no-op shuffles that show up after combining.
20529   if (isNoopShuffleMask(Mask))
20530     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20531
20532   // Look for simplifications involving one or two shuffle instructions.
20533   SDValue V = N.getOperand(0);
20534   switch (N.getOpcode()) {
20535   default:
20536     break;
20537   case X86ISD::PSHUFLW:
20538   case X86ISD::PSHUFHW:
20539     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20540
20541     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20542       return SDValue(); // We combined away this shuffle, so we're done.
20543
20544     // See if this reduces to a PSHUFD which is no more expensive and can
20545     // combine with more operations. Note that it has to at least flip the
20546     // dwords as otherwise it would have been removed as a no-op.
20547     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20548       int DMask[] = {0, 1, 2, 3};
20549       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20550       DMask[DOffset + 0] = DOffset + 1;
20551       DMask[DOffset + 1] = DOffset + 0;
20552       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20553       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20554       DCI.AddToWorklist(V.getNode());
20555       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20556                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20557       DCI.AddToWorklist(V.getNode());
20558       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20559     }
20560
20561     // Look for shuffle patterns which can be implemented as a single unpack.
20562     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20563     // only works when we have a PSHUFD followed by two half-shuffles.
20564     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20565         (V.getOpcode() == X86ISD::PSHUFLW ||
20566          V.getOpcode() == X86ISD::PSHUFHW) &&
20567         V.getOpcode() != N.getOpcode() &&
20568         V.hasOneUse()) {
20569       SDValue D = V.getOperand(0);
20570       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20571         D = D.getOperand(0);
20572       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20573         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20574         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20575         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20576         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20577         int WordMask[8];
20578         for (int i = 0; i < 4; ++i) {
20579           WordMask[i + NOffset] = Mask[i] + NOffset;
20580           WordMask[i + VOffset] = VMask[i] + VOffset;
20581         }
20582         // Map the word mask through the DWord mask.
20583         int MappedMask[8];
20584         for (int i = 0; i < 8; ++i)
20585           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20586         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20587             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20588           // We can replace all three shuffles with an unpack.
20589           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20590           DCI.AddToWorklist(V.getNode());
20591           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20592                                                 : X86ISD::UNPCKH,
20593                              DL, VT, V, V);
20594         }
20595       }
20596     }
20597
20598     break;
20599
20600   case X86ISD::PSHUFD:
20601     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20602       return NewN;
20603
20604     break;
20605   }
20606
20607   return SDValue();
20608 }
20609
20610 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20611 ///
20612 /// We combine this directly on the abstract vector shuffle nodes so it is
20613 /// easier to generically match. We also insert dummy vector shuffle nodes for
20614 /// the operands which explicitly discard the lanes which are unused by this
20615 /// operation to try to flow through the rest of the combiner the fact that
20616 /// they're unused.
20617 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20618   SDLoc DL(N);
20619   EVT VT = N->getValueType(0);
20620
20621   // We only handle target-independent shuffles.
20622   // FIXME: It would be easy and harmless to use the target shuffle mask
20623   // extraction tool to support more.
20624   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20625     return SDValue();
20626
20627   auto *SVN = cast<ShuffleVectorSDNode>(N);
20628   ArrayRef<int> Mask = SVN->getMask();
20629   SDValue V1 = N->getOperand(0);
20630   SDValue V2 = N->getOperand(1);
20631
20632   // We require the first shuffle operand to be the SUB node, and the second to
20633   // be the ADD node.
20634   // FIXME: We should support the commuted patterns.
20635   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20636     return SDValue();
20637
20638   // If there are other uses of these operations we can't fold them.
20639   if (!V1->hasOneUse() || !V2->hasOneUse())
20640     return SDValue();
20641
20642   // Ensure that both operations have the same operands. Note that we can
20643   // commute the FADD operands.
20644   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20645   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20646       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20647     return SDValue();
20648
20649   // We're looking for blends between FADD and FSUB nodes. We insist on these
20650   // nodes being lined up in a specific expected pattern.
20651   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20652         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20653         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20654     return SDValue();
20655
20656   // Only specific types are legal at this point, assert so we notice if and
20657   // when these change.
20658   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20659           VT == MVT::v4f64) &&
20660          "Unknown vector type encountered!");
20661
20662   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20663 }
20664
20665 /// PerformShuffleCombine - Performs several different shuffle combines.
20666 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20667                                      TargetLowering::DAGCombinerInfo &DCI,
20668                                      const X86Subtarget *Subtarget) {
20669   SDLoc dl(N);
20670   SDValue N0 = N->getOperand(0);
20671   SDValue N1 = N->getOperand(1);
20672   EVT VT = N->getValueType(0);
20673
20674   // Don't create instructions with illegal types after legalize types has run.
20675   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20676   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20677     return SDValue();
20678
20679   // If we have legalized the vector types, look for blends of FADD and FSUB
20680   // nodes that we can fuse into an ADDSUB node.
20681   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20682     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20683       return AddSub;
20684
20685   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20686   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20687       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20688     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20689
20690   // During Type Legalization, when promoting illegal vector types,
20691   // the backend might introduce new shuffle dag nodes and bitcasts.
20692   //
20693   // This code performs the following transformation:
20694   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20695   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20696   //
20697   // We do this only if both the bitcast and the BINOP dag nodes have
20698   // one use. Also, perform this transformation only if the new binary
20699   // operation is legal. This is to avoid introducing dag nodes that
20700   // potentially need to be further expanded (or custom lowered) into a
20701   // less optimal sequence of dag nodes.
20702   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20703       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20704       N0.getOpcode() == ISD::BITCAST) {
20705     SDValue BC0 = N0.getOperand(0);
20706     EVT SVT = BC0.getValueType();
20707     unsigned Opcode = BC0.getOpcode();
20708     unsigned NumElts = VT.getVectorNumElements();
20709
20710     if (BC0.hasOneUse() && SVT.isVector() &&
20711         SVT.getVectorNumElements() * 2 == NumElts &&
20712         TLI.isOperationLegal(Opcode, VT)) {
20713       bool CanFold = false;
20714       switch (Opcode) {
20715       default : break;
20716       case ISD::ADD :
20717       case ISD::FADD :
20718       case ISD::SUB :
20719       case ISD::FSUB :
20720       case ISD::MUL :
20721       case ISD::FMUL :
20722         CanFold = true;
20723       }
20724
20725       unsigned SVTNumElts = SVT.getVectorNumElements();
20726       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20727       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20728         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20729       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20730         CanFold = SVOp->getMaskElt(i) < 0;
20731
20732       if (CanFold) {
20733         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20734         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20735         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20736         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20737       }
20738     }
20739   }
20740
20741   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20742   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20743   // consecutive, non-overlapping, and in the right order.
20744   SmallVector<SDValue, 16> Elts;
20745   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20746     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20747
20748   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20749   if (LD.getNode())
20750     return LD;
20751
20752   if (isTargetShuffle(N->getOpcode())) {
20753     SDValue Shuffle =
20754         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20755     if (Shuffle.getNode())
20756       return Shuffle;
20757
20758     // Try recursively combining arbitrary sequences of x86 shuffle
20759     // instructions into higher-order shuffles. We do this after combining
20760     // specific PSHUF instruction sequences into their minimal form so that we
20761     // can evaluate how many specialized shuffle instructions are involved in
20762     // a particular chain.
20763     SmallVector<int, 1> NonceMask; // Just a placeholder.
20764     NonceMask.push_back(0);
20765     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20766                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20767                                       DCI, Subtarget))
20768       return SDValue(); // This routine will use CombineTo to replace N.
20769   }
20770
20771   return SDValue();
20772 }
20773
20774 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20775 /// specific shuffle of a load can be folded into a single element load.
20776 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20777 /// shuffles have been custom lowered so we need to handle those here.
20778 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20779                                          TargetLowering::DAGCombinerInfo &DCI) {
20780   if (DCI.isBeforeLegalizeOps())
20781     return SDValue();
20782
20783   SDValue InVec = N->getOperand(0);
20784   SDValue EltNo = N->getOperand(1);
20785
20786   if (!isa<ConstantSDNode>(EltNo))
20787     return SDValue();
20788
20789   EVT OriginalVT = InVec.getValueType();
20790
20791   if (InVec.getOpcode() == ISD::BITCAST) {
20792     // Don't duplicate a load with other uses.
20793     if (!InVec.hasOneUse())
20794       return SDValue();
20795     EVT BCVT = InVec.getOperand(0).getValueType();
20796     if (!BCVT.isVector() || 
20797         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20798       return SDValue();
20799     InVec = InVec.getOperand(0);
20800   }
20801
20802   EVT CurrentVT = InVec.getValueType();
20803
20804   if (!isTargetShuffle(InVec.getOpcode()))
20805     return SDValue();
20806
20807   // Don't duplicate a load with other uses.
20808   if (!InVec.hasOneUse())
20809     return SDValue();
20810
20811   SmallVector<int, 16> ShuffleMask;
20812   bool UnaryShuffle;
20813   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20814                             ShuffleMask, UnaryShuffle))
20815     return SDValue();
20816
20817   // Select the input vector, guarding against out of range extract vector.
20818   unsigned NumElems = CurrentVT.getVectorNumElements();
20819   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20820   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20821   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20822                                          : InVec.getOperand(1);
20823
20824   // If inputs to shuffle are the same for both ops, then allow 2 uses
20825   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20826                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20827
20828   if (LdNode.getOpcode() == ISD::BITCAST) {
20829     // Don't duplicate a load with other uses.
20830     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20831       return SDValue();
20832
20833     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20834     LdNode = LdNode.getOperand(0);
20835   }
20836
20837   if (!ISD::isNormalLoad(LdNode.getNode()))
20838     return SDValue();
20839
20840   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20841
20842   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20843     return SDValue();
20844
20845   EVT EltVT = N->getValueType(0);
20846   // If there's a bitcast before the shuffle, check if the load type and
20847   // alignment is valid.
20848   unsigned Align = LN0->getAlignment();
20849   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20850   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20851       EltVT.getTypeForEVT(*DAG.getContext()));
20852
20853   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20854     return SDValue();
20855
20856   // All checks match so transform back to vector_shuffle so that DAG combiner
20857   // can finish the job
20858   SDLoc dl(N);
20859
20860   // Create shuffle node taking into account the case that its a unary shuffle
20861   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20862                                    : InVec.getOperand(1);
20863   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20864                                  InVec.getOperand(0), Shuffle,
20865                                  &ShuffleMask[0]);
20866   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20867   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20868                      EltNo);
20869 }
20870
20871 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20872 /// special and don't usually play with other vector types, it's better to
20873 /// handle them early to be sure we emit efficient code by avoiding
20874 /// store-load conversions.
20875 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20876   if (N->getValueType(0) != MVT::x86mmx ||
20877       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20878       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20879     return SDValue();
20880
20881   SDValue V = N->getOperand(0);
20882   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20883   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20884     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20885                        N->getValueType(0), V.getOperand(0));
20886
20887   return SDValue();
20888 }
20889
20890 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20891 /// generation and convert it from being a bunch of shuffles and extracts
20892 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20893 /// storing the value and loading scalars back, while for x64 we should
20894 /// use 64-bit extracts and shifts.
20895 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20896                                          TargetLowering::DAGCombinerInfo &DCI) {
20897   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20898   if (NewOp.getNode())
20899     return NewOp;
20900
20901   SDValue InputVector = N->getOperand(0);
20902   SDLoc dl(InputVector);
20903   // Detect mmx to i32 conversion through a v2i32 elt extract.
20904   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20905       N->getValueType(0) == MVT::i32 &&
20906       InputVector.getValueType() == MVT::v2i32) {
20907
20908     // The bitcast source is a direct mmx result.
20909     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20910     if (MMXSrc.getValueType() == MVT::x86mmx)
20911       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20912                          N->getValueType(0),
20913                          InputVector.getNode()->getOperand(0));
20914
20915     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20916     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20917     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20918         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20919         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20920         MMXSrcOp.getValueType() == MVT::v1i64 &&
20921         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20922       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20923                          N->getValueType(0),
20924                          MMXSrcOp.getOperand(0));
20925   }
20926
20927   EVT VT = N->getValueType(0);
20928   
20929   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
20930       InputVector.getOpcode() == ISD::BITCAST &&
20931       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
20932     uint64_t ExtractedElt =
20933           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20934     uint64_t InputValue =
20935           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
20936     uint64_t Res = (InputValue >> ExtractedElt) & 1;
20937     return DAG.getConstant(Res, dl, MVT::i1);
20938   }
20939   // Only operate on vectors of 4 elements, where the alternative shuffling
20940   // gets to be more expensive.
20941   if (InputVector.getValueType() != MVT::v4i32)
20942     return SDValue();
20943
20944   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20945   // single use which is a sign-extend or zero-extend, and all elements are
20946   // used.
20947   SmallVector<SDNode *, 4> Uses;
20948   unsigned ExtractedElements = 0;
20949   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20950        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20951     if (UI.getUse().getResNo() != InputVector.getResNo())
20952       return SDValue();
20953
20954     SDNode *Extract = *UI;
20955     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20956       return SDValue();
20957
20958     if (Extract->getValueType(0) != MVT::i32)
20959       return SDValue();
20960     if (!Extract->hasOneUse())
20961       return SDValue();
20962     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20963         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20964       return SDValue();
20965     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20966       return SDValue();
20967
20968     // Record which element was extracted.
20969     ExtractedElements |=
20970       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20971
20972     Uses.push_back(Extract);
20973   }
20974
20975   // If not all the elements were used, this may not be worthwhile.
20976   if (ExtractedElements != 15)
20977     return SDValue();
20978
20979   // Ok, we've now decided to do the transformation.
20980   // If 64-bit shifts are legal, use the extract-shift sequence,
20981   // otherwise bounce the vector off the cache.
20982   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20983   SDValue Vals[4];
20984
20985   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20986     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20987     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20988     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20989       DAG.getConstant(0, dl, VecIdxTy));
20990     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20991       DAG.getConstant(1, dl, VecIdxTy));
20992
20993     SDValue ShAmt = DAG.getConstant(32, dl,
20994       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20995     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20996     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20997       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20998     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20999     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21000       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21001   } else {
21002     // Store the value to a temporary stack slot.
21003     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21004     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21005       MachinePointerInfo(), false, false, 0);
21006
21007     EVT ElementType = InputVector.getValueType().getVectorElementType();
21008     unsigned EltSize = ElementType.getSizeInBits() / 8;
21009
21010     // Replace each use (extract) with a load of the appropriate element.
21011     for (unsigned i = 0; i < 4; ++i) {
21012       uint64_t Offset = EltSize * i;
21013       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
21014
21015       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
21016                                        StackPtr, OffsetVal);
21017
21018       // Load the scalar.
21019       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21020                             ScalarAddr, MachinePointerInfo(),
21021                             false, false, false, 0);
21022
21023     }
21024   }
21025
21026   // Replace the extracts
21027   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21028     UE = Uses.end(); UI != UE; ++UI) {
21029     SDNode *Extract = *UI;
21030
21031     SDValue Idx = Extract->getOperand(1);
21032     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21033     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21034   }
21035
21036   // The replacement was made in place; don't return anything.
21037   return SDValue();
21038 }
21039
21040 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21041 static std::pair<unsigned, bool>
21042 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21043                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21044   if (!VT.isVector())
21045     return std::make_pair(0, false);
21046
21047   bool NeedSplit = false;
21048   switch (VT.getSimpleVT().SimpleTy) {
21049   default: return std::make_pair(0, false);
21050   case MVT::v4i64:
21051   case MVT::v2i64:
21052     if (!Subtarget->hasVLX())
21053       return std::make_pair(0, false);
21054     break;
21055   case MVT::v64i8:
21056   case MVT::v32i16:
21057     if (!Subtarget->hasBWI())
21058       return std::make_pair(0, false);
21059     break;
21060   case MVT::v16i32:
21061   case MVT::v8i64:
21062     if (!Subtarget->hasAVX512())
21063       return std::make_pair(0, false);
21064     break;
21065   case MVT::v32i8:
21066   case MVT::v16i16:
21067   case MVT::v8i32:
21068     if (!Subtarget->hasAVX2())
21069       NeedSplit = true;
21070     if (!Subtarget->hasAVX())
21071       return std::make_pair(0, false);
21072     break;
21073   case MVT::v16i8:
21074   case MVT::v8i16:
21075   case MVT::v4i32:
21076     if (!Subtarget->hasSSE2())
21077       return std::make_pair(0, false);
21078   }
21079
21080   // SSE2 has only a small subset of the operations.
21081   bool hasUnsigned = Subtarget->hasSSE41() ||
21082                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21083   bool hasSigned = Subtarget->hasSSE41() ||
21084                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21085
21086   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21087
21088   unsigned Opc = 0;
21089   // Check for x CC y ? x : y.
21090   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21091       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21092     switch (CC) {
21093     default: break;
21094     case ISD::SETULT:
21095     case ISD::SETULE:
21096       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21097     case ISD::SETUGT:
21098     case ISD::SETUGE:
21099       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21100     case ISD::SETLT:
21101     case ISD::SETLE:
21102       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21103     case ISD::SETGT:
21104     case ISD::SETGE:
21105       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21106     }
21107   // Check for x CC y ? y : x -- a min/max with reversed arms.
21108   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21109              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21110     switch (CC) {
21111     default: break;
21112     case ISD::SETULT:
21113     case ISD::SETULE:
21114       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21115     case ISD::SETUGT:
21116     case ISD::SETUGE:
21117       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21118     case ISD::SETLT:
21119     case ISD::SETLE:
21120       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21121     case ISD::SETGT:
21122     case ISD::SETGE:
21123       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21124     }
21125   }
21126
21127   return std::make_pair(Opc, NeedSplit);
21128 }
21129
21130 static SDValue
21131 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21132                                       const X86Subtarget *Subtarget) {
21133   SDLoc dl(N);
21134   SDValue Cond = N->getOperand(0);
21135   SDValue LHS = N->getOperand(1);
21136   SDValue RHS = N->getOperand(2);
21137
21138   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21139     SDValue CondSrc = Cond->getOperand(0);
21140     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21141       Cond = CondSrc->getOperand(0);
21142   }
21143
21144   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21145     return SDValue();
21146
21147   // A vselect where all conditions and data are constants can be optimized into
21148   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21149   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21150       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21151     return SDValue();
21152
21153   unsigned MaskValue = 0;
21154   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21155     return SDValue();
21156
21157   MVT VT = N->getSimpleValueType(0);
21158   unsigned NumElems = VT.getVectorNumElements();
21159   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21160   for (unsigned i = 0; i < NumElems; ++i) {
21161     // Be sure we emit undef where we can.
21162     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21163       ShuffleMask[i] = -1;
21164     else
21165       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21166   }
21167
21168   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21169   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21170     return SDValue();
21171   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21172 }
21173
21174 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21175 /// nodes.
21176 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21177                                     TargetLowering::DAGCombinerInfo &DCI,
21178                                     const X86Subtarget *Subtarget) {
21179   SDLoc DL(N);
21180   SDValue Cond = N->getOperand(0);
21181   // Get the LHS/RHS of the select.
21182   SDValue LHS = N->getOperand(1);
21183   SDValue RHS = N->getOperand(2);
21184   EVT VT = LHS.getValueType();
21185   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21186
21187   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21188   // instructions match the semantics of the common C idiom x<y?x:y but not
21189   // x<=y?x:y, because of how they handle negative zero (which can be
21190   // ignored in unsafe-math mode).
21191   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21192   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21193       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21194       (Subtarget->hasSSE2() ||
21195        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21196     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21197
21198     unsigned Opcode = 0;
21199     // Check for x CC y ? x : y.
21200     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21201         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21202       switch (CC) {
21203       default: break;
21204       case ISD::SETULT:
21205         // Converting this to a min would handle NaNs incorrectly, and swapping
21206         // the operands would cause it to handle comparisons between positive
21207         // and negative zero incorrectly.
21208         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21209           if (!DAG.getTarget().Options.UnsafeFPMath &&
21210               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21211             break;
21212           std::swap(LHS, RHS);
21213         }
21214         Opcode = X86ISD::FMIN;
21215         break;
21216       case ISD::SETOLE:
21217         // Converting this to a min would handle comparisons between positive
21218         // and negative zero incorrectly.
21219         if (!DAG.getTarget().Options.UnsafeFPMath &&
21220             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21221           break;
21222         Opcode = X86ISD::FMIN;
21223         break;
21224       case ISD::SETULE:
21225         // Converting this to a min would handle both negative zeros and NaNs
21226         // incorrectly, but we can swap the operands to fix both.
21227         std::swap(LHS, RHS);
21228       case ISD::SETOLT:
21229       case ISD::SETLT:
21230       case ISD::SETLE:
21231         Opcode = X86ISD::FMIN;
21232         break;
21233
21234       case ISD::SETOGE:
21235         // Converting this to a max would handle comparisons between positive
21236         // and negative zero incorrectly.
21237         if (!DAG.getTarget().Options.UnsafeFPMath &&
21238             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21239           break;
21240         Opcode = X86ISD::FMAX;
21241         break;
21242       case ISD::SETUGT:
21243         // Converting this to a max would handle NaNs incorrectly, and swapping
21244         // the operands would cause it to handle comparisons between positive
21245         // and negative zero incorrectly.
21246         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21247           if (!DAG.getTarget().Options.UnsafeFPMath &&
21248               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21249             break;
21250           std::swap(LHS, RHS);
21251         }
21252         Opcode = X86ISD::FMAX;
21253         break;
21254       case ISD::SETUGE:
21255         // Converting this to a max would handle both negative zeros and NaNs
21256         // incorrectly, but we can swap the operands to fix both.
21257         std::swap(LHS, RHS);
21258       case ISD::SETOGT:
21259       case ISD::SETGT:
21260       case ISD::SETGE:
21261         Opcode = X86ISD::FMAX;
21262         break;
21263       }
21264     // Check for x CC y ? y : x -- a min/max with reversed arms.
21265     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21266                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21267       switch (CC) {
21268       default: break;
21269       case ISD::SETOGE:
21270         // Converting this to a min would handle comparisons between positive
21271         // and negative zero incorrectly, and swapping the operands would
21272         // cause it to handle NaNs incorrectly.
21273         if (!DAG.getTarget().Options.UnsafeFPMath &&
21274             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21275           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21276             break;
21277           std::swap(LHS, RHS);
21278         }
21279         Opcode = X86ISD::FMIN;
21280         break;
21281       case ISD::SETUGT:
21282         // Converting this to a min would handle NaNs incorrectly.
21283         if (!DAG.getTarget().Options.UnsafeFPMath &&
21284             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21285           break;
21286         Opcode = X86ISD::FMIN;
21287         break;
21288       case ISD::SETUGE:
21289         // Converting this to a min would handle both negative zeros and NaNs
21290         // incorrectly, but we can swap the operands to fix both.
21291         std::swap(LHS, RHS);
21292       case ISD::SETOGT:
21293       case ISD::SETGT:
21294       case ISD::SETGE:
21295         Opcode = X86ISD::FMIN;
21296         break;
21297
21298       case ISD::SETULT:
21299         // Converting this to a max would handle NaNs incorrectly.
21300         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21301           break;
21302         Opcode = X86ISD::FMAX;
21303         break;
21304       case ISD::SETOLE:
21305         // Converting this to a max would handle comparisons between positive
21306         // and negative zero incorrectly, and swapping the operands would
21307         // cause it to handle NaNs incorrectly.
21308         if (!DAG.getTarget().Options.UnsafeFPMath &&
21309             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21310           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21311             break;
21312           std::swap(LHS, RHS);
21313         }
21314         Opcode = X86ISD::FMAX;
21315         break;
21316       case ISD::SETULE:
21317         // Converting this to a max would handle both negative zeros and NaNs
21318         // incorrectly, but we can swap the operands to fix both.
21319         std::swap(LHS, RHS);
21320       case ISD::SETOLT:
21321       case ISD::SETLT:
21322       case ISD::SETLE:
21323         Opcode = X86ISD::FMAX;
21324         break;
21325       }
21326     }
21327
21328     if (Opcode)
21329       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21330   }
21331
21332   EVT CondVT = Cond.getValueType();
21333   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21334       CondVT.getVectorElementType() == MVT::i1) {
21335     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21336     // lowering on KNL. In this case we convert it to
21337     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21338     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21339     // Since SKX these selects have a proper lowering.
21340     EVT OpVT = LHS.getValueType();
21341     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21342         (OpVT.getVectorElementType() == MVT::i8 ||
21343          OpVT.getVectorElementType() == MVT::i16) &&
21344         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21345       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21346       DCI.AddToWorklist(Cond.getNode());
21347       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21348     }
21349   }
21350   // If this is a select between two integer constants, try to do some
21351   // optimizations.
21352   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21353     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21354       // Don't do this for crazy integer types.
21355       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21356         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21357         // so that TrueC (the true value) is larger than FalseC.
21358         bool NeedsCondInvert = false;
21359
21360         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21361             // Efficiently invertible.
21362             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21363              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21364               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21365           NeedsCondInvert = true;
21366           std::swap(TrueC, FalseC);
21367         }
21368
21369         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21370         if (FalseC->getAPIntValue() == 0 &&
21371             TrueC->getAPIntValue().isPowerOf2()) {
21372           if (NeedsCondInvert) // Invert the condition if needed.
21373             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21374                                DAG.getConstant(1, DL, Cond.getValueType()));
21375
21376           // Zero extend the condition if needed.
21377           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21378
21379           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21380           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21381                              DAG.getConstant(ShAmt, DL, MVT::i8));
21382         }
21383
21384         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21385         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21386           if (NeedsCondInvert) // Invert the condition if needed.
21387             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21388                                DAG.getConstant(1, DL, Cond.getValueType()));
21389
21390           // Zero extend the condition if needed.
21391           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21392                              FalseC->getValueType(0), Cond);
21393           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21394                              SDValue(FalseC, 0));
21395         }
21396
21397         // Optimize cases that will turn into an LEA instruction.  This requires
21398         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21399         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21400           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21401           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21402
21403           bool isFastMultiplier = false;
21404           if (Diff < 10) {
21405             switch ((unsigned char)Diff) {
21406               default: break;
21407               case 1:  // result = add base, cond
21408               case 2:  // result = lea base(    , cond*2)
21409               case 3:  // result = lea base(cond, cond*2)
21410               case 4:  // result = lea base(    , cond*4)
21411               case 5:  // result = lea base(cond, cond*4)
21412               case 8:  // result = lea base(    , cond*8)
21413               case 9:  // result = lea base(cond, cond*8)
21414                 isFastMultiplier = true;
21415                 break;
21416             }
21417           }
21418
21419           if (isFastMultiplier) {
21420             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21421             if (NeedsCondInvert) // Invert the condition if needed.
21422               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21423                                  DAG.getConstant(1, DL, Cond.getValueType()));
21424
21425             // Zero extend the condition if needed.
21426             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21427                                Cond);
21428             // Scale the condition by the difference.
21429             if (Diff != 1)
21430               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21431                                  DAG.getConstant(Diff, DL,
21432                                                  Cond.getValueType()));
21433
21434             // Add the base if non-zero.
21435             if (FalseC->getAPIntValue() != 0)
21436               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21437                                  SDValue(FalseC, 0));
21438             return Cond;
21439           }
21440         }
21441       }
21442   }
21443
21444   // Canonicalize max and min:
21445   // (x > y) ? x : y -> (x >= y) ? x : y
21446   // (x < y) ? x : y -> (x <= y) ? x : y
21447   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21448   // the need for an extra compare
21449   // against zero. e.g.
21450   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21451   // subl   %esi, %edi
21452   // testl  %edi, %edi
21453   // movl   $0, %eax
21454   // cmovgl %edi, %eax
21455   // =>
21456   // xorl   %eax, %eax
21457   // subl   %esi, $edi
21458   // cmovsl %eax, %edi
21459   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21460       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21461       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21462     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21463     switch (CC) {
21464     default: break;
21465     case ISD::SETLT:
21466     case ISD::SETGT: {
21467       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21468       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21469                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21470       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21471     }
21472     }
21473   }
21474
21475   // Early exit check
21476   if (!TLI.isTypeLegal(VT))
21477     return SDValue();
21478
21479   // Match VSELECTs into subs with unsigned saturation.
21480   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21481       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21482       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21483        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21484     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21485
21486     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21487     // left side invert the predicate to simplify logic below.
21488     SDValue Other;
21489     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21490       Other = RHS;
21491       CC = ISD::getSetCCInverse(CC, true);
21492     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21493       Other = LHS;
21494     }
21495
21496     if (Other.getNode() && Other->getNumOperands() == 2 &&
21497         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21498       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21499       SDValue CondRHS = Cond->getOperand(1);
21500
21501       // Look for a general sub with unsigned saturation first.
21502       // x >= y ? x-y : 0 --> subus x, y
21503       // x >  y ? x-y : 0 --> subus x, y
21504       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21505           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21506         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21507
21508       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21509         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21510           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21511             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21512               // If the RHS is a constant we have to reverse the const
21513               // canonicalization.
21514               // x > C-1 ? x+-C : 0 --> subus x, C
21515               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21516                   CondRHSConst->getAPIntValue() ==
21517                       (-OpRHSConst->getAPIntValue() - 1))
21518                 return DAG.getNode(
21519                     X86ISD::SUBUS, DL, VT, OpLHS,
21520                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21521
21522           // Another special case: If C was a sign bit, the sub has been
21523           // canonicalized into a xor.
21524           // FIXME: Would it be better to use computeKnownBits to determine
21525           //        whether it's safe to decanonicalize the xor?
21526           // x s< 0 ? x^C : 0 --> subus x, C
21527           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21528               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21529               OpRHSConst->getAPIntValue().isSignBit())
21530             // Note that we have to rebuild the RHS constant here to ensure we
21531             // don't rely on particular values of undef lanes.
21532             return DAG.getNode(
21533                 X86ISD::SUBUS, DL, VT, OpLHS,
21534                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21535         }
21536     }
21537   }
21538
21539   // Try to match a min/max vector operation.
21540   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21541     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21542     unsigned Opc = ret.first;
21543     bool NeedSplit = ret.second;
21544
21545     if (Opc && NeedSplit) {
21546       unsigned NumElems = VT.getVectorNumElements();
21547       // Extract the LHS vectors
21548       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21549       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21550
21551       // Extract the RHS vectors
21552       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21553       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21554
21555       // Create min/max for each subvector
21556       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21557       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21558
21559       // Merge the result
21560       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21561     } else if (Opc)
21562       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21563   }
21564
21565   // Simplify vector selection if condition value type matches vselect
21566   // operand type
21567   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21568     assert(Cond.getValueType().isVector() &&
21569            "vector select expects a vector selector!");
21570
21571     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21572     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21573
21574     // Try invert the condition if true value is not all 1s and false value
21575     // is not all 0s.
21576     if (!TValIsAllOnes && !FValIsAllZeros &&
21577         // Check if the selector will be produced by CMPP*/PCMP*
21578         Cond.getOpcode() == ISD::SETCC &&
21579         // Check if SETCC has already been promoted
21580         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21581       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21582       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21583
21584       if (TValIsAllZeros || FValIsAllOnes) {
21585         SDValue CC = Cond.getOperand(2);
21586         ISD::CondCode NewCC =
21587           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21588                                Cond.getOperand(0).getValueType().isInteger());
21589         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21590         std::swap(LHS, RHS);
21591         TValIsAllOnes = FValIsAllOnes;
21592         FValIsAllZeros = TValIsAllZeros;
21593       }
21594     }
21595
21596     if (TValIsAllOnes || FValIsAllZeros) {
21597       SDValue Ret;
21598
21599       if (TValIsAllOnes && FValIsAllZeros)
21600         Ret = Cond;
21601       else if (TValIsAllOnes)
21602         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21603                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21604       else if (FValIsAllZeros)
21605         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21606                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21607
21608       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21609     }
21610   }
21611
21612   // We should generate an X86ISD::BLENDI from a vselect if its argument
21613   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21614   // constants. This specific pattern gets generated when we split a
21615   // selector for a 512 bit vector in a machine without AVX512 (but with
21616   // 256-bit vectors), during legalization:
21617   //
21618   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21619   //
21620   // Iff we find this pattern and the build_vectors are built from
21621   // constants, we translate the vselect into a shuffle_vector that we
21622   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21623   if ((N->getOpcode() == ISD::VSELECT ||
21624        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21625       !DCI.isBeforeLegalize()) {
21626     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21627     if (Shuffle.getNode())
21628       return Shuffle;
21629   }
21630
21631   // If this is a *dynamic* select (non-constant condition) and we can match
21632   // this node with one of the variable blend instructions, restructure the
21633   // condition so that the blends can use the high bit of each element and use
21634   // SimplifyDemandedBits to simplify the condition operand.
21635   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21636       !DCI.isBeforeLegalize() &&
21637       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21638     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21639
21640     // Don't optimize vector selects that map to mask-registers.
21641     if (BitWidth == 1)
21642       return SDValue();
21643
21644     // We can only handle the cases where VSELECT is directly legal on the
21645     // subtarget. We custom lower VSELECT nodes with constant conditions and
21646     // this makes it hard to see whether a dynamic VSELECT will correctly
21647     // lower, so we both check the operation's status and explicitly handle the
21648     // cases where a *dynamic* blend will fail even though a constant-condition
21649     // blend could be custom lowered.
21650     // FIXME: We should find a better way to handle this class of problems.
21651     // Potentially, we should combine constant-condition vselect nodes
21652     // pre-legalization into shuffles and not mark as many types as custom
21653     // lowered.
21654     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21655       return SDValue();
21656     // FIXME: We don't support i16-element blends currently. We could and
21657     // should support them by making *all* the bits in the condition be set
21658     // rather than just the high bit and using an i8-element blend.
21659     if (VT.getScalarType() == MVT::i16)
21660       return SDValue();
21661     // Dynamic blending was only available from SSE4.1 onward.
21662     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21663       return SDValue();
21664     // Byte blends are only available in AVX2
21665     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21666         !Subtarget->hasAVX2())
21667       return SDValue();
21668
21669     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21670     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21671
21672     APInt KnownZero, KnownOne;
21673     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21674                                           DCI.isBeforeLegalizeOps());
21675     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21676         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21677                                  TLO)) {
21678       // If we changed the computation somewhere in the DAG, this change
21679       // will affect all users of Cond.
21680       // Make sure it is fine and update all the nodes so that we do not
21681       // use the generic VSELECT anymore. Otherwise, we may perform
21682       // wrong optimizations as we messed up with the actual expectation
21683       // for the vector boolean values.
21684       if (Cond != TLO.Old) {
21685         // Check all uses of that condition operand to check whether it will be
21686         // consumed by non-BLEND instructions, which may depend on all bits are
21687         // set properly.
21688         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21689              I != E; ++I)
21690           if (I->getOpcode() != ISD::VSELECT)
21691             // TODO: Add other opcodes eventually lowered into BLEND.
21692             return SDValue();
21693
21694         // Update all the users of the condition, before committing the change,
21695         // so that the VSELECT optimizations that expect the correct vector
21696         // boolean value will not be triggered.
21697         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21698              I != E; ++I)
21699           DAG.ReplaceAllUsesOfValueWith(
21700               SDValue(*I, 0),
21701               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21702                           Cond, I->getOperand(1), I->getOperand(2)));
21703         DCI.CommitTargetLoweringOpt(TLO);
21704         return SDValue();
21705       }
21706       // At this point, only Cond is changed. Change the condition
21707       // just for N to keep the opportunity to optimize all other
21708       // users their own way.
21709       DAG.ReplaceAllUsesOfValueWith(
21710           SDValue(N, 0),
21711           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21712                       TLO.New, N->getOperand(1), N->getOperand(2)));
21713       return SDValue();
21714     }
21715   }
21716
21717   return SDValue();
21718 }
21719
21720 // Check whether a boolean test is testing a boolean value generated by
21721 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21722 // code.
21723 //
21724 // Simplify the following patterns:
21725 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21726 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21727 // to (Op EFLAGS Cond)
21728 //
21729 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21730 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21731 // to (Op EFLAGS !Cond)
21732 //
21733 // where Op could be BRCOND or CMOV.
21734 //
21735 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21736   // Quit if not CMP and SUB with its value result used.
21737   if (Cmp.getOpcode() != X86ISD::CMP &&
21738       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21739       return SDValue();
21740
21741   // Quit if not used as a boolean value.
21742   if (CC != X86::COND_E && CC != X86::COND_NE)
21743     return SDValue();
21744
21745   // Check CMP operands. One of them should be 0 or 1 and the other should be
21746   // an SetCC or extended from it.
21747   SDValue Op1 = Cmp.getOperand(0);
21748   SDValue Op2 = Cmp.getOperand(1);
21749
21750   SDValue SetCC;
21751   const ConstantSDNode* C = nullptr;
21752   bool needOppositeCond = (CC == X86::COND_E);
21753   bool checkAgainstTrue = false; // Is it a comparison against 1?
21754
21755   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21756     SetCC = Op2;
21757   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21758     SetCC = Op1;
21759   else // Quit if all operands are not constants.
21760     return SDValue();
21761
21762   if (C->getZExtValue() == 1) {
21763     needOppositeCond = !needOppositeCond;
21764     checkAgainstTrue = true;
21765   } else if (C->getZExtValue() != 0)
21766     // Quit if the constant is neither 0 or 1.
21767     return SDValue();
21768
21769   bool truncatedToBoolWithAnd = false;
21770   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21771   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21772          SetCC.getOpcode() == ISD::TRUNCATE ||
21773          SetCC.getOpcode() == ISD::AND) {
21774     if (SetCC.getOpcode() == ISD::AND) {
21775       int OpIdx = -1;
21776       ConstantSDNode *CS;
21777       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21778           CS->getZExtValue() == 1)
21779         OpIdx = 1;
21780       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21781           CS->getZExtValue() == 1)
21782         OpIdx = 0;
21783       if (OpIdx == -1)
21784         break;
21785       SetCC = SetCC.getOperand(OpIdx);
21786       truncatedToBoolWithAnd = true;
21787     } else
21788       SetCC = SetCC.getOperand(0);
21789   }
21790
21791   switch (SetCC.getOpcode()) {
21792   case X86ISD::SETCC_CARRY:
21793     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21794     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21795     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21796     // truncated to i1 using 'and'.
21797     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21798       break;
21799     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21800            "Invalid use of SETCC_CARRY!");
21801     // FALL THROUGH
21802   case X86ISD::SETCC:
21803     // Set the condition code or opposite one if necessary.
21804     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21805     if (needOppositeCond)
21806       CC = X86::GetOppositeBranchCondition(CC);
21807     return SetCC.getOperand(1);
21808   case X86ISD::CMOV: {
21809     // Check whether false/true value has canonical one, i.e. 0 or 1.
21810     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21811     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21812     // Quit if true value is not a constant.
21813     if (!TVal)
21814       return SDValue();
21815     // Quit if false value is not a constant.
21816     if (!FVal) {
21817       SDValue Op = SetCC.getOperand(0);
21818       // Skip 'zext' or 'trunc' node.
21819       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21820           Op.getOpcode() == ISD::TRUNCATE)
21821         Op = Op.getOperand(0);
21822       // A special case for rdrand/rdseed, where 0 is set if false cond is
21823       // found.
21824       if ((Op.getOpcode() != X86ISD::RDRAND &&
21825            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21826         return SDValue();
21827     }
21828     // Quit if false value is not the constant 0 or 1.
21829     bool FValIsFalse = true;
21830     if (FVal && FVal->getZExtValue() != 0) {
21831       if (FVal->getZExtValue() != 1)
21832         return SDValue();
21833       // If FVal is 1, opposite cond is needed.
21834       needOppositeCond = !needOppositeCond;
21835       FValIsFalse = false;
21836     }
21837     // Quit if TVal is not the constant opposite of FVal.
21838     if (FValIsFalse && TVal->getZExtValue() != 1)
21839       return SDValue();
21840     if (!FValIsFalse && TVal->getZExtValue() != 0)
21841       return SDValue();
21842     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21843     if (needOppositeCond)
21844       CC = X86::GetOppositeBranchCondition(CC);
21845     return SetCC.getOperand(3);
21846   }
21847   }
21848
21849   return SDValue();
21850 }
21851
21852 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21853 /// Match:
21854 ///   (X86or (X86setcc) (X86setcc))
21855 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21856 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21857                                            X86::CondCode &CC1, SDValue &Flags,
21858                                            bool &isAnd) {
21859   if (Cond->getOpcode() == X86ISD::CMP) {
21860     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21861     if (!CondOp1C || !CondOp1C->isNullValue())
21862       return false;
21863
21864     Cond = Cond->getOperand(0);
21865   }
21866
21867   isAnd = false;
21868
21869   SDValue SetCC0, SetCC1;
21870   switch (Cond->getOpcode()) {
21871   default: return false;
21872   case ISD::AND:
21873   case X86ISD::AND:
21874     isAnd = true;
21875     // fallthru
21876   case ISD::OR:
21877   case X86ISD::OR:
21878     SetCC0 = Cond->getOperand(0);
21879     SetCC1 = Cond->getOperand(1);
21880     break;
21881   };
21882
21883   // Make sure we have SETCC nodes, using the same flags value.
21884   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21885       SetCC1.getOpcode() != X86ISD::SETCC ||
21886       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21887     return false;
21888
21889   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21890   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21891   Flags = SetCC0->getOperand(1);
21892   return true;
21893 }
21894
21895 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21896 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21897                                   TargetLowering::DAGCombinerInfo &DCI,
21898                                   const X86Subtarget *Subtarget) {
21899   SDLoc DL(N);
21900
21901   // If the flag operand isn't dead, don't touch this CMOV.
21902   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21903     return SDValue();
21904
21905   SDValue FalseOp = N->getOperand(0);
21906   SDValue TrueOp = N->getOperand(1);
21907   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21908   SDValue Cond = N->getOperand(3);
21909
21910   if (CC == X86::COND_E || CC == X86::COND_NE) {
21911     switch (Cond.getOpcode()) {
21912     default: break;
21913     case X86ISD::BSR:
21914     case X86ISD::BSF:
21915       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21916       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21917         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21918     }
21919   }
21920
21921   SDValue Flags;
21922
21923   Flags = checkBoolTestSetCCCombine(Cond, CC);
21924   if (Flags.getNode() &&
21925       // Extra check as FCMOV only supports a subset of X86 cond.
21926       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21927     SDValue Ops[] = { FalseOp, TrueOp,
21928                       DAG.getConstant(CC, DL, MVT::i8), Flags };
21929     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21930   }
21931
21932   // If this is a select between two integer constants, try to do some
21933   // optimizations.  Note that the operands are ordered the opposite of SELECT
21934   // operands.
21935   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21936     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21937       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21938       // larger than FalseC (the false value).
21939       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21940         CC = X86::GetOppositeBranchCondition(CC);
21941         std::swap(TrueC, FalseC);
21942         std::swap(TrueOp, FalseOp);
21943       }
21944
21945       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21946       // This is efficient for any integer data type (including i8/i16) and
21947       // shift amount.
21948       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21949         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21950                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21951
21952         // Zero extend the condition if needed.
21953         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21954
21955         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21956         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21957                            DAG.getConstant(ShAmt, DL, MVT::i8));
21958         if (N->getNumValues() == 2)  // Dead flag value?
21959           return DCI.CombineTo(N, Cond, SDValue());
21960         return Cond;
21961       }
21962
21963       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21964       // for any integer data type, including i8/i16.
21965       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21966         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21967                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21968
21969         // Zero extend the condition if needed.
21970         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21971                            FalseC->getValueType(0), Cond);
21972         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21973                            SDValue(FalseC, 0));
21974
21975         if (N->getNumValues() == 2)  // Dead flag value?
21976           return DCI.CombineTo(N, Cond, SDValue());
21977         return Cond;
21978       }
21979
21980       // Optimize cases that will turn into an LEA instruction.  This requires
21981       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21982       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21983         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21984         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21985
21986         bool isFastMultiplier = false;
21987         if (Diff < 10) {
21988           switch ((unsigned char)Diff) {
21989           default: break;
21990           case 1:  // result = add base, cond
21991           case 2:  // result = lea base(    , cond*2)
21992           case 3:  // result = lea base(cond, cond*2)
21993           case 4:  // result = lea base(    , cond*4)
21994           case 5:  // result = lea base(cond, cond*4)
21995           case 8:  // result = lea base(    , cond*8)
21996           case 9:  // result = lea base(cond, cond*8)
21997             isFastMultiplier = true;
21998             break;
21999           }
22000         }
22001
22002         if (isFastMultiplier) {
22003           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22004           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22005                              DAG.getConstant(CC, DL, MVT::i8), Cond);
22006           // Zero extend the condition if needed.
22007           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22008                              Cond);
22009           // Scale the condition by the difference.
22010           if (Diff != 1)
22011             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22012                                DAG.getConstant(Diff, DL, Cond.getValueType()));
22013
22014           // Add the base if non-zero.
22015           if (FalseC->getAPIntValue() != 0)
22016             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22017                                SDValue(FalseC, 0));
22018           if (N->getNumValues() == 2)  // Dead flag value?
22019             return DCI.CombineTo(N, Cond, SDValue());
22020           return Cond;
22021         }
22022       }
22023     }
22024   }
22025
22026   // Handle these cases:
22027   //   (select (x != c), e, c) -> select (x != c), e, x),
22028   //   (select (x == c), c, e) -> select (x == c), x, e)
22029   // where the c is an integer constant, and the "select" is the combination
22030   // of CMOV and CMP.
22031   //
22032   // The rationale for this change is that the conditional-move from a constant
22033   // needs two instructions, however, conditional-move from a register needs
22034   // only one instruction.
22035   //
22036   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22037   //  some instruction-combining opportunities. This opt needs to be
22038   //  postponed as late as possible.
22039   //
22040   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22041     // the DCI.xxxx conditions are provided to postpone the optimization as
22042     // late as possible.
22043
22044     ConstantSDNode *CmpAgainst = nullptr;
22045     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22046         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22047         !isa<ConstantSDNode>(Cond.getOperand(0))) {
22048
22049       if (CC == X86::COND_NE &&
22050           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22051         CC = X86::GetOppositeBranchCondition(CC);
22052         std::swap(TrueOp, FalseOp);
22053       }
22054
22055       if (CC == X86::COND_E &&
22056           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22057         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22058                           DAG.getConstant(CC, DL, MVT::i8), Cond };
22059         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22060       }
22061     }
22062   }
22063
22064   // Fold and/or of setcc's to double CMOV:
22065   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22066   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22067   //
22068   // This combine lets us generate:
22069   //   cmovcc1 (jcc1 if we don't have CMOV)
22070   //   cmovcc2 (same)
22071   // instead of:
22072   //   setcc1
22073   //   setcc2
22074   //   and/or
22075   //   cmovne (jne if we don't have CMOV)
22076   // When we can't use the CMOV instruction, it might increase branch
22077   // mispredicts.
22078   // When we can use CMOV, or when there is no mispredict, this improves
22079   // throughput and reduces register pressure.
22080   //
22081   if (CC == X86::COND_NE) {
22082     SDValue Flags;
22083     X86::CondCode CC0, CC1;
22084     bool isAndSetCC;
22085     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22086       if (isAndSetCC) {
22087         std::swap(FalseOp, TrueOp);
22088         CC0 = X86::GetOppositeBranchCondition(CC0);
22089         CC1 = X86::GetOppositeBranchCondition(CC1);
22090       }
22091
22092       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22093         Flags};
22094       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22095       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22096       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22097       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22098       return CMOV;
22099     }
22100   }
22101
22102   return SDValue();
22103 }
22104
22105 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22106                                                 const X86Subtarget *Subtarget) {
22107   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22108   switch (IntNo) {
22109   default: return SDValue();
22110   // SSE/AVX/AVX2 blend intrinsics.
22111   case Intrinsic::x86_avx2_pblendvb:
22112     // Don't try to simplify this intrinsic if we don't have AVX2.
22113     if (!Subtarget->hasAVX2())
22114       return SDValue();
22115     // FALL-THROUGH
22116   case Intrinsic::x86_avx_blendv_pd_256:
22117   case Intrinsic::x86_avx_blendv_ps_256:
22118     // Don't try to simplify this intrinsic if we don't have AVX.
22119     if (!Subtarget->hasAVX())
22120       return SDValue();
22121     // FALL-THROUGH
22122   case Intrinsic::x86_sse41_blendvps:
22123   case Intrinsic::x86_sse41_blendvpd:
22124   case Intrinsic::x86_sse41_pblendvb: {
22125     SDValue Op0 = N->getOperand(1);
22126     SDValue Op1 = N->getOperand(2);
22127     SDValue Mask = N->getOperand(3);
22128
22129     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22130     if (!Subtarget->hasSSE41())
22131       return SDValue();
22132
22133     // fold (blend A, A, Mask) -> A
22134     if (Op0 == Op1)
22135       return Op0;
22136     // fold (blend A, B, allZeros) -> A
22137     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22138       return Op0;
22139     // fold (blend A, B, allOnes) -> B
22140     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22141       return Op1;
22142
22143     // Simplify the case where the mask is a constant i32 value.
22144     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22145       if (C->isNullValue())
22146         return Op0;
22147       if (C->isAllOnesValue())
22148         return Op1;
22149     }
22150
22151     return SDValue();
22152   }
22153
22154   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22155   case Intrinsic::x86_sse2_psrai_w:
22156   case Intrinsic::x86_sse2_psrai_d:
22157   case Intrinsic::x86_avx2_psrai_w:
22158   case Intrinsic::x86_avx2_psrai_d:
22159   case Intrinsic::x86_sse2_psra_w:
22160   case Intrinsic::x86_sse2_psra_d:
22161   case Intrinsic::x86_avx2_psra_w:
22162   case Intrinsic::x86_avx2_psra_d: {
22163     SDValue Op0 = N->getOperand(1);
22164     SDValue Op1 = N->getOperand(2);
22165     EVT VT = Op0.getValueType();
22166     assert(VT.isVector() && "Expected a vector type!");
22167
22168     if (isa<BuildVectorSDNode>(Op1))
22169       Op1 = Op1.getOperand(0);
22170
22171     if (!isa<ConstantSDNode>(Op1))
22172       return SDValue();
22173
22174     EVT SVT = VT.getVectorElementType();
22175     unsigned SVTBits = SVT.getSizeInBits();
22176
22177     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22178     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22179     uint64_t ShAmt = C.getZExtValue();
22180
22181     // Don't try to convert this shift into a ISD::SRA if the shift
22182     // count is bigger than or equal to the element size.
22183     if (ShAmt >= SVTBits)
22184       return SDValue();
22185
22186     // Trivial case: if the shift count is zero, then fold this
22187     // into the first operand.
22188     if (ShAmt == 0)
22189       return Op0;
22190
22191     // Replace this packed shift intrinsic with a target independent
22192     // shift dag node.
22193     SDLoc DL(N);
22194     SDValue Splat = DAG.getConstant(C, DL, VT);
22195     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22196   }
22197   }
22198 }
22199
22200 /// PerformMulCombine - Optimize a single multiply with constant into two
22201 /// in order to implement it with two cheaper instructions, e.g.
22202 /// LEA + SHL, LEA + LEA.
22203 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22204                                  TargetLowering::DAGCombinerInfo &DCI) {
22205   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22206     return SDValue();
22207
22208   EVT VT = N->getValueType(0);
22209   if (VT != MVT::i64 && VT != MVT::i32)
22210     return SDValue();
22211
22212   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22213   if (!C)
22214     return SDValue();
22215   uint64_t MulAmt = C->getZExtValue();
22216   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22217     return SDValue();
22218
22219   uint64_t MulAmt1 = 0;
22220   uint64_t MulAmt2 = 0;
22221   if ((MulAmt % 9) == 0) {
22222     MulAmt1 = 9;
22223     MulAmt2 = MulAmt / 9;
22224   } else if ((MulAmt % 5) == 0) {
22225     MulAmt1 = 5;
22226     MulAmt2 = MulAmt / 5;
22227   } else if ((MulAmt % 3) == 0) {
22228     MulAmt1 = 3;
22229     MulAmt2 = MulAmt / 3;
22230   }
22231   if (MulAmt2 &&
22232       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22233     SDLoc DL(N);
22234
22235     if (isPowerOf2_64(MulAmt2) &&
22236         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22237       // If second multiplifer is pow2, issue it first. We want the multiply by
22238       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22239       // is an add.
22240       std::swap(MulAmt1, MulAmt2);
22241
22242     SDValue NewMul;
22243     if (isPowerOf2_64(MulAmt1))
22244       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22245                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22246     else
22247       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22248                            DAG.getConstant(MulAmt1, DL, VT));
22249
22250     if (isPowerOf2_64(MulAmt2))
22251       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22252                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22253     else
22254       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22255                            DAG.getConstant(MulAmt2, DL, VT));
22256
22257     // Do not add new nodes to DAG combiner worklist.
22258     DCI.CombineTo(N, NewMul, false);
22259   }
22260   return SDValue();
22261 }
22262
22263 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22264   SDValue N0 = N->getOperand(0);
22265   SDValue N1 = N->getOperand(1);
22266   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22267   EVT VT = N0.getValueType();
22268
22269   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22270   // since the result of setcc_c is all zero's or all ones.
22271   if (VT.isInteger() && !VT.isVector() &&
22272       N1C && N0.getOpcode() == ISD::AND &&
22273       N0.getOperand(1).getOpcode() == ISD::Constant) {
22274     SDValue N00 = N0.getOperand(0);
22275     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22276         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22277           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22278          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22279       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22280       APInt ShAmt = N1C->getAPIntValue();
22281       Mask = Mask.shl(ShAmt);
22282       if (Mask != 0) {
22283         SDLoc DL(N);
22284         return DAG.getNode(ISD::AND, DL, VT,
22285                            N00, DAG.getConstant(Mask, DL, VT));
22286       }
22287     }
22288   }
22289
22290   // Hardware support for vector shifts is sparse which makes us scalarize the
22291   // vector operations in many cases. Also, on sandybridge ADD is faster than
22292   // shl.
22293   // (shl V, 1) -> add V,V
22294   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22295     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22296       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22297       // We shift all of the values by one. In many cases we do not have
22298       // hardware support for this operation. This is better expressed as an ADD
22299       // of two values.
22300       if (N1SplatC->getZExtValue() == 1)
22301         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22302     }
22303
22304   return SDValue();
22305 }
22306
22307 /// \brief Returns a vector of 0s if the node in input is a vector logical
22308 /// shift by a constant amount which is known to be bigger than or equal
22309 /// to the vector element size in bits.
22310 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22311                                       const X86Subtarget *Subtarget) {
22312   EVT VT = N->getValueType(0);
22313
22314   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22315       (!Subtarget->hasInt256() ||
22316        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22317     return SDValue();
22318
22319   SDValue Amt = N->getOperand(1);
22320   SDLoc DL(N);
22321   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22322     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22323       APInt ShiftAmt = AmtSplat->getAPIntValue();
22324       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22325
22326       // SSE2/AVX2 logical shifts always return a vector of 0s
22327       // if the shift amount is bigger than or equal to
22328       // the element size. The constant shift amount will be
22329       // encoded as a 8-bit immediate.
22330       if (ShiftAmt.trunc(8).uge(MaxAmount))
22331         return getZeroVector(VT, Subtarget, DAG, DL);
22332     }
22333
22334   return SDValue();
22335 }
22336
22337 /// PerformShiftCombine - Combine shifts.
22338 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22339                                    TargetLowering::DAGCombinerInfo &DCI,
22340                                    const X86Subtarget *Subtarget) {
22341   if (N->getOpcode() == ISD::SHL) {
22342     SDValue V = PerformSHLCombine(N, DAG);
22343     if (V.getNode()) return V;
22344   }
22345
22346   if (N->getOpcode() != ISD::SRA) {
22347     // Try to fold this logical shift into a zero vector.
22348     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22349     if (V.getNode()) return V;
22350   }
22351
22352   return SDValue();
22353 }
22354
22355 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22356 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22357 // and friends.  Likewise for OR -> CMPNEQSS.
22358 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22359                             TargetLowering::DAGCombinerInfo &DCI,
22360                             const X86Subtarget *Subtarget) {
22361   unsigned opcode;
22362
22363   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22364   // we're requiring SSE2 for both.
22365   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22366     SDValue N0 = N->getOperand(0);
22367     SDValue N1 = N->getOperand(1);
22368     SDValue CMP0 = N0->getOperand(1);
22369     SDValue CMP1 = N1->getOperand(1);
22370     SDLoc DL(N);
22371
22372     // The SETCCs should both refer to the same CMP.
22373     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22374       return SDValue();
22375
22376     SDValue CMP00 = CMP0->getOperand(0);
22377     SDValue CMP01 = CMP0->getOperand(1);
22378     EVT     VT    = CMP00.getValueType();
22379
22380     if (VT == MVT::f32 || VT == MVT::f64) {
22381       bool ExpectingFlags = false;
22382       // Check for any users that want flags:
22383       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22384            !ExpectingFlags && UI != UE; ++UI)
22385         switch (UI->getOpcode()) {
22386         default:
22387         case ISD::BR_CC:
22388         case ISD::BRCOND:
22389         case ISD::SELECT:
22390           ExpectingFlags = true;
22391           break;
22392         case ISD::CopyToReg:
22393         case ISD::SIGN_EXTEND:
22394         case ISD::ZERO_EXTEND:
22395         case ISD::ANY_EXTEND:
22396           break;
22397         }
22398
22399       if (!ExpectingFlags) {
22400         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22401         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22402
22403         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22404           X86::CondCode tmp = cc0;
22405           cc0 = cc1;
22406           cc1 = tmp;
22407         }
22408
22409         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22410             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22411           // FIXME: need symbolic constants for these magic numbers.
22412           // See X86ATTInstPrinter.cpp:printSSECC().
22413           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22414           if (Subtarget->hasAVX512()) {
22415             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22416                                          CMP01,
22417                                          DAG.getConstant(x86cc, DL, MVT::i8));
22418             if (N->getValueType(0) != MVT::i1)
22419               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22420                                  FSetCC);
22421             return FSetCC;
22422           }
22423           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22424                                               CMP00.getValueType(), CMP00, CMP01,
22425                                               DAG.getConstant(x86cc, DL,
22426                                                               MVT::i8));
22427
22428           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22429           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22430
22431           if (is64BitFP && !Subtarget->is64Bit()) {
22432             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22433             // 64-bit integer, since that's not a legal type. Since
22434             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22435             // bits, but can do this little dance to extract the lowest 32 bits
22436             // and work with those going forward.
22437             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22438                                            OnesOrZeroesF);
22439             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22440                                            Vector64);
22441             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22442                                         Vector32, DAG.getIntPtrConstant(0, DL));
22443             IntVT = MVT::i32;
22444           }
22445
22446           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22447                                               OnesOrZeroesF);
22448           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22449                                       DAG.getConstant(1, DL, IntVT));
22450           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22451                                               ANDed);
22452           return OneBitOfTruth;
22453         }
22454       }
22455     }
22456   }
22457   return SDValue();
22458 }
22459
22460 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22461 /// so it can be folded inside ANDNP.
22462 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22463   EVT VT = N->getValueType(0);
22464
22465   // Match direct AllOnes for 128 and 256-bit vectors
22466   if (ISD::isBuildVectorAllOnes(N))
22467     return true;
22468
22469   // Look through a bit convert.
22470   if (N->getOpcode() == ISD::BITCAST)
22471     N = N->getOperand(0).getNode();
22472
22473   // Sometimes the operand may come from a insert_subvector building a 256-bit
22474   // allones vector
22475   if (VT.is256BitVector() &&
22476       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22477     SDValue V1 = N->getOperand(0);
22478     SDValue V2 = N->getOperand(1);
22479
22480     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22481         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22482         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22483         ISD::isBuildVectorAllOnes(V2.getNode()))
22484       return true;
22485   }
22486
22487   return false;
22488 }
22489
22490 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22491 // register. In most cases we actually compare or select YMM-sized registers
22492 // and mixing the two types creates horrible code. This method optimizes
22493 // some of the transition sequences.
22494 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22495                                  TargetLowering::DAGCombinerInfo &DCI,
22496                                  const X86Subtarget *Subtarget) {
22497   EVT VT = N->getValueType(0);
22498   if (!VT.is256BitVector())
22499     return SDValue();
22500
22501   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22502           N->getOpcode() == ISD::ZERO_EXTEND ||
22503           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22504
22505   SDValue Narrow = N->getOperand(0);
22506   EVT NarrowVT = Narrow->getValueType(0);
22507   if (!NarrowVT.is128BitVector())
22508     return SDValue();
22509
22510   if (Narrow->getOpcode() != ISD::XOR &&
22511       Narrow->getOpcode() != ISD::AND &&
22512       Narrow->getOpcode() != ISD::OR)
22513     return SDValue();
22514
22515   SDValue N0  = Narrow->getOperand(0);
22516   SDValue N1  = Narrow->getOperand(1);
22517   SDLoc DL(Narrow);
22518
22519   // The Left side has to be a trunc.
22520   if (N0.getOpcode() != ISD::TRUNCATE)
22521     return SDValue();
22522
22523   // The type of the truncated inputs.
22524   EVT WideVT = N0->getOperand(0)->getValueType(0);
22525   if (WideVT != VT)
22526     return SDValue();
22527
22528   // The right side has to be a 'trunc' or a constant vector.
22529   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22530   ConstantSDNode *RHSConstSplat = nullptr;
22531   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22532     RHSConstSplat = RHSBV->getConstantSplatNode();
22533   if (!RHSTrunc && !RHSConstSplat)
22534     return SDValue();
22535
22536   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22537
22538   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22539     return SDValue();
22540
22541   // Set N0 and N1 to hold the inputs to the new wide operation.
22542   N0 = N0->getOperand(0);
22543   if (RHSConstSplat) {
22544     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22545                      SDValue(RHSConstSplat, 0));
22546     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22547     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22548   } else if (RHSTrunc) {
22549     N1 = N1->getOperand(0);
22550   }
22551
22552   // Generate the wide operation.
22553   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22554   unsigned Opcode = N->getOpcode();
22555   switch (Opcode) {
22556   case ISD::ANY_EXTEND:
22557     return Op;
22558   case ISD::ZERO_EXTEND: {
22559     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22560     APInt Mask = APInt::getAllOnesValue(InBits);
22561     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22562     return DAG.getNode(ISD::AND, DL, VT,
22563                        Op, DAG.getConstant(Mask, DL, VT));
22564   }
22565   case ISD::SIGN_EXTEND:
22566     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22567                        Op, DAG.getValueType(NarrowVT));
22568   default:
22569     llvm_unreachable("Unexpected opcode");
22570   }
22571 }
22572
22573 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22574                                  TargetLowering::DAGCombinerInfo &DCI,
22575                                  const X86Subtarget *Subtarget) {
22576   SDValue N0 = N->getOperand(0);
22577   SDValue N1 = N->getOperand(1);
22578   SDLoc DL(N);
22579
22580   // A vector zext_in_reg may be represented as a shuffle,
22581   // feeding into a bitcast (this represents anyext) feeding into
22582   // an and with a mask.
22583   // We'd like to try to combine that into a shuffle with zero
22584   // plus a bitcast, removing the and.
22585   if (N0.getOpcode() != ISD::BITCAST ||
22586       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22587     return SDValue();
22588
22589   // The other side of the AND should be a splat of 2^C, where C
22590   // is the number of bits in the source type.
22591   if (N1.getOpcode() == ISD::BITCAST)
22592     N1 = N1.getOperand(0);
22593   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22594     return SDValue();
22595   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22596
22597   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22598   EVT SrcType = Shuffle->getValueType(0);
22599
22600   // We expect a single-source shuffle
22601   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22602     return SDValue();
22603
22604   unsigned SrcSize = SrcType.getScalarSizeInBits();
22605
22606   APInt SplatValue, SplatUndef;
22607   unsigned SplatBitSize;
22608   bool HasAnyUndefs;
22609   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22610                                 SplatBitSize, HasAnyUndefs))
22611     return SDValue();
22612
22613   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22614   // Make sure the splat matches the mask we expect
22615   if (SplatBitSize > ResSize ||
22616       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22617     return SDValue();
22618
22619   // Make sure the input and output size make sense
22620   if (SrcSize >= ResSize || ResSize % SrcSize)
22621     return SDValue();
22622
22623   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22624   // The number of u's between each two values depends on the ratio between
22625   // the source and dest type.
22626   unsigned ZextRatio = ResSize / SrcSize;
22627   bool IsZext = true;
22628   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22629     if (i % ZextRatio) {
22630       if (Shuffle->getMaskElt(i) > 0) {
22631         // Expected undef
22632         IsZext = false;
22633         break;
22634       }
22635     } else {
22636       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22637         // Expected element number
22638         IsZext = false;
22639         break;
22640       }
22641     }
22642   }
22643
22644   if (!IsZext)
22645     return SDValue();
22646
22647   // Ok, perform the transformation - replace the shuffle with
22648   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22649   // (instead of undef) where the k elements come from the zero vector.
22650   SmallVector<int, 8> Mask;
22651   unsigned NumElems = SrcType.getVectorNumElements();
22652   for (unsigned i = 0; i < NumElems; ++i)
22653     if (i % ZextRatio)
22654       Mask.push_back(NumElems);
22655     else
22656       Mask.push_back(i / ZextRatio);
22657
22658   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22659     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22660   return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22661 }
22662
22663 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22664                                  TargetLowering::DAGCombinerInfo &DCI,
22665                                  const X86Subtarget *Subtarget) {
22666   if (DCI.isBeforeLegalizeOps())
22667     return SDValue();
22668
22669   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22670     return Zext;
22671
22672   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22673     return R;
22674
22675   EVT VT = N->getValueType(0);
22676   SDValue N0 = N->getOperand(0);
22677   SDValue N1 = N->getOperand(1);
22678   SDLoc DL(N);
22679
22680   // Create BEXTR instructions
22681   // BEXTR is ((X >> imm) & (2**size-1))
22682   if (VT == MVT::i32 || VT == MVT::i64) {
22683     // Check for BEXTR.
22684     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22685         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22686       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22687       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22688       if (MaskNode && ShiftNode) {
22689         uint64_t Mask = MaskNode->getZExtValue();
22690         uint64_t Shift = ShiftNode->getZExtValue();
22691         if (isMask_64(Mask)) {
22692           uint64_t MaskSize = countPopulation(Mask);
22693           if (Shift + MaskSize <= VT.getSizeInBits())
22694             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22695                                DAG.getConstant(Shift | (MaskSize << 8), DL,
22696                                                VT));
22697         }
22698       }
22699     } // BEXTR
22700
22701     return SDValue();
22702   }
22703
22704   // Want to form ANDNP nodes:
22705   // 1) In the hopes of then easily combining them with OR and AND nodes
22706   //    to form PBLEND/PSIGN.
22707   // 2) To match ANDN packed intrinsics
22708   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22709     return SDValue();
22710
22711   // Check LHS for vnot
22712   if (N0.getOpcode() == ISD::XOR &&
22713       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22714       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22715     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22716
22717   // Check RHS for vnot
22718   if (N1.getOpcode() == ISD::XOR &&
22719       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22720       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22721     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22722
22723   return SDValue();
22724 }
22725
22726 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22727                                 TargetLowering::DAGCombinerInfo &DCI,
22728                                 const X86Subtarget *Subtarget) {
22729   if (DCI.isBeforeLegalizeOps())
22730     return SDValue();
22731
22732   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22733   if (R.getNode())
22734     return R;
22735
22736   SDValue N0 = N->getOperand(0);
22737   SDValue N1 = N->getOperand(1);
22738   EVT VT = N->getValueType(0);
22739
22740   // look for psign/blend
22741   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22742     if (!Subtarget->hasSSSE3() ||
22743         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22744       return SDValue();
22745
22746     // Canonicalize pandn to RHS
22747     if (N0.getOpcode() == X86ISD::ANDNP)
22748       std::swap(N0, N1);
22749     // or (and (m, y), (pandn m, x))
22750     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22751       SDValue Mask = N1.getOperand(0);
22752       SDValue X    = N1.getOperand(1);
22753       SDValue Y;
22754       if (N0.getOperand(0) == Mask)
22755         Y = N0.getOperand(1);
22756       if (N0.getOperand(1) == Mask)
22757         Y = N0.getOperand(0);
22758
22759       // Check to see if the mask appeared in both the AND and ANDNP and
22760       if (!Y.getNode())
22761         return SDValue();
22762
22763       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22764       // Look through mask bitcast.
22765       if (Mask.getOpcode() == ISD::BITCAST)
22766         Mask = Mask.getOperand(0);
22767       if (X.getOpcode() == ISD::BITCAST)
22768         X = X.getOperand(0);
22769       if (Y.getOpcode() == ISD::BITCAST)
22770         Y = Y.getOperand(0);
22771
22772       EVT MaskVT = Mask.getValueType();
22773
22774       // Validate that the Mask operand is a vector sra node.
22775       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22776       // there is no psrai.b
22777       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22778       unsigned SraAmt = ~0;
22779       if (Mask.getOpcode() == ISD::SRA) {
22780         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22781           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22782             SraAmt = AmtConst->getZExtValue();
22783       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22784         SDValue SraC = Mask.getOperand(1);
22785         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22786       }
22787       if ((SraAmt + 1) != EltBits)
22788         return SDValue();
22789
22790       SDLoc DL(N);
22791
22792       // Now we know we at least have a plendvb with the mask val.  See if
22793       // we can form a psignb/w/d.
22794       // psign = x.type == y.type == mask.type && y = sub(0, x);
22795       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22796           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22797           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22798         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22799                "Unsupported VT for PSIGN");
22800         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22801         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22802       }
22803       // PBLENDVB only available on SSE 4.1
22804       if (!Subtarget->hasSSE41())
22805         return SDValue();
22806
22807       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22808
22809       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22810       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22811       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22812       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22813       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22814     }
22815   }
22816
22817   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22818     return SDValue();
22819
22820   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22821   MachineFunction &MF = DAG.getMachineFunction();
22822   bool OptForSize =
22823       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22824
22825   // SHLD/SHRD instructions have lower register pressure, but on some
22826   // platforms they have higher latency than the equivalent
22827   // series of shifts/or that would otherwise be generated.
22828   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22829   // have higher latencies and we are not optimizing for size.
22830   if (!OptForSize && Subtarget->isSHLDSlow())
22831     return SDValue();
22832
22833   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22834     std::swap(N0, N1);
22835   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22836     return SDValue();
22837   if (!N0.hasOneUse() || !N1.hasOneUse())
22838     return SDValue();
22839
22840   SDValue ShAmt0 = N0.getOperand(1);
22841   if (ShAmt0.getValueType() != MVT::i8)
22842     return SDValue();
22843   SDValue ShAmt1 = N1.getOperand(1);
22844   if (ShAmt1.getValueType() != MVT::i8)
22845     return SDValue();
22846   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22847     ShAmt0 = ShAmt0.getOperand(0);
22848   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22849     ShAmt1 = ShAmt1.getOperand(0);
22850
22851   SDLoc DL(N);
22852   unsigned Opc = X86ISD::SHLD;
22853   SDValue Op0 = N0.getOperand(0);
22854   SDValue Op1 = N1.getOperand(0);
22855   if (ShAmt0.getOpcode() == ISD::SUB) {
22856     Opc = X86ISD::SHRD;
22857     std::swap(Op0, Op1);
22858     std::swap(ShAmt0, ShAmt1);
22859   }
22860
22861   unsigned Bits = VT.getSizeInBits();
22862   if (ShAmt1.getOpcode() == ISD::SUB) {
22863     SDValue Sum = ShAmt1.getOperand(0);
22864     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22865       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22866       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22867         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22868       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22869         return DAG.getNode(Opc, DL, VT,
22870                            Op0, Op1,
22871                            DAG.getNode(ISD::TRUNCATE, DL,
22872                                        MVT::i8, ShAmt0));
22873     }
22874   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22875     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22876     if (ShAmt0C &&
22877         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22878       return DAG.getNode(Opc, DL, VT,
22879                          N0.getOperand(0), N1.getOperand(0),
22880                          DAG.getNode(ISD::TRUNCATE, DL,
22881                                        MVT::i8, ShAmt0));
22882   }
22883
22884   return SDValue();
22885 }
22886
22887 // Generate NEG and CMOV for integer abs.
22888 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22889   EVT VT = N->getValueType(0);
22890
22891   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22892   // 8-bit integer abs to NEG and CMOV.
22893   if (VT.isInteger() && VT.getSizeInBits() == 8)
22894     return SDValue();
22895
22896   SDValue N0 = N->getOperand(0);
22897   SDValue N1 = N->getOperand(1);
22898   SDLoc DL(N);
22899
22900   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22901   // and change it to SUB and CMOV.
22902   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22903       N0.getOpcode() == ISD::ADD &&
22904       N0.getOperand(1) == N1 &&
22905       N1.getOpcode() == ISD::SRA &&
22906       N1.getOperand(0) == N0.getOperand(0))
22907     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22908       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22909         // Generate SUB & CMOV.
22910         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22911                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
22912
22913         SDValue Ops[] = { N0.getOperand(0), Neg,
22914                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22915                           SDValue(Neg.getNode(), 1) };
22916         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22917       }
22918   return SDValue();
22919 }
22920
22921 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22922 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22923                                  TargetLowering::DAGCombinerInfo &DCI,
22924                                  const X86Subtarget *Subtarget) {
22925   if (DCI.isBeforeLegalizeOps())
22926     return SDValue();
22927
22928   if (Subtarget->hasCMov()) {
22929     SDValue RV = performIntegerAbsCombine(N, DAG);
22930     if (RV.getNode())
22931       return RV;
22932   }
22933
22934   return SDValue();
22935 }
22936
22937 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22938 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22939                                   TargetLowering::DAGCombinerInfo &DCI,
22940                                   const X86Subtarget *Subtarget) {
22941   LoadSDNode *Ld = cast<LoadSDNode>(N);
22942   EVT RegVT = Ld->getValueType(0);
22943   EVT MemVT = Ld->getMemoryVT();
22944   SDLoc dl(Ld);
22945   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22946
22947   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22948   // into two 16-byte operations.
22949   ISD::LoadExtType Ext = Ld->getExtensionType();
22950   unsigned Alignment = Ld->getAlignment();
22951   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22952   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22953       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22954     unsigned NumElems = RegVT.getVectorNumElements();
22955     if (NumElems < 2)
22956       return SDValue();
22957
22958     SDValue Ptr = Ld->getBasePtr();
22959     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
22960
22961     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22962                                   NumElems/2);
22963     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22964                                 Ld->getPointerInfo(), Ld->isVolatile(),
22965                                 Ld->isNonTemporal(), Ld->isInvariant(),
22966                                 Alignment);
22967     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22968     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22969                                 Ld->getPointerInfo(), Ld->isVolatile(),
22970                                 Ld->isNonTemporal(), Ld->isInvariant(),
22971                                 std::min(16U, Alignment));
22972     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22973                              Load1.getValue(1),
22974                              Load2.getValue(1));
22975
22976     SDValue NewVec = DAG.getUNDEF(RegVT);
22977     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22978     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22979     return DCI.CombineTo(N, NewVec, TF, true);
22980   }
22981
22982   return SDValue();
22983 }
22984
22985 /// PerformMLOADCombine - Resolve extending loads
22986 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22987                                    TargetLowering::DAGCombinerInfo &DCI,
22988                                    const X86Subtarget *Subtarget) {
22989   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22990   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22991     return SDValue();
22992
22993   EVT VT = Mld->getValueType(0);
22994   unsigned NumElems = VT.getVectorNumElements();
22995   EVT LdVT = Mld->getMemoryVT();
22996   SDLoc dl(Mld);
22997
22998   assert(LdVT != VT && "Cannot extend to the same type");
22999   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23000   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23001   // From, To sizes and ElemCount must be pow of two
23002   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23003     "Unexpected size for extending masked load");
23004
23005   unsigned SizeRatio  = ToSz / FromSz;
23006   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23007
23008   // Create a type on which we perform the shuffle
23009   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23010           LdVT.getScalarType(), NumElems*SizeRatio);
23011   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23012
23013   // Convert Src0 value
23014   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
23015   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
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     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23024                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23025   }
23026   // Prepare the new mask
23027   SDValue NewMask;
23028   SDValue Mask = Mld->getMask();
23029   if (Mask.getValueType() == VT) {
23030     // Mask and original value have the same type
23031     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23032     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
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   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23059                                      Mld->getBasePtr(), NewMask, WideSrc0,
23060                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23061                                      ISD::NON_EXTLOAD);
23062   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23063   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23064
23065 }
23066 /// PerformMSTORECombine - Resolve truncating stores
23067 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23068                                     const X86Subtarget *Subtarget) {
23069   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23070   if (!Mst->isTruncatingStore())
23071     return SDValue();
23072
23073   EVT VT = Mst->getValue().getValueType();
23074   unsigned NumElems = VT.getVectorNumElements();
23075   EVT StVT = Mst->getMemoryVT();
23076   SDLoc dl(Mst);
23077
23078   assert(StVT != VT && "Cannot truncate to the same type");
23079   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23080   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23081
23082   // From, To sizes and ElemCount must be pow of two
23083   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23084     "Unexpected size for truncating masked store");
23085   // We are going to use the original vector elt for storing.
23086   // Accumulated smaller vector elements must be a multiple of the store size.
23087   assert (((NumElems * FromSz) % ToSz) == 0 &&
23088           "Unexpected ratio for truncating masked store");
23089
23090   unsigned SizeRatio  = FromSz / ToSz;
23091   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23092
23093   // Create a type on which we perform the shuffle
23094   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23095           StVT.getScalarType(), NumElems*SizeRatio);
23096
23097   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23098
23099   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23100   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23101   for (unsigned i = 0; i != NumElems; ++i)
23102     ShuffleVec[i] = i * SizeRatio;
23103
23104   // Can't shuffle using an illegal type.
23105   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23106           && "WideVecVT should be legal");
23107
23108   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23109                                         DAG.getUNDEF(WideVecVT),
23110                                         &ShuffleVec[0]);
23111
23112   SDValue NewMask;
23113   SDValue Mask = Mst->getMask();
23114   if (Mask.getValueType() == VT) {
23115     // Mask and original value have the same type
23116     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23117     for (unsigned i = 0; i != NumElems; ++i)
23118       ShuffleVec[i] = i * SizeRatio;
23119     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23120       ShuffleVec[i] = NumElems*SizeRatio;
23121     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23122                                    DAG.getConstant(0, dl, WideVecVT),
23123                                    &ShuffleVec[0]);
23124   }
23125   else {
23126     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23127     unsigned WidenNumElts = NumElems*SizeRatio;
23128     unsigned MaskNumElts = VT.getVectorNumElements();
23129     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23130                                      WidenNumElts);
23131
23132     unsigned NumConcat = WidenNumElts / MaskNumElts;
23133     SmallVector<SDValue, 16> Ops(NumConcat);
23134     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23135     Ops[0] = Mask;
23136     for (unsigned i = 1; i != NumConcat; ++i)
23137       Ops[i] = ZeroVal;
23138
23139     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23140   }
23141
23142   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23143                             NewMask, StVT, Mst->getMemOperand(), false);
23144 }
23145 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23146 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23147                                    const X86Subtarget *Subtarget) {
23148   StoreSDNode *St = cast<StoreSDNode>(N);
23149   EVT VT = St->getValue().getValueType();
23150   EVT StVT = St->getMemoryVT();
23151   SDLoc dl(St);
23152   SDValue StoredVal = St->getOperand(1);
23153   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23154
23155   // If we are saving a concatenation of two XMM registers and 32-byte stores
23156   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23157   unsigned Alignment = St->getAlignment();
23158   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23159   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23160       StVT == VT && !IsAligned) {
23161     unsigned NumElems = VT.getVectorNumElements();
23162     if (NumElems < 2)
23163       return SDValue();
23164
23165     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23166     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23167
23168     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23169     SDValue Ptr0 = St->getBasePtr();
23170     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23171
23172     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23173                                 St->getPointerInfo(), St->isVolatile(),
23174                                 St->isNonTemporal(), Alignment);
23175     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23176                                 St->getPointerInfo(), St->isVolatile(),
23177                                 St->isNonTemporal(),
23178                                 std::min(16U, Alignment));
23179     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23180   }
23181
23182   // Optimize trunc store (of multiple scalars) to shuffle and store.
23183   // First, pack all of the elements in one place. Next, store to memory
23184   // in fewer chunks.
23185   if (St->isTruncatingStore() && VT.isVector()) {
23186     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23187     unsigned NumElems = VT.getVectorNumElements();
23188     assert(StVT != VT && "Cannot truncate to the same type");
23189     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23190     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23191
23192     // From, To sizes and ElemCount must be pow of two
23193     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23194     // We are going to use the original vector elt for storing.
23195     // Accumulated smaller vector elements must be a multiple of the store size.
23196     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23197
23198     unsigned SizeRatio  = FromSz / ToSz;
23199
23200     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23201
23202     // Create a type on which we perform the shuffle
23203     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23204             StVT.getScalarType(), NumElems*SizeRatio);
23205
23206     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23207
23208     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23209     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23210     for (unsigned i = 0; i != NumElems; ++i)
23211       ShuffleVec[i] = i * SizeRatio;
23212
23213     // Can't shuffle using an illegal type.
23214     if (!TLI.isTypeLegal(WideVecVT))
23215       return SDValue();
23216
23217     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23218                                          DAG.getUNDEF(WideVecVT),
23219                                          &ShuffleVec[0]);
23220     // At this point all of the data is stored at the bottom of the
23221     // register. We now need to save it to mem.
23222
23223     // Find the largest store unit
23224     MVT StoreType = MVT::i8;
23225     for (MVT Tp : MVT::integer_valuetypes()) {
23226       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23227         StoreType = Tp;
23228     }
23229
23230     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23231     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23232         (64 <= NumElems * ToSz))
23233       StoreType = MVT::f64;
23234
23235     // Bitcast the original vector into a vector of store-size units
23236     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23237             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23238     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23239     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23240     SmallVector<SDValue, 8> Chains;
23241     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23242                                         TLI.getPointerTy());
23243     SDValue Ptr = St->getBasePtr();
23244
23245     // Perform one or more big stores into memory.
23246     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23247       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23248                                    StoreType, ShuffWide,
23249                                    DAG.getIntPtrConstant(i, dl));
23250       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23251                                 St->getPointerInfo(), St->isVolatile(),
23252                                 St->isNonTemporal(), St->getAlignment());
23253       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23254       Chains.push_back(Ch);
23255     }
23256
23257     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23258   }
23259
23260   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23261   // the FP state in cases where an emms may be missing.
23262   // A preferable solution to the general problem is to figure out the right
23263   // places to insert EMMS.  This qualifies as a quick hack.
23264
23265   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23266   if (VT.getSizeInBits() != 64)
23267     return SDValue();
23268
23269   const Function *F = DAG.getMachineFunction().getFunction();
23270   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23271   bool F64IsLegal =
23272       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23273   if ((VT.isVector() ||
23274        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23275       isa<LoadSDNode>(St->getValue()) &&
23276       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23277       St->getChain().hasOneUse() && !St->isVolatile()) {
23278     SDNode* LdVal = St->getValue().getNode();
23279     LoadSDNode *Ld = nullptr;
23280     int TokenFactorIndex = -1;
23281     SmallVector<SDValue, 8> Ops;
23282     SDNode* ChainVal = St->getChain().getNode();
23283     // Must be a store of a load.  We currently handle two cases:  the load
23284     // is a direct child, and it's under an intervening TokenFactor.  It is
23285     // possible to dig deeper under nested TokenFactors.
23286     if (ChainVal == LdVal)
23287       Ld = cast<LoadSDNode>(St->getChain());
23288     else if (St->getValue().hasOneUse() &&
23289              ChainVal->getOpcode() == ISD::TokenFactor) {
23290       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23291         if (ChainVal->getOperand(i).getNode() == LdVal) {
23292           TokenFactorIndex = i;
23293           Ld = cast<LoadSDNode>(St->getValue());
23294         } else
23295           Ops.push_back(ChainVal->getOperand(i));
23296       }
23297     }
23298
23299     if (!Ld || !ISD::isNormalLoad(Ld))
23300       return SDValue();
23301
23302     // If this is not the MMX case, i.e. we are just turning i64 load/store
23303     // into f64 load/store, avoid the transformation if there are multiple
23304     // uses of the loaded value.
23305     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23306       return SDValue();
23307
23308     SDLoc LdDL(Ld);
23309     SDLoc StDL(N);
23310     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23311     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23312     // pair instead.
23313     if (Subtarget->is64Bit() || F64IsLegal) {
23314       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23315       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23316                                   Ld->getPointerInfo(), Ld->isVolatile(),
23317                                   Ld->isNonTemporal(), Ld->isInvariant(),
23318                                   Ld->getAlignment());
23319       SDValue NewChain = NewLd.getValue(1);
23320       if (TokenFactorIndex != -1) {
23321         Ops.push_back(NewChain);
23322         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23323       }
23324       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23325                           St->getPointerInfo(),
23326                           St->isVolatile(), St->isNonTemporal(),
23327                           St->getAlignment());
23328     }
23329
23330     // Otherwise, lower to two pairs of 32-bit loads / stores.
23331     SDValue LoAddr = Ld->getBasePtr();
23332     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23333                                  DAG.getConstant(4, LdDL, MVT::i32));
23334
23335     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23336                                Ld->getPointerInfo(),
23337                                Ld->isVolatile(), Ld->isNonTemporal(),
23338                                Ld->isInvariant(), Ld->getAlignment());
23339     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23340                                Ld->getPointerInfo().getWithOffset(4),
23341                                Ld->isVolatile(), Ld->isNonTemporal(),
23342                                Ld->isInvariant(),
23343                                MinAlign(Ld->getAlignment(), 4));
23344
23345     SDValue NewChain = LoLd.getValue(1);
23346     if (TokenFactorIndex != -1) {
23347       Ops.push_back(LoLd);
23348       Ops.push_back(HiLd);
23349       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23350     }
23351
23352     LoAddr = St->getBasePtr();
23353     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23354                          DAG.getConstant(4, StDL, MVT::i32));
23355
23356     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23357                                 St->getPointerInfo(),
23358                                 St->isVolatile(), St->isNonTemporal(),
23359                                 St->getAlignment());
23360     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23361                                 St->getPointerInfo().getWithOffset(4),
23362                                 St->isVolatile(),
23363                                 St->isNonTemporal(),
23364                                 MinAlign(St->getAlignment(), 4));
23365     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23366   }
23367
23368   // This is similar to the above case, but here we handle a scalar 64-bit
23369   // integer store that is extracted from a vector on a 32-bit target.
23370   // If we have SSE2, then we can treat it like a floating-point double
23371   // to get past legalization. The execution dependencies fixup pass will
23372   // choose the optimal machine instruction for the store if this really is
23373   // an integer or v2f32 rather than an f64.
23374   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23375       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23376     SDValue OldExtract = St->getOperand(1);
23377     SDValue ExtOp0 = OldExtract.getOperand(0);
23378     unsigned VecSize = ExtOp0.getValueSizeInBits();
23379     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23380     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23381     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23382                                      BitCast, OldExtract.getOperand(1));
23383     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23384                         St->getPointerInfo(), St->isVolatile(),
23385                         St->isNonTemporal(), St->getAlignment());
23386   }
23387
23388   return SDValue();
23389 }
23390
23391 /// Return 'true' if this vector operation is "horizontal"
23392 /// and return the operands for the horizontal operation in LHS and RHS.  A
23393 /// horizontal operation performs the binary operation on successive elements
23394 /// of its first operand, then on successive elements of its second operand,
23395 /// returning the resulting values in a vector.  For example, if
23396 ///   A = < float a0, float a1, float a2, float a3 >
23397 /// and
23398 ///   B = < float b0, float b1, float b2, float b3 >
23399 /// then the result of doing a horizontal operation on A and B is
23400 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23401 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23402 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23403 /// set to A, RHS to B, and the routine returns 'true'.
23404 /// Note that the binary operation should have the property that if one of the
23405 /// operands is UNDEF then the result is UNDEF.
23406 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23407   // Look for the following pattern: if
23408   //   A = < float a0, float a1, float a2, float a3 >
23409   //   B = < float b0, float b1, float b2, float b3 >
23410   // and
23411   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23412   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23413   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23414   // which is A horizontal-op B.
23415
23416   // At least one of the operands should be a vector shuffle.
23417   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23418       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23419     return false;
23420
23421   MVT VT = LHS.getSimpleValueType();
23422
23423   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23424          "Unsupported vector type for horizontal add/sub");
23425
23426   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23427   // operate independently on 128-bit lanes.
23428   unsigned NumElts = VT.getVectorNumElements();
23429   unsigned NumLanes = VT.getSizeInBits()/128;
23430   unsigned NumLaneElts = NumElts / NumLanes;
23431   assert((NumLaneElts % 2 == 0) &&
23432          "Vector type should have an even number of elements in each lane");
23433   unsigned HalfLaneElts = NumLaneElts/2;
23434
23435   // View LHS in the form
23436   //   LHS = VECTOR_SHUFFLE A, B, LMask
23437   // If LHS is not a shuffle then pretend it is the shuffle
23438   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23439   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23440   // type VT.
23441   SDValue A, B;
23442   SmallVector<int, 16> LMask(NumElts);
23443   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23444     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23445       A = LHS.getOperand(0);
23446     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23447       B = LHS.getOperand(1);
23448     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23449     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23450   } else {
23451     if (LHS.getOpcode() != ISD::UNDEF)
23452       A = LHS;
23453     for (unsigned i = 0; i != NumElts; ++i)
23454       LMask[i] = i;
23455   }
23456
23457   // Likewise, view RHS in the form
23458   //   RHS = VECTOR_SHUFFLE C, D, RMask
23459   SDValue C, D;
23460   SmallVector<int, 16> RMask(NumElts);
23461   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23462     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23463       C = RHS.getOperand(0);
23464     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23465       D = RHS.getOperand(1);
23466     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23467     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23468   } else {
23469     if (RHS.getOpcode() != ISD::UNDEF)
23470       C = RHS;
23471     for (unsigned i = 0; i != NumElts; ++i)
23472       RMask[i] = i;
23473   }
23474
23475   // Check that the shuffles are both shuffling the same vectors.
23476   if (!(A == C && B == D) && !(A == D && B == C))
23477     return false;
23478
23479   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23480   if (!A.getNode() && !B.getNode())
23481     return false;
23482
23483   // If A and B occur in reverse order in RHS, then "swap" them (which means
23484   // rewriting the mask).
23485   if (A != C)
23486     ShuffleVectorSDNode::commuteMask(RMask);
23487
23488   // At this point LHS and RHS are equivalent to
23489   //   LHS = VECTOR_SHUFFLE A, B, LMask
23490   //   RHS = VECTOR_SHUFFLE A, B, RMask
23491   // Check that the masks correspond to performing a horizontal operation.
23492   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23493     for (unsigned i = 0; i != NumLaneElts; ++i) {
23494       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23495
23496       // Ignore any UNDEF components.
23497       if (LIdx < 0 || RIdx < 0 ||
23498           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23499           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23500         continue;
23501
23502       // Check that successive elements are being operated on.  If not, this is
23503       // not a horizontal operation.
23504       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23505       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23506       if (!(LIdx == Index && RIdx == Index + 1) &&
23507           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23508         return false;
23509     }
23510   }
23511
23512   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23513   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23514   return true;
23515 }
23516
23517 /// Do target-specific dag combines on floating point adds.
23518 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23519                                   const X86Subtarget *Subtarget) {
23520   EVT VT = N->getValueType(0);
23521   SDValue LHS = N->getOperand(0);
23522   SDValue RHS = N->getOperand(1);
23523
23524   // Try to synthesize horizontal adds from adds of shuffles.
23525   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23526        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23527       isHorizontalBinOp(LHS, RHS, true))
23528     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23529   return SDValue();
23530 }
23531
23532 /// Do target-specific dag combines on floating point subs.
23533 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23534                                   const X86Subtarget *Subtarget) {
23535   EVT VT = N->getValueType(0);
23536   SDValue LHS = N->getOperand(0);
23537   SDValue RHS = N->getOperand(1);
23538
23539   // Try to synthesize horizontal subs from subs of shuffles.
23540   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23541        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23542       isHorizontalBinOp(LHS, RHS, false))
23543     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23544   return SDValue();
23545 }
23546
23547 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23548 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23549   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23550
23551   // F[X]OR(0.0, x) -> x
23552   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23553     if (C->getValueAPF().isPosZero())
23554       return N->getOperand(1);
23555
23556   // F[X]OR(x, 0.0) -> x
23557   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23558     if (C->getValueAPF().isPosZero())
23559       return N->getOperand(0);
23560   return SDValue();
23561 }
23562
23563 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23564 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23565   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23566
23567   // Only perform optimizations if UnsafeMath is used.
23568   if (!DAG.getTarget().Options.UnsafeFPMath)
23569     return SDValue();
23570
23571   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23572   // into FMINC and FMAXC, which are Commutative operations.
23573   unsigned NewOp = 0;
23574   switch (N->getOpcode()) {
23575     default: llvm_unreachable("unknown opcode");
23576     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23577     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23578   }
23579
23580   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23581                      N->getOperand(0), N->getOperand(1));
23582 }
23583
23584 /// Do target-specific dag combines on X86ISD::FAND nodes.
23585 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23586   // FAND(0.0, x) -> 0.0
23587   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23588     if (C->getValueAPF().isPosZero())
23589       return N->getOperand(0);
23590
23591   // FAND(x, 0.0) -> 0.0
23592   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23593     if (C->getValueAPF().isPosZero())
23594       return N->getOperand(1);
23595
23596   return SDValue();
23597 }
23598
23599 /// Do target-specific dag combines on X86ISD::FANDN nodes
23600 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23601   // FANDN(0.0, x) -> x
23602   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23603     if (C->getValueAPF().isPosZero())
23604       return N->getOperand(1);
23605
23606   // FANDN(x, 0.0) -> 0.0
23607   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23608     if (C->getValueAPF().isPosZero())
23609       return N->getOperand(1);
23610
23611   return SDValue();
23612 }
23613
23614 static SDValue PerformBTCombine(SDNode *N,
23615                                 SelectionDAG &DAG,
23616                                 TargetLowering::DAGCombinerInfo &DCI) {
23617   // BT ignores high bits in the bit index operand.
23618   SDValue Op1 = N->getOperand(1);
23619   if (Op1.hasOneUse()) {
23620     unsigned BitWidth = Op1.getValueSizeInBits();
23621     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23622     APInt KnownZero, KnownOne;
23623     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23624                                           !DCI.isBeforeLegalizeOps());
23625     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23626     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23627         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23628       DCI.CommitTargetLoweringOpt(TLO);
23629   }
23630   return SDValue();
23631 }
23632
23633 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23634   SDValue Op = N->getOperand(0);
23635   if (Op.getOpcode() == ISD::BITCAST)
23636     Op = Op.getOperand(0);
23637   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23638   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23639       VT.getVectorElementType().getSizeInBits() ==
23640       OpVT.getVectorElementType().getSizeInBits()) {
23641     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23642   }
23643   return SDValue();
23644 }
23645
23646 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23647                                                const X86Subtarget *Subtarget) {
23648   EVT VT = N->getValueType(0);
23649   if (!VT.isVector())
23650     return SDValue();
23651
23652   SDValue N0 = N->getOperand(0);
23653   SDValue N1 = N->getOperand(1);
23654   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23655   SDLoc dl(N);
23656
23657   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23658   // both SSE and AVX2 since there is no sign-extended shift right
23659   // operation on a vector with 64-bit elements.
23660   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23661   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23662   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23663       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23664     SDValue N00 = N0.getOperand(0);
23665
23666     // EXTLOAD has a better solution on AVX2,
23667     // it may be replaced with X86ISD::VSEXT node.
23668     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23669       if (!ISD::isNormalLoad(N00.getNode()))
23670         return SDValue();
23671
23672     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23673         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23674                                   N00, N1);
23675       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23676     }
23677   }
23678   return SDValue();
23679 }
23680
23681 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23682                                   TargetLowering::DAGCombinerInfo &DCI,
23683                                   const X86Subtarget *Subtarget) {
23684   SDValue N0 = N->getOperand(0);
23685   EVT VT = N->getValueType(0);
23686   SDLoc dl(N);
23687
23688   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23689   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23690   // This exposes the sext to the sdivrem lowering, so that it directly extends
23691   // from AH (which we otherwise need to do contortions to access).
23692   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23693       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23694     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23695     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23696                             N0.getOperand(0), N0.getOperand(1));
23697     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23698     return R.getValue(1);
23699   }
23700
23701   if (!DCI.isBeforeLegalizeOps()) {
23702     if (N0.getValueType() == MVT::i1) {
23703       SDValue Zero = DAG.getConstant(0, dl, VT);
23704       SDValue AllOnes =
23705         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, VT);
23706       return DAG.getNode(ISD::SELECT, dl, VT, N0, AllOnes, Zero);
23707     }
23708     return SDValue();
23709   }
23710
23711   if (!Subtarget->hasFp256())
23712     return SDValue();
23713
23714   if (VT.isVector() && VT.getSizeInBits() == 256) {
23715     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23716     if (R.getNode())
23717       return R;
23718   }
23719
23720   return SDValue();
23721 }
23722
23723 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23724                                  const X86Subtarget* Subtarget) {
23725   SDLoc dl(N);
23726   EVT VT = N->getValueType(0);
23727
23728   // Let legalize expand this if it isn't a legal type yet.
23729   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23730     return SDValue();
23731
23732   EVT ScalarVT = VT.getScalarType();
23733   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23734       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23735     return SDValue();
23736
23737   SDValue A = N->getOperand(0);
23738   SDValue B = N->getOperand(1);
23739   SDValue C = N->getOperand(2);
23740
23741   bool NegA = (A.getOpcode() == ISD::FNEG);
23742   bool NegB = (B.getOpcode() == ISD::FNEG);
23743   bool NegC = (C.getOpcode() == ISD::FNEG);
23744
23745   // Negative multiplication when NegA xor NegB
23746   bool NegMul = (NegA != NegB);
23747   if (NegA)
23748     A = A.getOperand(0);
23749   if (NegB)
23750     B = B.getOperand(0);
23751   if (NegC)
23752     C = C.getOperand(0);
23753
23754   unsigned Opcode;
23755   if (!NegMul)
23756     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23757   else
23758     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23759
23760   return DAG.getNode(Opcode, dl, VT, A, B, C);
23761 }
23762
23763 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23764                                   TargetLowering::DAGCombinerInfo &DCI,
23765                                   const X86Subtarget *Subtarget) {
23766   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23767   //           (and (i32 x86isd::setcc_carry), 1)
23768   // This eliminates the zext. This transformation is necessary because
23769   // ISD::SETCC is always legalized to i8.
23770   SDLoc dl(N);
23771   SDValue N0 = N->getOperand(0);
23772   EVT VT = N->getValueType(0);
23773
23774   if (N0.getOpcode() == ISD::AND &&
23775       N0.hasOneUse() &&
23776       N0.getOperand(0).hasOneUse()) {
23777     SDValue N00 = N0.getOperand(0);
23778     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23779       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23780       if (!C || C->getZExtValue() != 1)
23781         return SDValue();
23782       return DAG.getNode(ISD::AND, dl, VT,
23783                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23784                                      N00.getOperand(0), N00.getOperand(1)),
23785                          DAG.getConstant(1, dl, VT));
23786     }
23787   }
23788
23789   if (N0.getOpcode() == ISD::TRUNCATE &&
23790       N0.hasOneUse() &&
23791       N0.getOperand(0).hasOneUse()) {
23792     SDValue N00 = N0.getOperand(0);
23793     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23794       return DAG.getNode(ISD::AND, dl, VT,
23795                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23796                                      N00.getOperand(0), N00.getOperand(1)),
23797                          DAG.getConstant(1, dl, VT));
23798     }
23799   }
23800   if (VT.is256BitVector()) {
23801     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23802     if (R.getNode())
23803       return R;
23804   }
23805
23806   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23807   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23808   // This exposes the zext to the udivrem lowering, so that it directly extends
23809   // from AH (which we otherwise need to do contortions to access).
23810   if (N0.getOpcode() == ISD::UDIVREM &&
23811       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23812       (VT == MVT::i32 || VT == MVT::i64)) {
23813     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23814     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23815                             N0.getOperand(0), N0.getOperand(1));
23816     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23817     return R.getValue(1);
23818   }
23819
23820   return SDValue();
23821 }
23822
23823 // Optimize x == -y --> x+y == 0
23824 //          x != -y --> x+y != 0
23825 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23826                                       const X86Subtarget* Subtarget) {
23827   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23828   SDValue LHS = N->getOperand(0);
23829   SDValue RHS = N->getOperand(1);
23830   EVT VT = N->getValueType(0);
23831   SDLoc DL(N);
23832
23833   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23834     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23835       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23836         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23837                                    LHS.getOperand(1));
23838         return DAG.getSetCC(DL, N->getValueType(0), addV,
23839                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23840       }
23841   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23842     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23843       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23844         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23845                                    RHS.getOperand(1));
23846         return DAG.getSetCC(DL, N->getValueType(0), addV,
23847                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23848       }
23849
23850   if (VT.getScalarType() == MVT::i1 &&
23851       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23852     bool IsSEXT0 =
23853         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23854         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23855     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23856
23857     if (!IsSEXT0 || !IsVZero1) {
23858       // Swap the operands and update the condition code.
23859       std::swap(LHS, RHS);
23860       CC = ISD::getSetCCSwappedOperands(CC);
23861
23862       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23863                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23864       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23865     }
23866
23867     if (IsSEXT0 && IsVZero1) {
23868       assert(VT == LHS.getOperand(0).getValueType() &&
23869              "Uexpected operand type");
23870       if (CC == ISD::SETGT)
23871         return DAG.getConstant(0, DL, VT);
23872       if (CC == ISD::SETLE)
23873         return DAG.getConstant(1, DL, VT);
23874       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23875         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23876
23877       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23878              "Unexpected condition code!");
23879       return LHS.getOperand(0);
23880     }
23881   }
23882
23883   return SDValue();
23884 }
23885
23886 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23887                                          SelectionDAG &DAG) {
23888   SDLoc dl(Load);
23889   MVT VT = Load->getSimpleValueType(0);
23890   MVT EVT = VT.getVectorElementType();
23891   SDValue Addr = Load->getOperand(1);
23892   SDValue NewAddr = DAG.getNode(
23893       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23894       DAG.getConstant(Index * EVT.getStoreSize(), dl,
23895                       Addr.getSimpleValueType()));
23896
23897   SDValue NewLoad =
23898       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23899                   DAG.getMachineFunction().getMachineMemOperand(
23900                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23901   return NewLoad;
23902 }
23903
23904 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23905                                       const X86Subtarget *Subtarget) {
23906   SDLoc dl(N);
23907   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23908   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23909          "X86insertps is only defined for v4x32");
23910
23911   SDValue Ld = N->getOperand(1);
23912   if (MayFoldLoad(Ld)) {
23913     // Extract the countS bits from the immediate so we can get the proper
23914     // address when narrowing the vector load to a specific element.
23915     // When the second source op is a memory address, insertps doesn't use
23916     // countS and just gets an f32 from that address.
23917     unsigned DestIndex =
23918         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23919
23920     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23921
23922     // Create this as a scalar to vector to match the instruction pattern.
23923     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23924     // countS bits are ignored when loading from memory on insertps, which
23925     // means we don't need to explicitly set them to 0.
23926     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23927                        LoadScalarToVector, N->getOperand(2));
23928   }
23929   return SDValue();
23930 }
23931
23932 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23933   SDValue V0 = N->getOperand(0);
23934   SDValue V1 = N->getOperand(1);
23935   SDLoc DL(N);
23936   EVT VT = N->getValueType(0);
23937
23938   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23939   // operands and changing the mask to 1. This saves us a bunch of
23940   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23941   // x86InstrInfo knows how to commute this back after instruction selection
23942   // if it would help register allocation.
23943
23944   // TODO: If optimizing for size or a processor that doesn't suffer from
23945   // partial register update stalls, this should be transformed into a MOVSD
23946   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23947
23948   if (VT == MVT::v2f64)
23949     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23950       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23951         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23952         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23953       }
23954
23955   return SDValue();
23956 }
23957
23958 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23959 // as "sbb reg,reg", since it can be extended without zext and produces
23960 // an all-ones bit which is more useful than 0/1 in some cases.
23961 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23962                                MVT VT) {
23963   if (VT == MVT::i8)
23964     return DAG.getNode(ISD::AND, DL, VT,
23965                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23966                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
23967                                    EFLAGS),
23968                        DAG.getConstant(1, DL, VT));
23969   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23970   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23971                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23972                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
23973                                  EFLAGS));
23974 }
23975
23976 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23977 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23978                                    TargetLowering::DAGCombinerInfo &DCI,
23979                                    const X86Subtarget *Subtarget) {
23980   SDLoc DL(N);
23981   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23982   SDValue EFLAGS = N->getOperand(1);
23983
23984   if (CC == X86::COND_A) {
23985     // Try to convert COND_A into COND_B in an attempt to facilitate
23986     // materializing "setb reg".
23987     //
23988     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23989     // cannot take an immediate as its first operand.
23990     //
23991     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23992         EFLAGS.getValueType().isInteger() &&
23993         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23994       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23995                                    EFLAGS.getNode()->getVTList(),
23996                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23997       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23998       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23999     }
24000   }
24001
24002   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24003   // a zext and produces an all-ones bit which is more useful than 0/1 in some
24004   // cases.
24005   if (CC == X86::COND_B)
24006     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24007
24008   SDValue Flags;
24009
24010   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24011   if (Flags.getNode()) {
24012     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24013     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24014   }
24015
24016   return SDValue();
24017 }
24018
24019 // Optimize branch condition evaluation.
24020 //
24021 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24022                                     TargetLowering::DAGCombinerInfo &DCI,
24023                                     const X86Subtarget *Subtarget) {
24024   SDLoc DL(N);
24025   SDValue Chain = N->getOperand(0);
24026   SDValue Dest = N->getOperand(1);
24027   SDValue EFLAGS = N->getOperand(3);
24028   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24029
24030   SDValue Flags;
24031
24032   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24033   if (Flags.getNode()) {
24034     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24035     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24036                        Flags);
24037   }
24038
24039   return SDValue();
24040 }
24041
24042 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24043                                                          SelectionDAG &DAG) {
24044   // Take advantage of vector comparisons producing 0 or -1 in each lane to
24045   // optimize away operation when it's from a constant.
24046   //
24047   // The general transformation is:
24048   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24049   //       AND(VECTOR_CMP(x,y), constant2)
24050   //    constant2 = UNARYOP(constant)
24051
24052   // Early exit if this isn't a vector operation, the operand of the
24053   // unary operation isn't a bitwise AND, or if the sizes of the operations
24054   // aren't the same.
24055   EVT VT = N->getValueType(0);
24056   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24057       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24058       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24059     return SDValue();
24060
24061   // Now check that the other operand of the AND is a constant. We could
24062   // make the transformation for non-constant splats as well, but it's unclear
24063   // that would be a benefit as it would not eliminate any operations, just
24064   // perform one more step in scalar code before moving to the vector unit.
24065   if (BuildVectorSDNode *BV =
24066           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24067     // Bail out if the vector isn't a constant.
24068     if (!BV->isConstant())
24069       return SDValue();
24070
24071     // Everything checks out. Build up the new and improved node.
24072     SDLoc DL(N);
24073     EVT IntVT = BV->getValueType(0);
24074     // Create a new constant of the appropriate type for the transformed
24075     // DAG.
24076     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24077     // The AND node needs bitcasts to/from an integer vector type around it.
24078     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24079     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24080                                  N->getOperand(0)->getOperand(0), MaskConst);
24081     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24082     return Res;
24083   }
24084
24085   return SDValue();
24086 }
24087
24088 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24089                                         const X86Subtarget *Subtarget) {
24090   // First try to optimize away the conversion entirely when it's
24091   // conditionally from a constant. Vectors only.
24092   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24093   if (Res != SDValue())
24094     return Res;
24095
24096   // Now move on to more general possibilities.
24097   SDValue Op0 = N->getOperand(0);
24098   EVT InVT = Op0->getValueType(0);
24099
24100   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24101   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24102     SDLoc dl(N);
24103     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24104     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24105     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24106   }
24107
24108   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24109   // a 32-bit target where SSE doesn't support i64->FP operations.
24110   if (Op0.getOpcode() == ISD::LOAD) {
24111     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24112     EVT VT = Ld->getValueType(0);
24113
24114     // This transformation is not supported if the result type is f16
24115     if (N->getValueType(0) == MVT::f16)
24116       return SDValue();
24117
24118     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24119         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24120         !Subtarget->is64Bit() && VT == MVT::i64) {
24121       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24122           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24123       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24124       return FILDChain;
24125     }
24126   }
24127   return SDValue();
24128 }
24129
24130 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24131 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24132                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24133   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24134   // the result is either zero or one (depending on the input carry bit).
24135   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24136   if (X86::isZeroNode(N->getOperand(0)) &&
24137       X86::isZeroNode(N->getOperand(1)) &&
24138       // We don't have a good way to replace an EFLAGS use, so only do this when
24139       // dead right now.
24140       SDValue(N, 1).use_empty()) {
24141     SDLoc DL(N);
24142     EVT VT = N->getValueType(0);
24143     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24144     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24145                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24146                                            DAG.getConstant(X86::COND_B, DL,
24147                                                            MVT::i8),
24148                                            N->getOperand(2)),
24149                                DAG.getConstant(1, DL, VT));
24150     return DCI.CombineTo(N, Res1, CarryOut);
24151   }
24152
24153   return SDValue();
24154 }
24155
24156 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24157 //      (add Y, (setne X, 0)) -> sbb -1, Y
24158 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24159 //      (sub (setne X, 0), Y) -> adc -1, Y
24160 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24161   SDLoc DL(N);
24162
24163   // Look through ZExts.
24164   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24165   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24166     return SDValue();
24167
24168   SDValue SetCC = Ext.getOperand(0);
24169   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24170     return SDValue();
24171
24172   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24173   if (CC != X86::COND_E && CC != X86::COND_NE)
24174     return SDValue();
24175
24176   SDValue Cmp = SetCC.getOperand(1);
24177   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24178       !X86::isZeroNode(Cmp.getOperand(1)) ||
24179       !Cmp.getOperand(0).getValueType().isInteger())
24180     return SDValue();
24181
24182   SDValue CmpOp0 = Cmp.getOperand(0);
24183   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24184                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24185
24186   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24187   if (CC == X86::COND_NE)
24188     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24189                        DL, OtherVal.getValueType(), OtherVal,
24190                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24191                        NewCmp);
24192   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24193                      DL, OtherVal.getValueType(), OtherVal,
24194                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24195 }
24196
24197 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24198 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24199                                  const X86Subtarget *Subtarget) {
24200   EVT VT = N->getValueType(0);
24201   SDValue Op0 = N->getOperand(0);
24202   SDValue Op1 = N->getOperand(1);
24203
24204   // Try to synthesize horizontal adds from adds of shuffles.
24205   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24206        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24207       isHorizontalBinOp(Op0, Op1, true))
24208     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24209
24210   return OptimizeConditionalInDecrement(N, DAG);
24211 }
24212
24213 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24214                                  const X86Subtarget *Subtarget) {
24215   SDValue Op0 = N->getOperand(0);
24216   SDValue Op1 = N->getOperand(1);
24217
24218   // X86 can't encode an immediate LHS of a sub. See if we can push the
24219   // negation into a preceding instruction.
24220   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24221     // If the RHS of the sub is a XOR with one use and a constant, invert the
24222     // immediate. Then add one to the LHS of the sub so we can turn
24223     // X-Y -> X+~Y+1, saving one register.
24224     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24225         isa<ConstantSDNode>(Op1.getOperand(1))) {
24226       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24227       EVT VT = Op0.getValueType();
24228       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24229                                    Op1.getOperand(0),
24230                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24231       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24232                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24233     }
24234   }
24235
24236   // Try to synthesize horizontal adds from adds of shuffles.
24237   EVT VT = N->getValueType(0);
24238   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24239        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24240       isHorizontalBinOp(Op0, Op1, true))
24241     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24242
24243   return OptimizeConditionalInDecrement(N, DAG);
24244 }
24245
24246 /// performVZEXTCombine - Performs build vector combines
24247 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24248                                    TargetLowering::DAGCombinerInfo &DCI,
24249                                    const X86Subtarget *Subtarget) {
24250   SDLoc DL(N);
24251   MVT VT = N->getSimpleValueType(0);
24252   SDValue Op = N->getOperand(0);
24253   MVT OpVT = Op.getSimpleValueType();
24254   MVT OpEltVT = OpVT.getVectorElementType();
24255   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24256
24257   // (vzext (bitcast (vzext (x)) -> (vzext x)
24258   SDValue V = Op;
24259   while (V.getOpcode() == ISD::BITCAST)
24260     V = V.getOperand(0);
24261
24262   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24263     MVT InnerVT = V.getSimpleValueType();
24264     MVT InnerEltVT = InnerVT.getVectorElementType();
24265
24266     // If the element sizes match exactly, we can just do one larger vzext. This
24267     // is always an exact type match as vzext operates on integer types.
24268     if (OpEltVT == InnerEltVT) {
24269       assert(OpVT == InnerVT && "Types must match for vzext!");
24270       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24271     }
24272
24273     // The only other way we can combine them is if only a single element of the
24274     // inner vzext is used in the input to the outer vzext.
24275     if (InnerEltVT.getSizeInBits() < InputBits)
24276       return SDValue();
24277
24278     // In this case, the inner vzext is completely dead because we're going to
24279     // only look at bits inside of the low element. Just do the outer vzext on
24280     // a bitcast of the input to the inner.
24281     return DAG.getNode(X86ISD::VZEXT, DL, VT,
24282                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24283   }
24284
24285   // Check if we can bypass extracting and re-inserting an element of an input
24286   // vector. Essentialy:
24287   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24288   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24289       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24290       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24291     SDValue ExtractedV = V.getOperand(0);
24292     SDValue OrigV = ExtractedV.getOperand(0);
24293     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24294       if (ExtractIdx->getZExtValue() == 0) {
24295         MVT OrigVT = OrigV.getSimpleValueType();
24296         // Extract a subvector if necessary...
24297         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24298           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24299           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24300                                     OrigVT.getVectorNumElements() / Ratio);
24301           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24302                               DAG.getIntPtrConstant(0, DL));
24303         }
24304         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24305         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24306       }
24307   }
24308
24309   return SDValue();
24310 }
24311
24312 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24313                                              DAGCombinerInfo &DCI) const {
24314   SelectionDAG &DAG = DCI.DAG;
24315   switch (N->getOpcode()) {
24316   default: break;
24317   case ISD::EXTRACT_VECTOR_ELT:
24318     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24319   case ISD::VSELECT:
24320   case ISD::SELECT:
24321   case X86ISD::SHRUNKBLEND:
24322     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24323   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24324   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24325   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24326   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24327   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24328   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24329   case ISD::SHL:
24330   case ISD::SRA:
24331   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24332   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24333   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24334   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24335   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24336   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24337   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24338   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24339   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24340   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24341   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24342   case X86ISD::FXOR:
24343   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24344   case X86ISD::FMIN:
24345   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24346   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24347   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24348   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24349   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24350   case ISD::ANY_EXTEND:
24351   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24352   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24353   case ISD::SIGN_EXTEND_INREG:
24354     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24355   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24356   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24357   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24358   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24359   case X86ISD::SHUFP:       // Handle all target specific shuffles
24360   case X86ISD::PALIGNR:
24361   case X86ISD::UNPCKH:
24362   case X86ISD::UNPCKL:
24363   case X86ISD::MOVHLPS:
24364   case X86ISD::MOVLHPS:
24365   case X86ISD::PSHUFB:
24366   case X86ISD::PSHUFD:
24367   case X86ISD::PSHUFHW:
24368   case X86ISD::PSHUFLW:
24369   case X86ISD::MOVSS:
24370   case X86ISD::MOVSD:
24371   case X86ISD::VPERMILPI:
24372   case X86ISD::VPERM2X128:
24373   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24374   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24375   case ISD::INTRINSIC_WO_CHAIN:
24376     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24377   case X86ISD::INSERTPS: {
24378     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24379       return PerformINSERTPSCombine(N, DAG, Subtarget);
24380     break;
24381   }
24382   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24383   }
24384
24385   return SDValue();
24386 }
24387
24388 /// isTypeDesirableForOp - Return true if the target has native support for
24389 /// the specified value type and it is 'desirable' to use the type for the
24390 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24391 /// instruction encodings are longer and some i16 instructions are slow.
24392 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24393   if (!isTypeLegal(VT))
24394     return false;
24395   if (VT != MVT::i16)
24396     return true;
24397
24398   switch (Opc) {
24399   default:
24400     return true;
24401   case ISD::LOAD:
24402   case ISD::SIGN_EXTEND:
24403   case ISD::ZERO_EXTEND:
24404   case ISD::ANY_EXTEND:
24405   case ISD::SHL:
24406   case ISD::SRL:
24407   case ISD::SUB:
24408   case ISD::ADD:
24409   case ISD::MUL:
24410   case ISD::AND:
24411   case ISD::OR:
24412   case ISD::XOR:
24413     return false;
24414   }
24415 }
24416
24417 /// IsDesirableToPromoteOp - This method query the target whether it is
24418 /// beneficial for dag combiner to promote the specified node. If true, it
24419 /// should return the desired promotion type by reference.
24420 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24421   EVT VT = Op.getValueType();
24422   if (VT != MVT::i16)
24423     return false;
24424
24425   bool Promote = false;
24426   bool Commute = false;
24427   switch (Op.getOpcode()) {
24428   default: break;
24429   case ISD::LOAD: {
24430     LoadSDNode *LD = cast<LoadSDNode>(Op);
24431     // If the non-extending load has a single use and it's not live out, then it
24432     // might be folded.
24433     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24434                                                      Op.hasOneUse()*/) {
24435       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24436              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24437         // The only case where we'd want to promote LOAD (rather then it being
24438         // promoted as an operand is when it's only use is liveout.
24439         if (UI->getOpcode() != ISD::CopyToReg)
24440           return false;
24441       }
24442     }
24443     Promote = true;
24444     break;
24445   }
24446   case ISD::SIGN_EXTEND:
24447   case ISD::ZERO_EXTEND:
24448   case ISD::ANY_EXTEND:
24449     Promote = true;
24450     break;
24451   case ISD::SHL:
24452   case ISD::SRL: {
24453     SDValue N0 = Op.getOperand(0);
24454     // Look out for (store (shl (load), x)).
24455     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24456       return false;
24457     Promote = true;
24458     break;
24459   }
24460   case ISD::ADD:
24461   case ISD::MUL:
24462   case ISD::AND:
24463   case ISD::OR:
24464   case ISD::XOR:
24465     Commute = true;
24466     // fallthrough
24467   case ISD::SUB: {
24468     SDValue N0 = Op.getOperand(0);
24469     SDValue N1 = Op.getOperand(1);
24470     if (!Commute && MayFoldLoad(N1))
24471       return false;
24472     // Avoid disabling potential load folding opportunities.
24473     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24474       return false;
24475     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24476       return false;
24477     Promote = true;
24478   }
24479   }
24480
24481   PVT = MVT::i32;
24482   return Promote;
24483 }
24484
24485 //===----------------------------------------------------------------------===//
24486 //                           X86 Inline Assembly Support
24487 //===----------------------------------------------------------------------===//
24488
24489 // Helper to match a string separated by whitespace.
24490 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24491   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24492
24493   for (StringRef Piece : Pieces) {
24494     if (!S.startswith(Piece)) // Check if the piece matches.
24495       return false;
24496
24497     S = S.substr(Piece.size());
24498     StringRef::size_type Pos = S.find_first_not_of(" \t");
24499     if (Pos == 0) // We matched a prefix.
24500       return false;
24501
24502     S = S.substr(Pos);
24503   }
24504
24505   return S.empty();
24506 }
24507
24508 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24509
24510   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24511     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24512         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24513         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24514
24515       if (AsmPieces.size() == 3)
24516         return true;
24517       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24518         return true;
24519     }
24520   }
24521   return false;
24522 }
24523
24524 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24525   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24526
24527   std::string AsmStr = IA->getAsmString();
24528
24529   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24530   if (!Ty || Ty->getBitWidth() % 16 != 0)
24531     return false;
24532
24533   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24534   SmallVector<StringRef, 4> AsmPieces;
24535   SplitString(AsmStr, AsmPieces, ";\n");
24536
24537   switch (AsmPieces.size()) {
24538   default: return false;
24539   case 1:
24540     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24541     // we will turn this bswap into something that will be lowered to logical
24542     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24543     // lower so don't worry about this.
24544     // bswap $0
24545     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24546         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24547         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24548         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24549         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24550         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24551       // No need to check constraints, nothing other than the equivalent of
24552       // "=r,0" would be valid here.
24553       return IntrinsicLowering::LowerToByteSwap(CI);
24554     }
24555
24556     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24557     if (CI->getType()->isIntegerTy(16) &&
24558         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24559         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24560          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24561       AsmPieces.clear();
24562       const std::string &ConstraintsStr = IA->getConstraintString();
24563       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24564       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24565       if (clobbersFlagRegisters(AsmPieces))
24566         return IntrinsicLowering::LowerToByteSwap(CI);
24567     }
24568     break;
24569   case 3:
24570     if (CI->getType()->isIntegerTy(32) &&
24571         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24572         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24573         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24574         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24575       AsmPieces.clear();
24576       const std::string &ConstraintsStr = IA->getConstraintString();
24577       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24578       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24579       if (clobbersFlagRegisters(AsmPieces))
24580         return IntrinsicLowering::LowerToByteSwap(CI);
24581     }
24582
24583     if (CI->getType()->isIntegerTy(64)) {
24584       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24585       if (Constraints.size() >= 2 &&
24586           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24587           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24588         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24589         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24590             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24591             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24592           return IntrinsicLowering::LowerToByteSwap(CI);
24593       }
24594     }
24595     break;
24596   }
24597   return false;
24598 }
24599
24600 /// getConstraintType - Given a constraint letter, return the type of
24601 /// constraint it is for this target.
24602 X86TargetLowering::ConstraintType
24603 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24604   if (Constraint.size() == 1) {
24605     switch (Constraint[0]) {
24606     case 'R':
24607     case 'q':
24608     case 'Q':
24609     case 'f':
24610     case 't':
24611     case 'u':
24612     case 'y':
24613     case 'x':
24614     case 'Y':
24615     case 'l':
24616       return C_RegisterClass;
24617     case 'a':
24618     case 'b':
24619     case 'c':
24620     case 'd':
24621     case 'S':
24622     case 'D':
24623     case 'A':
24624       return C_Register;
24625     case 'I':
24626     case 'J':
24627     case 'K':
24628     case 'L':
24629     case 'M':
24630     case 'N':
24631     case 'G':
24632     case 'C':
24633     case 'e':
24634     case 'Z':
24635       return C_Other;
24636     default:
24637       break;
24638     }
24639   }
24640   return TargetLowering::getConstraintType(Constraint);
24641 }
24642
24643 /// Examine constraint type and operand type and determine a weight value.
24644 /// This object must already have been set up with the operand type
24645 /// and the current alternative constraint selected.
24646 TargetLowering::ConstraintWeight
24647   X86TargetLowering::getSingleConstraintMatchWeight(
24648     AsmOperandInfo &info, const char *constraint) const {
24649   ConstraintWeight weight = CW_Invalid;
24650   Value *CallOperandVal = info.CallOperandVal;
24651     // If we don't have a value, we can't do a match,
24652     // but allow it at the lowest weight.
24653   if (!CallOperandVal)
24654     return CW_Default;
24655   Type *type = CallOperandVal->getType();
24656   // Look at the constraint type.
24657   switch (*constraint) {
24658   default:
24659     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24660   case 'R':
24661   case 'q':
24662   case 'Q':
24663   case 'a':
24664   case 'b':
24665   case 'c':
24666   case 'd':
24667   case 'S':
24668   case 'D':
24669   case 'A':
24670     if (CallOperandVal->getType()->isIntegerTy())
24671       weight = CW_SpecificReg;
24672     break;
24673   case 'f':
24674   case 't':
24675   case 'u':
24676     if (type->isFloatingPointTy())
24677       weight = CW_SpecificReg;
24678     break;
24679   case 'y':
24680     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24681       weight = CW_SpecificReg;
24682     break;
24683   case 'x':
24684   case 'Y':
24685     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24686         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24687       weight = CW_Register;
24688     break;
24689   case 'I':
24690     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24691       if (C->getZExtValue() <= 31)
24692         weight = CW_Constant;
24693     }
24694     break;
24695   case 'J':
24696     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24697       if (C->getZExtValue() <= 63)
24698         weight = CW_Constant;
24699     }
24700     break;
24701   case 'K':
24702     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24703       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24704         weight = CW_Constant;
24705     }
24706     break;
24707   case 'L':
24708     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24709       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24710         weight = CW_Constant;
24711     }
24712     break;
24713   case 'M':
24714     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24715       if (C->getZExtValue() <= 3)
24716         weight = CW_Constant;
24717     }
24718     break;
24719   case 'N':
24720     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24721       if (C->getZExtValue() <= 0xff)
24722         weight = CW_Constant;
24723     }
24724     break;
24725   case 'G':
24726   case 'C':
24727     if (isa<ConstantFP>(CallOperandVal)) {
24728       weight = CW_Constant;
24729     }
24730     break;
24731   case 'e':
24732     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24733       if ((C->getSExtValue() >= -0x80000000LL) &&
24734           (C->getSExtValue() <= 0x7fffffffLL))
24735         weight = CW_Constant;
24736     }
24737     break;
24738   case 'Z':
24739     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24740       if (C->getZExtValue() <= 0xffffffff)
24741         weight = CW_Constant;
24742     }
24743     break;
24744   }
24745   return weight;
24746 }
24747
24748 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24749 /// with another that has more specific requirements based on the type of the
24750 /// corresponding operand.
24751 const char *X86TargetLowering::
24752 LowerXConstraint(EVT ConstraintVT) const {
24753   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24754   // 'f' like normal targets.
24755   if (ConstraintVT.isFloatingPoint()) {
24756     if (Subtarget->hasSSE2())
24757       return "Y";
24758     if (Subtarget->hasSSE1())
24759       return "x";
24760   }
24761
24762   return TargetLowering::LowerXConstraint(ConstraintVT);
24763 }
24764
24765 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24766 /// vector.  If it is invalid, don't add anything to Ops.
24767 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24768                                                      std::string &Constraint,
24769                                                      std::vector<SDValue>&Ops,
24770                                                      SelectionDAG &DAG) const {
24771   SDValue Result;
24772
24773   // Only support length 1 constraints for now.
24774   if (Constraint.length() > 1) return;
24775
24776   char ConstraintLetter = Constraint[0];
24777   switch (ConstraintLetter) {
24778   default: break;
24779   case 'I':
24780     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24781       if (C->getZExtValue() <= 31) {
24782         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24783                                        Op.getValueType());
24784         break;
24785       }
24786     }
24787     return;
24788   case 'J':
24789     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24790       if (C->getZExtValue() <= 63) {
24791         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24792                                        Op.getValueType());
24793         break;
24794       }
24795     }
24796     return;
24797   case 'K':
24798     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24799       if (isInt<8>(C->getSExtValue())) {
24800         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24801                                        Op.getValueType());
24802         break;
24803       }
24804     }
24805     return;
24806   case 'L':
24807     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24808       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24809           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24810         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24811                                        Op.getValueType());
24812         break;
24813       }
24814     }
24815     return;
24816   case 'M':
24817     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24818       if (C->getZExtValue() <= 3) {
24819         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24820                                        Op.getValueType());
24821         break;
24822       }
24823     }
24824     return;
24825   case 'N':
24826     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24827       if (C->getZExtValue() <= 255) {
24828         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24829                                        Op.getValueType());
24830         break;
24831       }
24832     }
24833     return;
24834   case 'O':
24835     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24836       if (C->getZExtValue() <= 127) {
24837         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24838                                        Op.getValueType());
24839         break;
24840       }
24841     }
24842     return;
24843   case 'e': {
24844     // 32-bit signed value
24845     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24846       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24847                                            C->getSExtValue())) {
24848         // Widen to 64 bits here to get it sign extended.
24849         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24850         break;
24851       }
24852     // FIXME gcc accepts some relocatable values here too, but only in certain
24853     // memory models; it's complicated.
24854     }
24855     return;
24856   }
24857   case 'Z': {
24858     // 32-bit unsigned value
24859     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24860       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24861                                            C->getZExtValue())) {
24862         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24863                                        Op.getValueType());
24864         break;
24865       }
24866     }
24867     // FIXME gcc accepts some relocatable values here too, but only in certain
24868     // memory models; it's complicated.
24869     return;
24870   }
24871   case 'i': {
24872     // Literal immediates are always ok.
24873     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24874       // Widen to 64 bits here to get it sign extended.
24875       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24876       break;
24877     }
24878
24879     // In any sort of PIC mode addresses need to be computed at runtime by
24880     // adding in a register or some sort of table lookup.  These can't
24881     // be used as immediates.
24882     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24883       return;
24884
24885     // If we are in non-pic codegen mode, we allow the address of a global (with
24886     // an optional displacement) to be used with 'i'.
24887     GlobalAddressSDNode *GA = nullptr;
24888     int64_t Offset = 0;
24889
24890     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24891     while (1) {
24892       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24893         Offset += GA->getOffset();
24894         break;
24895       } else if (Op.getOpcode() == ISD::ADD) {
24896         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24897           Offset += C->getZExtValue();
24898           Op = Op.getOperand(0);
24899           continue;
24900         }
24901       } else if (Op.getOpcode() == ISD::SUB) {
24902         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24903           Offset += -C->getZExtValue();
24904           Op = Op.getOperand(0);
24905           continue;
24906         }
24907       }
24908
24909       // Otherwise, this isn't something we can handle, reject it.
24910       return;
24911     }
24912
24913     const GlobalValue *GV = GA->getGlobal();
24914     // If we require an extra load to get this address, as in PIC mode, we
24915     // can't accept it.
24916     if (isGlobalStubReference(
24917             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24918       return;
24919
24920     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24921                                         GA->getValueType(0), Offset);
24922     break;
24923   }
24924   }
24925
24926   if (Result.getNode()) {
24927     Ops.push_back(Result);
24928     return;
24929   }
24930   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24931 }
24932
24933 std::pair<unsigned, const TargetRegisterClass *>
24934 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24935                                                 const std::string &Constraint,
24936                                                 MVT VT) const {
24937   // First, see if this is a constraint that directly corresponds to an LLVM
24938   // register class.
24939   if (Constraint.size() == 1) {
24940     // GCC Constraint Letters
24941     switch (Constraint[0]) {
24942     default: break;
24943       // TODO: Slight differences here in allocation order and leaving
24944       // RIP in the class. Do they matter any more here than they do
24945       // in the normal allocation?
24946     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24947       if (Subtarget->is64Bit()) {
24948         if (VT == MVT::i32 || VT == MVT::f32)
24949           return std::make_pair(0U, &X86::GR32RegClass);
24950         if (VT == MVT::i16)
24951           return std::make_pair(0U, &X86::GR16RegClass);
24952         if (VT == MVT::i8 || VT == MVT::i1)
24953           return std::make_pair(0U, &X86::GR8RegClass);
24954         if (VT == MVT::i64 || VT == MVT::f64)
24955           return std::make_pair(0U, &X86::GR64RegClass);
24956         break;
24957       }
24958       // 32-bit fallthrough
24959     case 'Q':   // Q_REGS
24960       if (VT == MVT::i32 || VT == MVT::f32)
24961         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24962       if (VT == MVT::i16)
24963         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24964       if (VT == MVT::i8 || VT == MVT::i1)
24965         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24966       if (VT == MVT::i64)
24967         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24968       break;
24969     case 'r':   // GENERAL_REGS
24970     case 'l':   // INDEX_REGS
24971       if (VT == MVT::i8 || VT == MVT::i1)
24972         return std::make_pair(0U, &X86::GR8RegClass);
24973       if (VT == MVT::i16)
24974         return std::make_pair(0U, &X86::GR16RegClass);
24975       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24976         return std::make_pair(0U, &X86::GR32RegClass);
24977       return std::make_pair(0U, &X86::GR64RegClass);
24978     case 'R':   // LEGACY_REGS
24979       if (VT == MVT::i8 || VT == MVT::i1)
24980         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24981       if (VT == MVT::i16)
24982         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24983       if (VT == MVT::i32 || !Subtarget->is64Bit())
24984         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24985       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24986     case 'f':  // FP Stack registers.
24987       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24988       // value to the correct fpstack register class.
24989       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24990         return std::make_pair(0U, &X86::RFP32RegClass);
24991       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24992         return std::make_pair(0U, &X86::RFP64RegClass);
24993       return std::make_pair(0U, &X86::RFP80RegClass);
24994     case 'y':   // MMX_REGS if MMX allowed.
24995       if (!Subtarget->hasMMX()) break;
24996       return std::make_pair(0U, &X86::VR64RegClass);
24997     case 'Y':   // SSE_REGS if SSE2 allowed
24998       if (!Subtarget->hasSSE2()) break;
24999       // FALL THROUGH.
25000     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25001       if (!Subtarget->hasSSE1()) break;
25002
25003       switch (VT.SimpleTy) {
25004       default: break;
25005       // Scalar SSE types.
25006       case MVT::f32:
25007       case MVT::i32:
25008         return std::make_pair(0U, &X86::FR32RegClass);
25009       case MVT::f64:
25010       case MVT::i64:
25011         return std::make_pair(0U, &X86::FR64RegClass);
25012       // Vector types.
25013       case MVT::v16i8:
25014       case MVT::v8i16:
25015       case MVT::v4i32:
25016       case MVT::v2i64:
25017       case MVT::v4f32:
25018       case MVT::v2f64:
25019         return std::make_pair(0U, &X86::VR128RegClass);
25020       // AVX types.
25021       case MVT::v32i8:
25022       case MVT::v16i16:
25023       case MVT::v8i32:
25024       case MVT::v4i64:
25025       case MVT::v8f32:
25026       case MVT::v4f64:
25027         return std::make_pair(0U, &X86::VR256RegClass);
25028       case MVT::v8f64:
25029       case MVT::v16f32:
25030       case MVT::v16i32:
25031       case MVT::v8i64:
25032         return std::make_pair(0U, &X86::VR512RegClass);
25033       }
25034       break;
25035     }
25036   }
25037
25038   // Use the default implementation in TargetLowering to convert the register
25039   // constraint into a member of a register class.
25040   std::pair<unsigned, const TargetRegisterClass*> Res;
25041   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25042
25043   // Not found as a standard register?
25044   if (!Res.second) {
25045     // Map st(0) -> st(7) -> ST0
25046     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25047         tolower(Constraint[1]) == 's' &&
25048         tolower(Constraint[2]) == 't' &&
25049         Constraint[3] == '(' &&
25050         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25051         Constraint[5] == ')' &&
25052         Constraint[6] == '}') {
25053
25054       Res.first = X86::FP0+Constraint[4]-'0';
25055       Res.second = &X86::RFP80RegClass;
25056       return Res;
25057     }
25058
25059     // GCC allows "st(0)" to be called just plain "st".
25060     if (StringRef("{st}").equals_lower(Constraint)) {
25061       Res.first = X86::FP0;
25062       Res.second = &X86::RFP80RegClass;
25063       return Res;
25064     }
25065
25066     // flags -> EFLAGS
25067     if (StringRef("{flags}").equals_lower(Constraint)) {
25068       Res.first = X86::EFLAGS;
25069       Res.second = &X86::CCRRegClass;
25070       return Res;
25071     }
25072
25073     // 'A' means EAX + EDX.
25074     if (Constraint == "A") {
25075       Res.first = X86::EAX;
25076       Res.second = &X86::GR32_ADRegClass;
25077       return Res;
25078     }
25079     return Res;
25080   }
25081
25082   // Otherwise, check to see if this is a register class of the wrong value
25083   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25084   // turn into {ax},{dx}.
25085   if (Res.second->hasType(VT))
25086     return Res;   // Correct type already, nothing to do.
25087
25088   // All of the single-register GCC register classes map their values onto
25089   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
25090   // really want an 8-bit or 32-bit register, map to the appropriate register
25091   // class and return the appropriate register.
25092   if (Res.second == &X86::GR16RegClass) {
25093     if (VT == MVT::i8 || VT == MVT::i1) {
25094       unsigned DestReg = 0;
25095       switch (Res.first) {
25096       default: break;
25097       case X86::AX: DestReg = X86::AL; break;
25098       case X86::DX: DestReg = X86::DL; break;
25099       case X86::CX: DestReg = X86::CL; break;
25100       case X86::BX: DestReg = X86::BL; break;
25101       }
25102       if (DestReg) {
25103         Res.first = DestReg;
25104         Res.second = &X86::GR8RegClass;
25105       }
25106     } else if (VT == MVT::i32 || VT == MVT::f32) {
25107       unsigned DestReg = 0;
25108       switch (Res.first) {
25109       default: break;
25110       case X86::AX: DestReg = X86::EAX; break;
25111       case X86::DX: DestReg = X86::EDX; break;
25112       case X86::CX: DestReg = X86::ECX; break;
25113       case X86::BX: DestReg = X86::EBX; break;
25114       case X86::SI: DestReg = X86::ESI; break;
25115       case X86::DI: DestReg = X86::EDI; break;
25116       case X86::BP: DestReg = X86::EBP; break;
25117       case X86::SP: DestReg = X86::ESP; break;
25118       }
25119       if (DestReg) {
25120         Res.first = DestReg;
25121         Res.second = &X86::GR32RegClass;
25122       }
25123     } else if (VT == MVT::i64 || VT == MVT::f64) {
25124       unsigned DestReg = 0;
25125       switch (Res.first) {
25126       default: break;
25127       case X86::AX: DestReg = X86::RAX; break;
25128       case X86::DX: DestReg = X86::RDX; break;
25129       case X86::CX: DestReg = X86::RCX; break;
25130       case X86::BX: DestReg = X86::RBX; break;
25131       case X86::SI: DestReg = X86::RSI; break;
25132       case X86::DI: DestReg = X86::RDI; break;
25133       case X86::BP: DestReg = X86::RBP; break;
25134       case X86::SP: DestReg = X86::RSP; break;
25135       }
25136       if (DestReg) {
25137         Res.first = DestReg;
25138         Res.second = &X86::GR64RegClass;
25139       }
25140     }
25141   } else if (Res.second == &X86::FR32RegClass ||
25142              Res.second == &X86::FR64RegClass ||
25143              Res.second == &X86::VR128RegClass ||
25144              Res.second == &X86::VR256RegClass ||
25145              Res.second == &X86::FR32XRegClass ||
25146              Res.second == &X86::FR64XRegClass ||
25147              Res.second == &X86::VR128XRegClass ||
25148              Res.second == &X86::VR256XRegClass ||
25149              Res.second == &X86::VR512RegClass) {
25150     // Handle references to XMM physical registers that got mapped into the
25151     // wrong class.  This can happen with constraints like {xmm0} where the
25152     // target independent register mapper will just pick the first match it can
25153     // find, ignoring the required type.
25154
25155     if (VT == MVT::f32 || VT == MVT::i32)
25156       Res.second = &X86::FR32RegClass;
25157     else if (VT == MVT::f64 || VT == MVT::i64)
25158       Res.second = &X86::FR64RegClass;
25159     else if (X86::VR128RegClass.hasType(VT))
25160       Res.second = &X86::VR128RegClass;
25161     else if (X86::VR256RegClass.hasType(VT))
25162       Res.second = &X86::VR256RegClass;
25163     else if (X86::VR512RegClass.hasType(VT))
25164       Res.second = &X86::VR512RegClass;
25165   }
25166
25167   return Res;
25168 }
25169
25170 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25171                                             Type *Ty) const {
25172   // Scaling factors are not free at all.
25173   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25174   // will take 2 allocations in the out of order engine instead of 1
25175   // for plain addressing mode, i.e. inst (reg1).
25176   // E.g.,
25177   // vaddps (%rsi,%drx), %ymm0, %ymm1
25178   // Requires two allocations (one for the load, one for the computation)
25179   // whereas:
25180   // vaddps (%rsi), %ymm0, %ymm1
25181   // Requires just 1 allocation, i.e., freeing allocations for other operations
25182   // and having less micro operations to execute.
25183   //
25184   // For some X86 architectures, this is even worse because for instance for
25185   // stores, the complex addressing mode forces the instruction to use the
25186   // "load" ports instead of the dedicated "store" port.
25187   // E.g., on Haswell:
25188   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25189   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25190   if (isLegalAddressingMode(AM, Ty))
25191     // Scale represents reg2 * scale, thus account for 1
25192     // as soon as we use a second register.
25193     return AM.Scale != 0;
25194   return -1;
25195 }
25196
25197 bool X86TargetLowering::isTargetFTOL() const {
25198   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25199 }