c4d4a0f6ce73bd3778636cc43008c494a48ba3a4
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 static cl::opt<int> ReciprocalEstimateRefinementSteps(
71     "x86-recip-refinement-steps", cl::init(1),
72     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
73              "result of the hardware reciprocal estimate instruction."),
74     cl::NotHidden);
75
76 // Forward declarations.
77 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
78                        SDValue V2);
79
80 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
81                                      const X86Subtarget &STI)
82     : TargetLowering(TM), Subtarget(&STI) {
83   X86ScalarSSEf64 = Subtarget->hasSSE2();
84   X86ScalarSSEf32 = Subtarget->hasSSE1();
85   TD = getDataLayout();
86
87   // Set up the TargetLowering object.
88   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
89
90   // X86 is weird. It always uses i8 for shift amounts and setcc results.
91   setBooleanContents(ZeroOrOneBooleanContent);
92   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
93   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
94
95   // For 64-bit, since we have so many registers, use the ILP scheduler.
96   // For 32-bit, use the register pressure specific scheduling.
97   // For Atom, always use ILP scheduling.
98   if (Subtarget->isAtom())
99     setSchedulingPreference(Sched::ILP);
100   else if (Subtarget->is64Bit())
101     setSchedulingPreference(Sched::ILP);
102   else
103     setSchedulingPreference(Sched::RegPressure);
104   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
105   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
106
107   // Bypass expensive divides on Atom when compiling with O2.
108   if (TM.getOptLevel() >= CodeGenOpt::Default) {
109     if (Subtarget->hasSlowDivide32())
110       addBypassSlowDiv(32, 8);
111     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
112       addBypassSlowDiv(64, 16);
113   }
114
115   if (Subtarget->isTargetKnownWindowsMSVC()) {
116     // Setup Windows compiler runtime calls.
117     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
118     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
119     setLibcallName(RTLIB::SREM_I64, "_allrem");
120     setLibcallName(RTLIB::UREM_I64, "_aullrem");
121     setLibcallName(RTLIB::MUL_I64, "_allmul");
122     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
123     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
124     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
125     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
126     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
127
128     // The _ftol2 runtime function has an unusual calling conv, which
129     // is modeled by a special pseudo-instruction.
130     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
131     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
132     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
133     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
134   }
135
136   if (Subtarget->isTargetDarwin()) {
137     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
138     setUseUnderscoreSetJmp(false);
139     setUseUnderscoreLongJmp(false);
140   } else if (Subtarget->isTargetWindowsGNU()) {
141     // MS runtime is weird: it exports _setjmp, but longjmp!
142     setUseUnderscoreSetJmp(true);
143     setUseUnderscoreLongJmp(false);
144   } else {
145     setUseUnderscoreSetJmp(true);
146     setUseUnderscoreLongJmp(true);
147   }
148
149   // Set up the register classes.
150   addRegisterClass(MVT::i8, &X86::GR8RegClass);
151   addRegisterClass(MVT::i16, &X86::GR16RegClass);
152   addRegisterClass(MVT::i32, &X86::GR32RegClass);
153   if (Subtarget->is64Bit())
154     addRegisterClass(MVT::i64, &X86::GR64RegClass);
155
156   for (MVT VT : MVT::integer_valuetypes())
157     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
158
159   // We don't accept any truncstore of integer registers.
160   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
161   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
162   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
163   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
164   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
165   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
166
167   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
168
169   // SETOEQ and SETUNE require checking two conditions.
170   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
171   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
172   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
173   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
174   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
175   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
176
177   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
178   // operation.
179   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
180   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
181   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
182
183   if (Subtarget->is64Bit()) {
184     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
185     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
186   } else if (!TM.Options.UseSoftFloat) {
187     // We have an algorithm for SSE2->double, and we turn this into a
188     // 64-bit FILD followed by conditional FADD for other targets.
189     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
190     // We have an algorithm for SSE2, and we turn this into a 64-bit
191     // FILD for other targets.
192     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
193   }
194
195   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
196   // this operation.
197   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
198   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
199
200   if (!TM.Options.UseSoftFloat) {
201     // SSE has no i16 to fp conversion, only i32
202     if (X86ScalarSSEf32) {
203       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
204       // f32 and f64 cases are Legal, f80 case is not
205       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
206     } else {
207       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
208       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
209     }
210   } else {
211     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
212     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
213   }
214
215   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
216   // are Legal, f80 is custom lowered.
217   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
218   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
219
220   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
221   // this operation.
222   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
223   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
224
225   if (X86ScalarSSEf32) {
226     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
227     // f32 and f64 cases are Legal, f80 case is not
228     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
229   } else {
230     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
231     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
232   }
233
234   // Handle FP_TO_UINT by promoting the destination to a larger signed
235   // conversion.
236   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
237   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
238   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
239
240   if (Subtarget->is64Bit()) {
241     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
242     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
243   } else if (!TM.Options.UseSoftFloat) {
244     // Since AVX is a superset of SSE3, only check for SSE here.
245     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246       // Expand FP_TO_UINT into a select.
247       // FIXME: We would like to use a Custom expander here eventually to do
248       // the optimal thing for SSE vs. the default expansion in the legalizer.
249       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
250     else
251       // With SSE3 we can use fisttpll to convert to a signed i64; without
252       // SSE, we're stuck with a fistpll.
253       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
254   }
255
256   if (isTargetFTOL()) {
257     // Use the _ftol2 runtime function, which has a pseudo-instruction
258     // to handle its weird calling convention.
259     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
260   }
261
262   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
263   if (!X86ScalarSSEf64) {
264     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
265     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
266     if (Subtarget->is64Bit()) {
267       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
268       // Without SSE, i64->f64 goes through memory.
269       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
270     }
271   }
272
273   // Scalar integer divide and remainder are lowered to use operations that
274   // produce two results, to match the available instructions. This exposes
275   // the two-result form to trivial CSE, which is able to combine x/y and x%y
276   // into a single instruction.
277   //
278   // Scalar integer multiply-high is also lowered to use two-result
279   // operations, to match the available instructions. However, plain multiply
280   // (low) operations are left as Legal, as there are single-result
281   // instructions for this in x86. Using the two-result multiply instructions
282   // when both high and low results are needed must be arranged by dagcombine.
283   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
284     MVT VT = IntVTs[i];
285     setOperationAction(ISD::MULHS, VT, Expand);
286     setOperationAction(ISD::MULHU, VT, Expand);
287     setOperationAction(ISD::SDIV, VT, Expand);
288     setOperationAction(ISD::UDIV, VT, Expand);
289     setOperationAction(ISD::SREM, VT, Expand);
290     setOperationAction(ISD::UREM, VT, Expand);
291
292     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
293     setOperationAction(ISD::ADDC, VT, Custom);
294     setOperationAction(ISD::ADDE, VT, Custom);
295     setOperationAction(ISD::SUBC, VT, Custom);
296     setOperationAction(ISD::SUBE, VT, Custom);
297   }
298
299   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
300   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
301   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
302   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
303   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
304   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
305   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
306   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
307   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
312   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
313   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
314   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
315   if (Subtarget->is64Bit())
316     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
318   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
319   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
320   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
321   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
322   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
323   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
324   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
325
326   // Promote the i8 variants and force them on up to i32 which has a shorter
327   // encoding.
328   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
329   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
330   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
331   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
332   if (Subtarget->hasBMI()) {
333     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
334     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
335     if (Subtarget->is64Bit())
336       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
337   } else {
338     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
339     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
340     if (Subtarget->is64Bit())
341       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
342   }
343
344   if (Subtarget->hasLZCNT()) {
345     // When promoting the i8 variants, force them to i32 for a shorter
346     // encoding.
347     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
348     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
350     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
352     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
353     if (Subtarget->is64Bit())
354       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
355   } else {
356     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
357     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
358     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
361     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
362     if (Subtarget->is64Bit()) {
363       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
364       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
365     }
366   }
367
368   // Special handling for half-precision floating point conversions.
369   // If we don't have F16C support, then lower half float conversions
370   // into library calls.
371   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
372     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
374   }
375
376   // There's never any support for operations beyond MVT::f32.
377   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
381
382   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
388
389   if (Subtarget->hasPOPCNT()) {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
391   } else {
392     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
394     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
397   }
398
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400
401   if (!Subtarget->hasMOVBE())
402     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
403
404   // These should be promoted to a larger select which is supported.
405   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
406   // X86 wants to expand cmov itself.
407   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
408   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
412   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
419   if (Subtarget->is64Bit()) {
420     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
421     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
422   }
423   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
424   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426   // support continuation, user-level threading, and etc.. As a result, no
427   // other SjLj exception interfaces are implemented and please don't build
428   // your own exception handling based on them.
429   // LLVM/Clang supports zero-cost DWARF exception handling.
430   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
432
433   // Darwin ABI issue.
434   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
435   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
436   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
437   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
438   if (Subtarget->is64Bit())
439     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
441   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
442   if (Subtarget->is64Bit()) {
443     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
444     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
445     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
446     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
447     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
448   }
449   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
451   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
452   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
455     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
456     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
457   }
458
459   if (Subtarget->hasSSE1())
460     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
461
462   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
463
464   // Expand certain atomics
465   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
466     MVT VT = IntVTs[i];
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
470   }
471
472   if (Subtarget->hasCmpxchg16b()) {
473     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
474   }
475
476   // FIXME - use subtarget debug flags
477   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
480   }
481
482   if (Subtarget->is64Bit()) {
483     setExceptionPointerRegister(X86::RAX);
484     setExceptionSelectorRegister(X86::RDX);
485   } else {
486     setExceptionPointerRegister(X86::EAX);
487     setExceptionSelectorRegister(X86::EDX);
488   }
489   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
491
492   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
494
495   setOperationAction(ISD::TRAP, MVT::Other, Legal);
496   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
497
498   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
500   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
501   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
502     // TargetInfo::X86_64ABIBuiltinVaList
503     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
505   } else {
506     // TargetInfo::CharPtrBuiltinVaList
507     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
508     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
509   }
510
511   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
512   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
513
514   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
515
516   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
517     // f32 and f64 use SSE.
518     // Set up the FP register classes.
519     addRegisterClass(MVT::f32, &X86::FR32RegClass);
520     addRegisterClass(MVT::f64, &X86::FR64RegClass);
521
522     // Use ANDPD to simulate FABS.
523     setOperationAction(ISD::FABS , MVT::f64, Custom);
524     setOperationAction(ISD::FABS , MVT::f32, Custom);
525
526     // Use XORP to simulate FNEG.
527     setOperationAction(ISD::FNEG , MVT::f64, Custom);
528     setOperationAction(ISD::FNEG , MVT::f32, Custom);
529
530     // Use ANDPD and ORPD to simulate FCOPYSIGN.
531     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
532     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
533
534     // Lower this to FGETSIGNx86 plus an AND.
535     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
536     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
537
538     // We don't support sin/cos/fmod
539     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
540     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
541     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
542     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
543     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
544     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
545
546     // Expand FP immediates into loads from the stack, except for the special
547     // cases we handle.
548     addLegalFPImmediate(APFloat(+0.0)); // xorpd
549     addLegalFPImmediate(APFloat(+0.0f)); // xorps
550   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
551     // Use SSE for f32, x87 for f64.
552     // Set up the FP register classes.
553     addRegisterClass(MVT::f32, &X86::FR32RegClass);
554     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
555
556     // Use ANDPS to simulate FABS.
557     setOperationAction(ISD::FABS , MVT::f32, Custom);
558
559     // Use XORP to simulate FNEG.
560     setOperationAction(ISD::FNEG , MVT::f32, Custom);
561
562     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
563
564     // Use ANDPS and ORPS to simulate FCOPYSIGN.
565     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
566     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
567
568     // We don't support sin/cos/fmod
569     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
570     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
571     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
572
573     // Special cases we handle for FP constants.
574     addLegalFPImmediate(APFloat(+0.0f)); // xorps
575     addLegalFPImmediate(APFloat(+0.0)); // FLD0
576     addLegalFPImmediate(APFloat(+1.0)); // FLD1
577     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
578     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
579
580     if (!TM.Options.UnsafeFPMath) {
581       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
582       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
583       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
584     }
585   } else if (!TM.Options.UseSoftFloat) {
586     // f32 and f64 in x87.
587     // Set up the FP register classes.
588     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
589     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
590
591     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
592     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
593     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
594     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
595
596     if (!TM.Options.UnsafeFPMath) {
597       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
598       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
599       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
600       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
601       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
602       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
603     }
604     addLegalFPImmediate(APFloat(+0.0)); // FLD0
605     addLegalFPImmediate(APFloat(+1.0)); // FLD1
606     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
607     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
608     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
612   }
613
614   // We don't support FMA.
615   setOperationAction(ISD::FMA, MVT::f64, Expand);
616   setOperationAction(ISD::FMA, MVT::f32, Expand);
617
618   // Long double always uses X87.
619   if (!TM.Options.UseSoftFloat) {
620     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
621     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
622     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
623     {
624       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
625       addLegalFPImmediate(TmpFlt);  // FLD0
626       TmpFlt.changeSign();
627       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
628
629       bool ignored;
630       APFloat TmpFlt2(+1.0);
631       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
632                       &ignored);
633       addLegalFPImmediate(TmpFlt2);  // FLD1
634       TmpFlt2.changeSign();
635       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
636     }
637
638     if (!TM.Options.UnsafeFPMath) {
639       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
640       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
641       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
642     }
643
644     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
645     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
646     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
647     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
648     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
649     setOperationAction(ISD::FMA, MVT::f80, Expand);
650   }
651
652   // Always use a library call for pow.
653   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
654   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
655   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
656
657   setOperationAction(ISD::FLOG, MVT::f80, Expand);
658   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
659   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
660   setOperationAction(ISD::FEXP, MVT::f80, Expand);
661   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
662   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
663   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
664
665   // First set operation action for all vector types to either promote
666   // (for widening) or expand (for scalarization). Then we will selectively
667   // turn on ones that can be effectively codegen'd.
668   for (MVT VT : MVT::vector_valuetypes()) {
669     setOperationAction(ISD::ADD , VT, Expand);
670     setOperationAction(ISD::SUB , VT, Expand);
671     setOperationAction(ISD::FADD, VT, Expand);
672     setOperationAction(ISD::FNEG, VT, Expand);
673     setOperationAction(ISD::FSUB, VT, Expand);
674     setOperationAction(ISD::MUL , VT, Expand);
675     setOperationAction(ISD::FMUL, VT, Expand);
676     setOperationAction(ISD::SDIV, VT, Expand);
677     setOperationAction(ISD::UDIV, VT, Expand);
678     setOperationAction(ISD::FDIV, VT, Expand);
679     setOperationAction(ISD::SREM, VT, Expand);
680     setOperationAction(ISD::UREM, VT, Expand);
681     setOperationAction(ISD::LOAD, VT, Expand);
682     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
683     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
684     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
685     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
686     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
687     setOperationAction(ISD::FABS, VT, Expand);
688     setOperationAction(ISD::FSIN, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FCOS, VT, Expand);
691     setOperationAction(ISD::FSINCOS, VT, Expand);
692     setOperationAction(ISD::FREM, VT, Expand);
693     setOperationAction(ISD::FMA,  VT, Expand);
694     setOperationAction(ISD::FPOWI, VT, Expand);
695     setOperationAction(ISD::FSQRT, VT, Expand);
696     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
697     setOperationAction(ISD::FFLOOR, VT, Expand);
698     setOperationAction(ISD::FCEIL, VT, Expand);
699     setOperationAction(ISD::FTRUNC, VT, Expand);
700     setOperationAction(ISD::FRINT, VT, Expand);
701     setOperationAction(ISD::FNEARBYINT, VT, Expand);
702     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHS, VT, Expand);
704     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
705     setOperationAction(ISD::MULHU, VT, Expand);
706     setOperationAction(ISD::SDIVREM, VT, Expand);
707     setOperationAction(ISD::UDIVREM, VT, Expand);
708     setOperationAction(ISD::FPOW, VT, Expand);
709     setOperationAction(ISD::CTPOP, VT, Expand);
710     setOperationAction(ISD::CTTZ, VT, Expand);
711     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::CTLZ, VT, Expand);
713     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
714     setOperationAction(ISD::SHL, VT, Expand);
715     setOperationAction(ISD::SRA, VT, Expand);
716     setOperationAction(ISD::SRL, VT, Expand);
717     setOperationAction(ISD::ROTL, VT, Expand);
718     setOperationAction(ISD::ROTR, VT, Expand);
719     setOperationAction(ISD::BSWAP, VT, Expand);
720     setOperationAction(ISD::SETCC, VT, Expand);
721     setOperationAction(ISD::FLOG, VT, Expand);
722     setOperationAction(ISD::FLOG2, VT, Expand);
723     setOperationAction(ISD::FLOG10, VT, Expand);
724     setOperationAction(ISD::FEXP, VT, Expand);
725     setOperationAction(ISD::FEXP2, VT, Expand);
726     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
727     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
728     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
729     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
731     setOperationAction(ISD::TRUNCATE, VT, Expand);
732     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
733     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
734     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
735     setOperationAction(ISD::VSELECT, VT, Expand);
736     setOperationAction(ISD::SELECT_CC, VT, Expand);
737     for (MVT InnerVT : MVT::vector_valuetypes()) {
738       setTruncStoreAction(InnerVT, VT, Expand);
739
740       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
741       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
742
743       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
744       // types, we have to deal with them whether we ask for Expansion or not.
745       // Setting Expand causes its own optimisation problems though, so leave
746       // them legal.
747       if (VT.getVectorElementType() == MVT::i1)
748         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
749     }
750   }
751
752   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
753   // with -msoft-float, disable use of MMX as well.
754   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
755     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
756     // No operations on x86mmx supported, everything uses intrinsics.
757   }
758
759   // MMX-sized vectors (other than x86mmx) are expected to be expanded
760   // into smaller operations.
761   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
762     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
763     setOperationAction(ISD::AND,                MMXTy,      Expand);
764     setOperationAction(ISD::OR,                 MMXTy,      Expand);
765     setOperationAction(ISD::XOR,                MMXTy,      Expand);
766     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
767     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
768     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
769   }
770   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
771
772   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
773     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
774
775     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
776     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
777     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
778     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
779     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
780     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
781     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
782     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
783     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
784     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
785     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
786     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
787     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
788     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
789   }
790
791   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
792     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
793
794     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
795     // registers cannot be used even for integer operations.
796     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
797     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
798     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
799     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
800
801     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
802     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
803     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
804     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
805     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
806     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
807     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
808     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
809     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
810     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
811     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
812     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
813     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
814     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
815     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
816     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
817     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
818     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
819     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
820     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
822     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
823     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
824
825     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
826     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
827     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
828     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
829
830     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
831     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
832     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
833     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
834     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
835
836     // Only provide customized ctpop vector bit twiddling for vector types we
837     // know to perform better than using the popcnt instructions on each vector
838     // element. If popcnt isn't supported, always provide the custom version.
839     if (!Subtarget->hasPOPCNT()) {
840       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
841       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
842     }
843
844     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
845     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
846       MVT VT = (MVT::SimpleValueType)i;
847       // Do not attempt to custom lower non-power-of-2 vectors
848       if (!isPowerOf2_32(VT.getVectorNumElements()))
849         continue;
850       // Do not attempt to custom lower non-128-bit vectors
851       if (!VT.is128BitVector())
852         continue;
853       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
854       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
855       setOperationAction(ISD::VSELECT,            VT, Custom);
856       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
857     }
858
859     // We support custom legalizing of sext and anyext loads for specific
860     // memory vector types which we can load as a scalar (or sequence of
861     // scalars) and extend in-register to a legal 128-bit vector type. For sext
862     // loads these must work with a single scalar load.
863     for (MVT VT : MVT::integer_vector_valuetypes()) {
864       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
865       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
866       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
867       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
868       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
869       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
870       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
871       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
873     }
874
875     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
876     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
877     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
878     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
879     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
880     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
881     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
882     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
883
884     if (Subtarget->is64Bit()) {
885       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
886       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
887     }
888
889     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
890     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
891       MVT VT = (MVT::SimpleValueType)i;
892
893       // Do not attempt to promote non-128-bit vectors
894       if (!VT.is128BitVector())
895         continue;
896
897       setOperationAction(ISD::AND,    VT, Promote);
898       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
899       setOperationAction(ISD::OR,     VT, Promote);
900       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
901       setOperationAction(ISD::XOR,    VT, Promote);
902       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
903       setOperationAction(ISD::LOAD,   VT, Promote);
904       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
905       setOperationAction(ISD::SELECT, VT, Promote);
906       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
907     }
908
909     // Custom lower v2i64 and v2f64 selects.
910     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
911     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
912     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
913     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
914
915     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
916     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
917
918     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
919     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
920     // As there is no 64-bit GPR available, we need build a special custom
921     // sequence to convert from v2i32 to v2f32.
922     if (!Subtarget->is64Bit())
923       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
924
925     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
926     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
927
928     for (MVT VT : MVT::fp_vector_valuetypes())
929       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
930
931     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
932     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
933     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
934   }
935
936   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
937     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
938       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
939       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
940       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
941       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
942       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
943     }
944
945     // FIXME: Do we need to handle scalar-to-vector here?
946     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
947
948     // We directly match byte blends in the backend as they match the VSELECT
949     // condition form.
950     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
951
952     // SSE41 brings specific instructions for doing vector sign extend even in
953     // cases where we don't have SRA.
954     for (MVT VT : MVT::integer_vector_valuetypes()) {
955       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
956       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
957       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
958     }
959
960     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
961     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
962     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
963     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
964     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
965     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
966     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
967
968     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
969     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
970     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
971     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
972     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
973     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
974
975     // i8 and i16 vectors are custom because the source register and source
976     // source memory operand types are not the same width.  f32 vectors are
977     // custom since the immediate controlling the insert encodes additional
978     // information.
979     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
980     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
981     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
982     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
983
984     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
985     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
986     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
987     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
988
989     // FIXME: these should be Legal, but that's only for the case where
990     // the index is constant.  For now custom expand to deal with that.
991     if (Subtarget->is64Bit()) {
992       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
993       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
994     }
995   }
996
997   if (Subtarget->hasSSE2()) {
998     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
999     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1000
1001     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1002     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1003
1004     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1005     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1006
1007     // In the customized shift lowering, the legal cases in AVX2 will be
1008     // recognized.
1009     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1010     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1011
1012     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1013     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1014
1015     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1016   }
1017
1018   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1019     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1020     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1021     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1022     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1023     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1024     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1025
1026     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1027     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1028     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1029
1030     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1031     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1032     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1033     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1034     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1035     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1036     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1037     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1038     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1039     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1040     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1041     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1042
1043     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1044     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1045     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1046     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1047     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1048     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1049     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1050     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1051     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1052     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1053     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1054     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1055
1056     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1057     // even though v8i16 is a legal type.
1058     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1059     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1060     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1061
1062     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1063     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1064     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1065
1066     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1067     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1068
1069     for (MVT VT : MVT::fp_vector_valuetypes())
1070       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1071
1072     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1073     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1074
1075     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1076     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1077
1078     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1079     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1080
1081     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1082     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1083     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1084     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1085
1086     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1087     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1088     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1089
1090     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1091     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1092     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1093     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1094     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1095     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1096     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1097     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1098     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1099     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1100     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1101     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1102
1103     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1104       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1105       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1106       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1107       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1108       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1109       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1110     }
1111
1112     if (Subtarget->hasInt256()) {
1113       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1114       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1115       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1116       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1117
1118       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1119       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1120       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1121       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1122
1123       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1124       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1125       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1126       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1127
1128       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1129       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1130       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1131       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1132
1133       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1134       // when we have a 256bit-wide blend with immediate.
1135       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1136
1137       // Only provide customized ctpop vector bit twiddling for vector types we
1138       // know to perform better than using the popcnt instructions on each
1139       // vector element. If popcnt isn't supported, always provide the custom
1140       // version.
1141       if (!Subtarget->hasPOPCNT())
1142         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1143
1144       // Custom CTPOP always performs better on natively supported v8i32
1145       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1146
1147       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1148       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1149       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1150       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1151       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1152       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1153       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1154
1155       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1156       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1157       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1158       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1159       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1160       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1161     } else {
1162       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1163       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1164       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1165       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1166
1167       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1168       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1169       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1170       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1171
1172       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1173       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1174       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1175       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1176     }
1177
1178     // In the customized shift lowering, the legal cases in AVX2 will be
1179     // recognized.
1180     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1181     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1182
1183     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1184     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1185
1186     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1187
1188     // Custom lower several nodes for 256-bit types.
1189     for (MVT VT : MVT::vector_valuetypes()) {
1190       if (VT.getScalarSizeInBits() >= 32) {
1191         setOperationAction(ISD::MLOAD,  VT, Legal);
1192         setOperationAction(ISD::MSTORE, VT, Legal);
1193       }
1194       // Extract subvector is special because the value type
1195       // (result) is 128-bit but the source is 256-bit wide.
1196       if (VT.is128BitVector()) {
1197         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1198       }
1199       // Do not attempt to custom lower other non-256-bit vectors
1200       if (!VT.is256BitVector())
1201         continue;
1202
1203       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1204       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1205       setOperationAction(ISD::VSELECT,            VT, Custom);
1206       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1207       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1208       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1209       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1210       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1211     }
1212
1213     if (Subtarget->hasInt256())
1214       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1215
1216
1217     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1218     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1219       MVT VT = (MVT::SimpleValueType)i;
1220
1221       // Do not attempt to promote non-256-bit vectors
1222       if (!VT.is256BitVector())
1223         continue;
1224
1225       setOperationAction(ISD::AND,    VT, Promote);
1226       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1227       setOperationAction(ISD::OR,     VT, Promote);
1228       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1229       setOperationAction(ISD::XOR,    VT, Promote);
1230       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1231       setOperationAction(ISD::LOAD,   VT, Promote);
1232       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1233       setOperationAction(ISD::SELECT, VT, Promote);
1234       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1235     }
1236   }
1237
1238   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1239     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1240     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1241     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1242     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1243
1244     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1245     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1246     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1247
1248     for (MVT VT : MVT::fp_vector_valuetypes())
1249       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1250
1251     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1252     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1253     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1254     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1255     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1256     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1257     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1258     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1259     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1260     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1261
1262     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1263     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1264     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1265     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1266     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1267     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1268
1269     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1270     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1271     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1272     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1273     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1274     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1275     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1276     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1277
1278     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1279     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1280     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1281     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1282     if (Subtarget->is64Bit()) {
1283       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1284       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1285       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1286       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1287     }
1288     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1289     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1290     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1291     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1292     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1293     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1294     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1295     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1296     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1297     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1298     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1299     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1300     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1301     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1302
1303     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1304     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1305     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1306     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1307     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1308     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1309     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1310     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1311     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1312     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1313     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1314     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1315     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1316
1317     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1318     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1319     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1320     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1321     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1322     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1323     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1324     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1325     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1326     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1327
1328     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1329     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1330     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1331     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1332     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1333
1334     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1335     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1336
1337     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1338
1339     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1340     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1341     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1342     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1343     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1344     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1345     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1346     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1347     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1348
1349     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1350     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1351
1352     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1353     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1354
1355     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1356
1357     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1358     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1359
1360     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1361     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1362
1363     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1364     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1365
1366     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1367     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1368     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1369     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1370     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1371     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1372
1373     if (Subtarget->hasCDI()) {
1374       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1375       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1376     }
1377     if (Subtarget->hasDQI()) {
1378       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1379       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1380       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1381     }
1382     // Custom lower several nodes.
1383     for (MVT VT : MVT::vector_valuetypes()) {
1384       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1385       // Extract subvector is special because the value type
1386       // (result) is 256/128-bit but the source is 512-bit wide.
1387       if (VT.is128BitVector() || VT.is256BitVector()) {
1388         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1389       }
1390       if (VT.getVectorElementType() == MVT::i1)
1391         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1392
1393       // Do not attempt to custom lower other non-512-bit vectors
1394       if (!VT.is512BitVector())
1395         continue;
1396
1397       if ( EltSize >= 32) {
1398         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1399         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1400         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1401         setOperationAction(ISD::VSELECT,             VT, Legal);
1402         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1403         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1404         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1405         setOperationAction(ISD::MLOAD,               VT, Legal);
1406         setOperationAction(ISD::MSTORE,              VT, Legal);
1407       }
1408     }
1409     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1410       MVT VT = (MVT::SimpleValueType)i;
1411
1412       // Do not attempt to promote non-512-bit vectors.
1413       if (!VT.is512BitVector())
1414         continue;
1415
1416       setOperationAction(ISD::SELECT, VT, Promote);
1417       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1418     }
1419   }// has  AVX-512
1420
1421   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1422     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1423     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1424
1425     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1426     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1427
1428     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1429     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1430     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1431     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1432     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1433     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1434     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1435     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1436     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1437     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1439     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1440     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1441
1442     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1443       const MVT VT = (MVT::SimpleValueType)i;
1444
1445       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1446
1447       // Do not attempt to promote non-512-bit vectors.
1448       if (!VT.is512BitVector())
1449         continue;
1450
1451       if (EltSize < 32) {
1452         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1453         setOperationAction(ISD::VSELECT,             VT, Legal);
1454       }
1455     }
1456   }
1457
1458   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1459     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1460     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1461
1462     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1463     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1464     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1465     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1466     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1467     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1468
1469     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1470     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1471     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1472     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1473     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1474     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1475   }
1476
1477   // We want to custom lower some of our intrinsics.
1478   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1479   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1480   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1481   if (!Subtarget->is64Bit())
1482     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1483
1484   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1485   // handle type legalization for these operations here.
1486   //
1487   // FIXME: We really should do custom legalization for addition and
1488   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1489   // than generic legalization for 64-bit multiplication-with-overflow, though.
1490   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1491     // Add/Sub/Mul with overflow operations are custom lowered.
1492     MVT VT = IntVTs[i];
1493     setOperationAction(ISD::SADDO, VT, Custom);
1494     setOperationAction(ISD::UADDO, VT, Custom);
1495     setOperationAction(ISD::SSUBO, VT, Custom);
1496     setOperationAction(ISD::USUBO, VT, Custom);
1497     setOperationAction(ISD::SMULO, VT, Custom);
1498     setOperationAction(ISD::UMULO, VT, Custom);
1499   }
1500
1501
1502   if (!Subtarget->is64Bit()) {
1503     // These libcalls are not available in 32-bit.
1504     setLibcallName(RTLIB::SHL_I128, nullptr);
1505     setLibcallName(RTLIB::SRL_I128, nullptr);
1506     setLibcallName(RTLIB::SRA_I128, nullptr);
1507   }
1508
1509   // Combine sin / cos into one node or libcall if possible.
1510   if (Subtarget->hasSinCos()) {
1511     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1512     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1513     if (Subtarget->isTargetDarwin()) {
1514       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1515       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1516       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1517       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1518     }
1519   }
1520
1521   if (Subtarget->isTargetWin64()) {
1522     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1523     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1524     setOperationAction(ISD::SREM, MVT::i128, Custom);
1525     setOperationAction(ISD::UREM, MVT::i128, Custom);
1526     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1527     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1528   }
1529
1530   // We have target-specific dag combine patterns for the following nodes:
1531   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1532   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1533   setTargetDAGCombine(ISD::BITCAST);
1534   setTargetDAGCombine(ISD::VSELECT);
1535   setTargetDAGCombine(ISD::SELECT);
1536   setTargetDAGCombine(ISD::SHL);
1537   setTargetDAGCombine(ISD::SRA);
1538   setTargetDAGCombine(ISD::SRL);
1539   setTargetDAGCombine(ISD::OR);
1540   setTargetDAGCombine(ISD::AND);
1541   setTargetDAGCombine(ISD::ADD);
1542   setTargetDAGCombine(ISD::FADD);
1543   setTargetDAGCombine(ISD::FSUB);
1544   setTargetDAGCombine(ISD::FMA);
1545   setTargetDAGCombine(ISD::SUB);
1546   setTargetDAGCombine(ISD::LOAD);
1547   setTargetDAGCombine(ISD::MLOAD);
1548   setTargetDAGCombine(ISD::STORE);
1549   setTargetDAGCombine(ISD::MSTORE);
1550   setTargetDAGCombine(ISD::ZERO_EXTEND);
1551   setTargetDAGCombine(ISD::ANY_EXTEND);
1552   setTargetDAGCombine(ISD::SIGN_EXTEND);
1553   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1554   setTargetDAGCombine(ISD::TRUNCATE);
1555   setTargetDAGCombine(ISD::SINT_TO_FP);
1556   setTargetDAGCombine(ISD::SETCC);
1557   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1558   setTargetDAGCombine(ISD::BUILD_VECTOR);
1559   setTargetDAGCombine(ISD::MUL);
1560   setTargetDAGCombine(ISD::XOR);
1561
1562   computeRegisterProperties(Subtarget->getRegisterInfo());
1563
1564   // On Darwin, -Os means optimize for size without hurting performance,
1565   // do not reduce the limit.
1566   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1567   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1568   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1569   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1570   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1571   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1572   setPrefLoopAlignment(4); // 2^4 bytes.
1573
1574   // Predictable cmov don't hurt on atom because it's in-order.
1575   PredictableSelectIsExpensive = !Subtarget->isAtom();
1576   EnableExtLdPromotion = true;
1577   setPrefFunctionAlignment(4); // 2^4 bytes.
1578
1579   verifyIntrinsicTables();
1580 }
1581
1582 // This has so far only been implemented for 64-bit MachO.
1583 bool X86TargetLowering::useLoadStackGuardNode() const {
1584   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1585 }
1586
1587 TargetLoweringBase::LegalizeTypeAction
1588 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1589   if (ExperimentalVectorWideningLegalization &&
1590       VT.getVectorNumElements() != 1 &&
1591       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1592     return TypeWidenVector;
1593
1594   return TargetLoweringBase::getPreferredVectorAction(VT);
1595 }
1596
1597 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1598   if (!VT.isVector())
1599     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1600
1601   const unsigned NumElts = VT.getVectorNumElements();
1602   const EVT EltVT = VT.getVectorElementType();
1603   if (VT.is512BitVector()) {
1604     if (Subtarget->hasAVX512())
1605       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1606           EltVT == MVT::f32 || EltVT == MVT::f64)
1607         switch(NumElts) {
1608         case  8: return MVT::v8i1;
1609         case 16: return MVT::v16i1;
1610       }
1611     if (Subtarget->hasBWI())
1612       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1613         switch(NumElts) {
1614         case 32: return MVT::v32i1;
1615         case 64: return MVT::v64i1;
1616       }
1617   }
1618
1619   if (VT.is256BitVector() || VT.is128BitVector()) {
1620     if (Subtarget->hasVLX())
1621       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1622           EltVT == MVT::f32 || EltVT == MVT::f64)
1623         switch(NumElts) {
1624         case 2: return MVT::v2i1;
1625         case 4: return MVT::v4i1;
1626         case 8: return MVT::v8i1;
1627       }
1628     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1629       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1630         switch(NumElts) {
1631         case  8: return MVT::v8i1;
1632         case 16: return MVT::v16i1;
1633         case 32: return MVT::v32i1;
1634       }
1635   }
1636
1637   return VT.changeVectorElementTypeToInteger();
1638 }
1639
1640 /// Helper for getByValTypeAlignment to determine
1641 /// the desired ByVal argument alignment.
1642 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1643   if (MaxAlign == 16)
1644     return;
1645   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1646     if (VTy->getBitWidth() == 128)
1647       MaxAlign = 16;
1648   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1649     unsigned EltAlign = 0;
1650     getMaxByValAlign(ATy->getElementType(), EltAlign);
1651     if (EltAlign > MaxAlign)
1652       MaxAlign = EltAlign;
1653   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1654     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1655       unsigned EltAlign = 0;
1656       getMaxByValAlign(STy->getElementType(i), EltAlign);
1657       if (EltAlign > MaxAlign)
1658         MaxAlign = EltAlign;
1659       if (MaxAlign == 16)
1660         break;
1661     }
1662   }
1663 }
1664
1665 /// Return the desired alignment for ByVal aggregate
1666 /// function arguments in the caller parameter area. For X86, aggregates
1667 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1668 /// are at 4-byte boundaries.
1669 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1670   if (Subtarget->is64Bit()) {
1671     // Max of 8 and alignment of type.
1672     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1673     if (TyAlign > 8)
1674       return TyAlign;
1675     return 8;
1676   }
1677
1678   unsigned Align = 4;
1679   if (Subtarget->hasSSE1())
1680     getMaxByValAlign(Ty, Align);
1681   return Align;
1682 }
1683
1684 /// Returns the target specific optimal type for load
1685 /// and store operations as a result of memset, memcpy, and memmove
1686 /// lowering. If DstAlign is zero that means it's safe to destination
1687 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1688 /// means there isn't a need to check it against alignment requirement,
1689 /// probably because the source does not need to be loaded. If 'IsMemset' is
1690 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1691 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1692 /// source is constant so it does not need to be loaded.
1693 /// It returns EVT::Other if the type should be determined using generic
1694 /// target-independent logic.
1695 EVT
1696 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1697                                        unsigned DstAlign, unsigned SrcAlign,
1698                                        bool IsMemset, bool ZeroMemset,
1699                                        bool MemcpyStrSrc,
1700                                        MachineFunction &MF) const {
1701   const Function *F = MF.getFunction();
1702   if ((!IsMemset || ZeroMemset) &&
1703       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1704     if (Size >= 16 &&
1705         (Subtarget->isUnalignedMemAccessFast() ||
1706          ((DstAlign == 0 || DstAlign >= 16) &&
1707           (SrcAlign == 0 || SrcAlign >= 16)))) {
1708       if (Size >= 32) {
1709         if (Subtarget->hasInt256())
1710           return MVT::v8i32;
1711         if (Subtarget->hasFp256())
1712           return MVT::v8f32;
1713       }
1714       if (Subtarget->hasSSE2())
1715         return MVT::v4i32;
1716       if (Subtarget->hasSSE1())
1717         return MVT::v4f32;
1718     } else if (!MemcpyStrSrc && Size >= 8 &&
1719                !Subtarget->is64Bit() &&
1720                Subtarget->hasSSE2()) {
1721       // Do not use f64 to lower memcpy if source is string constant. It's
1722       // better to use i32 to avoid the loads.
1723       return MVT::f64;
1724     }
1725   }
1726   if (Subtarget->is64Bit() && Size >= 8)
1727     return MVT::i64;
1728   return MVT::i32;
1729 }
1730
1731 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1732   if (VT == MVT::f32)
1733     return X86ScalarSSEf32;
1734   else if (VT == MVT::f64)
1735     return X86ScalarSSEf64;
1736   return true;
1737 }
1738
1739 bool
1740 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1741                                                   unsigned,
1742                                                   unsigned,
1743                                                   bool *Fast) const {
1744   if (Fast)
1745     *Fast = Subtarget->isUnalignedMemAccessFast();
1746   return true;
1747 }
1748
1749 /// Return the entry encoding for a jump table in the
1750 /// current function.  The returned value is a member of the
1751 /// MachineJumpTableInfo::JTEntryKind enum.
1752 unsigned X86TargetLowering::getJumpTableEncoding() const {
1753   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1754   // symbol.
1755   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1756       Subtarget->isPICStyleGOT())
1757     return MachineJumpTableInfo::EK_Custom32;
1758
1759   // Otherwise, use the normal jump table encoding heuristics.
1760   return TargetLowering::getJumpTableEncoding();
1761 }
1762
1763 const MCExpr *
1764 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1765                                              const MachineBasicBlock *MBB,
1766                                              unsigned uid,MCContext &Ctx) const{
1767   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1768          Subtarget->isPICStyleGOT());
1769   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1770   // entries.
1771   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1772                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1773 }
1774
1775 /// Returns relocation base for the given PIC jumptable.
1776 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1777                                                     SelectionDAG &DAG) const {
1778   if (!Subtarget->is64Bit())
1779     // This doesn't have SDLoc associated with it, but is not really the
1780     // same as a Register.
1781     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1782   return Table;
1783 }
1784
1785 /// This returns the relocation base for the given PIC jumptable,
1786 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1787 const MCExpr *X86TargetLowering::
1788 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1789                              MCContext &Ctx) const {
1790   // X86-64 uses RIP relative addressing based on the jump table label.
1791   if (Subtarget->isPICStyleRIPRel())
1792     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1793
1794   // Otherwise, the reference is relative to the PIC base.
1795   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1796 }
1797
1798 std::pair<const TargetRegisterClass *, uint8_t>
1799 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1800                                            MVT VT) const {
1801   const TargetRegisterClass *RRC = nullptr;
1802   uint8_t Cost = 1;
1803   switch (VT.SimpleTy) {
1804   default:
1805     return TargetLowering::findRepresentativeClass(TRI, VT);
1806   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1807     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1808     break;
1809   case MVT::x86mmx:
1810     RRC = &X86::VR64RegClass;
1811     break;
1812   case MVT::f32: case MVT::f64:
1813   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1814   case MVT::v4f32: case MVT::v2f64:
1815   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1816   case MVT::v4f64:
1817     RRC = &X86::VR128RegClass;
1818     break;
1819   }
1820   return std::make_pair(RRC, Cost);
1821 }
1822
1823 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1824                                                unsigned &Offset) const {
1825   if (!Subtarget->isTargetLinux())
1826     return false;
1827
1828   if (Subtarget->is64Bit()) {
1829     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1830     Offset = 0x28;
1831     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1832       AddressSpace = 256;
1833     else
1834       AddressSpace = 257;
1835   } else {
1836     // %gs:0x14 on i386
1837     Offset = 0x14;
1838     AddressSpace = 256;
1839   }
1840   return true;
1841 }
1842
1843 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1844                                             unsigned DestAS) const {
1845   assert(SrcAS != DestAS && "Expected different address spaces!");
1846
1847   return SrcAS < 256 && DestAS < 256;
1848 }
1849
1850 //===----------------------------------------------------------------------===//
1851 //               Return Value Calling Convention Implementation
1852 //===----------------------------------------------------------------------===//
1853
1854 #include "X86GenCallingConv.inc"
1855
1856 bool
1857 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1858                                   MachineFunction &MF, bool isVarArg,
1859                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1860                         LLVMContext &Context) const {
1861   SmallVector<CCValAssign, 16> RVLocs;
1862   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1863   return CCInfo.CheckReturn(Outs, RetCC_X86);
1864 }
1865
1866 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1867   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1868   return ScratchRegs;
1869 }
1870
1871 SDValue
1872 X86TargetLowering::LowerReturn(SDValue Chain,
1873                                CallingConv::ID CallConv, bool isVarArg,
1874                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1875                                const SmallVectorImpl<SDValue> &OutVals,
1876                                SDLoc dl, SelectionDAG &DAG) const {
1877   MachineFunction &MF = DAG.getMachineFunction();
1878   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1879
1880   SmallVector<CCValAssign, 16> RVLocs;
1881   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1882   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1883
1884   SDValue Flag;
1885   SmallVector<SDValue, 6> RetOps;
1886   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1887   // Operand #1 = Bytes To Pop
1888   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1889                    MVT::i16));
1890
1891   // Copy the result values into the output registers.
1892   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1893     CCValAssign &VA = RVLocs[i];
1894     assert(VA.isRegLoc() && "Can only return in registers!");
1895     SDValue ValToCopy = OutVals[i];
1896     EVT ValVT = ValToCopy.getValueType();
1897
1898     // Promote values to the appropriate types.
1899     if (VA.getLocInfo() == CCValAssign::SExt)
1900       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1901     else if (VA.getLocInfo() == CCValAssign::ZExt)
1902       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1903     else if (VA.getLocInfo() == CCValAssign::AExt)
1904       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1905     else if (VA.getLocInfo() == CCValAssign::BCvt)
1906       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1907
1908     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1909            "Unexpected FP-extend for return value.");
1910
1911     // If this is x86-64, and we disabled SSE, we can't return FP values,
1912     // or SSE or MMX vectors.
1913     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1914          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1915           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1916       report_fatal_error("SSE register return with SSE disabled");
1917     }
1918     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1919     // llvm-gcc has never done it right and no one has noticed, so this
1920     // should be OK for now.
1921     if (ValVT == MVT::f64 &&
1922         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1923       report_fatal_error("SSE2 register return with SSE2 disabled");
1924
1925     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1926     // the RET instruction and handled by the FP Stackifier.
1927     if (VA.getLocReg() == X86::FP0 ||
1928         VA.getLocReg() == X86::FP1) {
1929       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1930       // change the value to the FP stack register class.
1931       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1932         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1933       RetOps.push_back(ValToCopy);
1934       // Don't emit a copytoreg.
1935       continue;
1936     }
1937
1938     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1939     // which is returned in RAX / RDX.
1940     if (Subtarget->is64Bit()) {
1941       if (ValVT == MVT::x86mmx) {
1942         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1943           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1944           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1945                                   ValToCopy);
1946           // If we don't have SSE2 available, convert to v4f32 so the generated
1947           // register is legal.
1948           if (!Subtarget->hasSSE2())
1949             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1950         }
1951       }
1952     }
1953
1954     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1955     Flag = Chain.getValue(1);
1956     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1957   }
1958
1959   // The x86-64 ABIs require that for returning structs by value we copy
1960   // the sret argument into %rax/%eax (depending on ABI) for the return.
1961   // Win32 requires us to put the sret argument to %eax as well.
1962   // We saved the argument into a virtual register in the entry block,
1963   // so now we copy the value out and into %rax/%eax.
1964   //
1965   // Checking Function.hasStructRetAttr() here is insufficient because the IR
1966   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
1967   // false, then an sret argument may be implicitly inserted in the SelDAG. In
1968   // either case FuncInfo->setSRetReturnReg() will have been called.
1969   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
1970     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
1971            "No need for an sret register");
1972     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
1973
1974     unsigned RetValReg
1975         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1976           X86::RAX : X86::EAX;
1977     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1978     Flag = Chain.getValue(1);
1979
1980     // RAX/EAX now acts like a return value.
1981     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1982   }
1983
1984   RetOps[0] = Chain;  // Update chain.
1985
1986   // Add the flag if we have it.
1987   if (Flag.getNode())
1988     RetOps.push_back(Flag);
1989
1990   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1991 }
1992
1993 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1994   if (N->getNumValues() != 1)
1995     return false;
1996   if (!N->hasNUsesOfValue(1, 0))
1997     return false;
1998
1999   SDValue TCChain = Chain;
2000   SDNode *Copy = *N->use_begin();
2001   if (Copy->getOpcode() == ISD::CopyToReg) {
2002     // If the copy has a glue operand, we conservatively assume it isn't safe to
2003     // perform a tail call.
2004     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2005       return false;
2006     TCChain = Copy->getOperand(0);
2007   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2008     return false;
2009
2010   bool HasRet = false;
2011   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2012        UI != UE; ++UI) {
2013     if (UI->getOpcode() != X86ISD::RET_FLAG)
2014       return false;
2015     // If we are returning more than one value, we can definitely
2016     // not make a tail call see PR19530
2017     if (UI->getNumOperands() > 4)
2018       return false;
2019     if (UI->getNumOperands() == 4 &&
2020         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2021       return false;
2022     HasRet = true;
2023   }
2024
2025   if (!HasRet)
2026     return false;
2027
2028   Chain = TCChain;
2029   return true;
2030 }
2031
2032 EVT
2033 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2034                                             ISD::NodeType ExtendKind) const {
2035   MVT ReturnMVT;
2036   // TODO: Is this also valid on 32-bit?
2037   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2038     ReturnMVT = MVT::i8;
2039   else
2040     ReturnMVT = MVT::i32;
2041
2042   EVT MinVT = getRegisterType(Context, ReturnMVT);
2043   return VT.bitsLT(MinVT) ? MinVT : VT;
2044 }
2045
2046 /// Lower the result values of a call into the
2047 /// appropriate copies out of appropriate physical registers.
2048 ///
2049 SDValue
2050 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2051                                    CallingConv::ID CallConv, bool isVarArg,
2052                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2053                                    SDLoc dl, SelectionDAG &DAG,
2054                                    SmallVectorImpl<SDValue> &InVals) const {
2055
2056   // Assign locations to each value returned by this call.
2057   SmallVector<CCValAssign, 16> RVLocs;
2058   bool Is64Bit = Subtarget->is64Bit();
2059   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2060                  *DAG.getContext());
2061   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2062
2063   // Copy all of the result registers out of their specified physreg.
2064   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2065     CCValAssign &VA = RVLocs[i];
2066     EVT CopyVT = VA.getValVT();
2067
2068     // If this is x86-64, and we disabled SSE, we can't return FP values
2069     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2070         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2071       report_fatal_error("SSE register return with SSE disabled");
2072     }
2073
2074     // If we prefer to use the value in xmm registers, copy it out as f80 and
2075     // use a truncate to move it from fp stack reg to xmm reg.
2076     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2077         isScalarFPTypeInSSEReg(VA.getValVT()))
2078       CopyVT = MVT::f80;
2079
2080     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2081                                CopyVT, InFlag).getValue(1);
2082     SDValue Val = Chain.getValue(0);
2083
2084     if (CopyVT != VA.getValVT())
2085       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2086                         // This truncation won't change the value.
2087                         DAG.getIntPtrConstant(1));
2088
2089     InFlag = Chain.getValue(2);
2090     InVals.push_back(Val);
2091   }
2092
2093   return Chain;
2094 }
2095
2096 //===----------------------------------------------------------------------===//
2097 //                C & StdCall & Fast Calling Convention implementation
2098 //===----------------------------------------------------------------------===//
2099 //  StdCall calling convention seems to be standard for many Windows' API
2100 //  routines and around. It differs from C calling convention just a little:
2101 //  callee should clean up the stack, not caller. Symbols should be also
2102 //  decorated in some fancy way :) It doesn't support any vector arguments.
2103 //  For info on fast calling convention see Fast Calling Convention (tail call)
2104 //  implementation LowerX86_32FastCCCallTo.
2105
2106 /// CallIsStructReturn - Determines whether a call uses struct return
2107 /// semantics.
2108 enum StructReturnType {
2109   NotStructReturn,
2110   RegStructReturn,
2111   StackStructReturn
2112 };
2113 static StructReturnType
2114 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2115   if (Outs.empty())
2116     return NotStructReturn;
2117
2118   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2119   if (!Flags.isSRet())
2120     return NotStructReturn;
2121   if (Flags.isInReg())
2122     return RegStructReturn;
2123   return StackStructReturn;
2124 }
2125
2126 /// Determines whether a function uses struct return semantics.
2127 static StructReturnType
2128 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2129   if (Ins.empty())
2130     return NotStructReturn;
2131
2132   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2133   if (!Flags.isSRet())
2134     return NotStructReturn;
2135   if (Flags.isInReg())
2136     return RegStructReturn;
2137   return StackStructReturn;
2138 }
2139
2140 /// Make a copy of an aggregate at address specified by "Src" to address
2141 /// "Dst" with size and alignment information specified by the specific
2142 /// parameter attribute. The copy will be passed as a byval function parameter.
2143 static SDValue
2144 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2145                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2146                           SDLoc dl) {
2147   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2148
2149   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2150                        /*isVolatile*/false, /*AlwaysInline=*/true,
2151                        /*isTailCall*/false,
2152                        MachinePointerInfo(), MachinePointerInfo());
2153 }
2154
2155 /// Return true if the calling convention is one that
2156 /// supports tail call optimization.
2157 static bool IsTailCallConvention(CallingConv::ID CC) {
2158   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2159           CC == CallingConv::HiPE);
2160 }
2161
2162 /// \brief Return true if the calling convention is a C calling convention.
2163 static bool IsCCallConvention(CallingConv::ID CC) {
2164   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2165           CC == CallingConv::X86_64_SysV);
2166 }
2167
2168 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2169   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2170     return false;
2171
2172   CallSite CS(CI);
2173   CallingConv::ID CalleeCC = CS.getCallingConv();
2174   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2175     return false;
2176
2177   return true;
2178 }
2179
2180 /// Return true if the function is being made into
2181 /// a tailcall target by changing its ABI.
2182 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2183                                    bool GuaranteedTailCallOpt) {
2184   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2185 }
2186
2187 SDValue
2188 X86TargetLowering::LowerMemArgument(SDValue Chain,
2189                                     CallingConv::ID CallConv,
2190                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2191                                     SDLoc dl, SelectionDAG &DAG,
2192                                     const CCValAssign &VA,
2193                                     MachineFrameInfo *MFI,
2194                                     unsigned i) const {
2195   // Create the nodes corresponding to a load from this parameter slot.
2196   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2197   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2198       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2199   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2200   EVT ValVT;
2201
2202   // If value is passed by pointer we have address passed instead of the value
2203   // itself.
2204   if (VA.getLocInfo() == CCValAssign::Indirect)
2205     ValVT = VA.getLocVT();
2206   else
2207     ValVT = VA.getValVT();
2208
2209   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2210   // changed with more analysis.
2211   // In case of tail call optimization mark all arguments mutable. Since they
2212   // could be overwritten by lowering of arguments in case of a tail call.
2213   if (Flags.isByVal()) {
2214     unsigned Bytes = Flags.getByValSize();
2215     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2216     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2217     return DAG.getFrameIndex(FI, getPointerTy());
2218   } else {
2219     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2220                                     VA.getLocMemOffset(), isImmutable);
2221     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2222     return DAG.getLoad(ValVT, dl, Chain, FIN,
2223                        MachinePointerInfo::getFixedStack(FI),
2224                        false, false, false, 0);
2225   }
2226 }
2227
2228 // FIXME: Get this from tablegen.
2229 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2230                                                 const X86Subtarget *Subtarget) {
2231   assert(Subtarget->is64Bit());
2232
2233   if (Subtarget->isCallingConvWin64(CallConv)) {
2234     static const MCPhysReg GPR64ArgRegsWin64[] = {
2235       X86::RCX, X86::RDX, X86::R8,  X86::R9
2236     };
2237     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2238   }
2239
2240   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2241     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2242   };
2243   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2244 }
2245
2246 // FIXME: Get this from tablegen.
2247 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2248                                                 CallingConv::ID CallConv,
2249                                                 const X86Subtarget *Subtarget) {
2250   assert(Subtarget->is64Bit());
2251   if (Subtarget->isCallingConvWin64(CallConv)) {
2252     // The XMM registers which might contain var arg parameters are shadowed
2253     // in their paired GPR.  So we only need to save the GPR to their home
2254     // slots.
2255     // TODO: __vectorcall will change this.
2256     return None;
2257   }
2258
2259   const Function *Fn = MF.getFunction();
2260   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2261   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2262          "SSE register cannot be used when SSE is disabled!");
2263   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2264       !Subtarget->hasSSE1())
2265     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2266     // registers.
2267     return None;
2268
2269   static const MCPhysReg XMMArgRegs64Bit[] = {
2270     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2271     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2272   };
2273   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2274 }
2275
2276 SDValue
2277 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2278                                         CallingConv::ID CallConv,
2279                                         bool isVarArg,
2280                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2281                                         SDLoc dl,
2282                                         SelectionDAG &DAG,
2283                                         SmallVectorImpl<SDValue> &InVals)
2284                                           const {
2285   MachineFunction &MF = DAG.getMachineFunction();
2286   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2287   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2288
2289   const Function* Fn = MF.getFunction();
2290   if (Fn->hasExternalLinkage() &&
2291       Subtarget->isTargetCygMing() &&
2292       Fn->getName() == "main")
2293     FuncInfo->setForceFramePointer(true);
2294
2295   MachineFrameInfo *MFI = MF.getFrameInfo();
2296   bool Is64Bit = Subtarget->is64Bit();
2297   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2298
2299   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2300          "Var args not supported with calling convention fastcc, ghc or hipe");
2301
2302   // Assign locations to all of the incoming arguments.
2303   SmallVector<CCValAssign, 16> ArgLocs;
2304   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2305
2306   // Allocate shadow area for Win64
2307   if (IsWin64)
2308     CCInfo.AllocateStack(32, 8);
2309
2310   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2311
2312   unsigned LastVal = ~0U;
2313   SDValue ArgValue;
2314   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2315     CCValAssign &VA = ArgLocs[i];
2316     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2317     // places.
2318     assert(VA.getValNo() != LastVal &&
2319            "Don't support value assigned to multiple locs yet");
2320     (void)LastVal;
2321     LastVal = VA.getValNo();
2322
2323     if (VA.isRegLoc()) {
2324       EVT RegVT = VA.getLocVT();
2325       const TargetRegisterClass *RC;
2326       if (RegVT == MVT::i32)
2327         RC = &X86::GR32RegClass;
2328       else if (Is64Bit && RegVT == MVT::i64)
2329         RC = &X86::GR64RegClass;
2330       else if (RegVT == MVT::f32)
2331         RC = &X86::FR32RegClass;
2332       else if (RegVT == MVT::f64)
2333         RC = &X86::FR64RegClass;
2334       else if (RegVT.is512BitVector())
2335         RC = &X86::VR512RegClass;
2336       else if (RegVT.is256BitVector())
2337         RC = &X86::VR256RegClass;
2338       else if (RegVT.is128BitVector())
2339         RC = &X86::VR128RegClass;
2340       else if (RegVT == MVT::x86mmx)
2341         RC = &X86::VR64RegClass;
2342       else if (RegVT == MVT::i1)
2343         RC = &X86::VK1RegClass;
2344       else if (RegVT == MVT::v8i1)
2345         RC = &X86::VK8RegClass;
2346       else if (RegVT == MVT::v16i1)
2347         RC = &X86::VK16RegClass;
2348       else if (RegVT == MVT::v32i1)
2349         RC = &X86::VK32RegClass;
2350       else if (RegVT == MVT::v64i1)
2351         RC = &X86::VK64RegClass;
2352       else
2353         llvm_unreachable("Unknown argument type!");
2354
2355       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2356       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2357
2358       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2359       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2360       // right size.
2361       if (VA.getLocInfo() == CCValAssign::SExt)
2362         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2363                                DAG.getValueType(VA.getValVT()));
2364       else if (VA.getLocInfo() == CCValAssign::ZExt)
2365         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2366                                DAG.getValueType(VA.getValVT()));
2367       else if (VA.getLocInfo() == CCValAssign::BCvt)
2368         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2369
2370       if (VA.isExtInLoc()) {
2371         // Handle MMX values passed in XMM regs.
2372         if (RegVT.isVector())
2373           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2374         else
2375           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2376       }
2377     } else {
2378       assert(VA.isMemLoc());
2379       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2380     }
2381
2382     // If value is passed via pointer - do a load.
2383     if (VA.getLocInfo() == CCValAssign::Indirect)
2384       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2385                              MachinePointerInfo(), false, false, false, 0);
2386
2387     InVals.push_back(ArgValue);
2388   }
2389
2390   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2391     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2392       // The x86-64 ABIs require that for returning structs by value we copy
2393       // the sret argument into %rax/%eax (depending on ABI) for the return.
2394       // Win32 requires us to put the sret argument to %eax as well.
2395       // Save the argument into a virtual register so that we can access it
2396       // from the return points.
2397       if (Ins[i].Flags.isSRet()) {
2398         unsigned Reg = FuncInfo->getSRetReturnReg();
2399         if (!Reg) {
2400           MVT PtrTy = getPointerTy();
2401           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2402           FuncInfo->setSRetReturnReg(Reg);
2403         }
2404         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2405         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2406         break;
2407       }
2408     }
2409   }
2410
2411   unsigned StackSize = CCInfo.getNextStackOffset();
2412   // Align stack specially for tail calls.
2413   if (FuncIsMadeTailCallSafe(CallConv,
2414                              MF.getTarget().Options.GuaranteedTailCallOpt))
2415     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2416
2417   // If the function takes variable number of arguments, make a frame index for
2418   // the start of the first vararg value... for expansion of llvm.va_start. We
2419   // can skip this if there are no va_start calls.
2420   if (MFI->hasVAStart() &&
2421       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2422                    CallConv != CallingConv::X86_ThisCall))) {
2423     FuncInfo->setVarArgsFrameIndex(
2424         MFI->CreateFixedObject(1, StackSize, true));
2425   }
2426
2427   MachineModuleInfo &MMI = MF.getMMI();
2428   const Function *WinEHParent = nullptr;
2429   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2430     WinEHParent = MMI.getWinEHParent(Fn);
2431   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2432   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2433
2434   // Figure out if XMM registers are in use.
2435   assert(!(MF.getTarget().Options.UseSoftFloat &&
2436            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2437          "SSE register cannot be used when SSE is disabled!");
2438
2439   // 64-bit calling conventions support varargs and register parameters, so we
2440   // have to do extra work to spill them in the prologue.
2441   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2442     // Find the first unallocated argument registers.
2443     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2444     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2445     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2446     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2447     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2448            "SSE register cannot be used when SSE is disabled!");
2449
2450     // Gather all the live in physical registers.
2451     SmallVector<SDValue, 6> LiveGPRs;
2452     SmallVector<SDValue, 8> LiveXMMRegs;
2453     SDValue ALVal;
2454     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2455       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2456       LiveGPRs.push_back(
2457           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2458     }
2459     if (!ArgXMMs.empty()) {
2460       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2461       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2462       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2463         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2464         LiveXMMRegs.push_back(
2465             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2466       }
2467     }
2468
2469     if (IsWin64) {
2470       // Get to the caller-allocated home save location.  Add 8 to account
2471       // for the return address.
2472       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2473       FuncInfo->setRegSaveFrameIndex(
2474           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2475       // Fixup to set vararg frame on shadow area (4 x i64).
2476       if (NumIntRegs < 4)
2477         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2478     } else {
2479       // For X86-64, if there are vararg parameters that are passed via
2480       // registers, then we must store them to their spots on the stack so
2481       // they may be loaded by deferencing the result of va_next.
2482       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2483       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2484       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2485           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2486     }
2487
2488     // Store the integer parameter registers.
2489     SmallVector<SDValue, 8> MemOps;
2490     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2491                                       getPointerTy());
2492     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2493     for (SDValue Val : LiveGPRs) {
2494       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2495                                 DAG.getIntPtrConstant(Offset));
2496       SDValue Store =
2497         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2498                      MachinePointerInfo::getFixedStack(
2499                        FuncInfo->getRegSaveFrameIndex(), Offset),
2500                      false, false, 0);
2501       MemOps.push_back(Store);
2502       Offset += 8;
2503     }
2504
2505     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2506       // Now store the XMM (fp + vector) parameter registers.
2507       SmallVector<SDValue, 12> SaveXMMOps;
2508       SaveXMMOps.push_back(Chain);
2509       SaveXMMOps.push_back(ALVal);
2510       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2511                              FuncInfo->getRegSaveFrameIndex()));
2512       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2513                              FuncInfo->getVarArgsFPOffset()));
2514       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2515                         LiveXMMRegs.end());
2516       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2517                                    MVT::Other, SaveXMMOps));
2518     }
2519
2520     if (!MemOps.empty())
2521       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2522   } else if (IsWinEHOutlined) {
2523     // Get to the caller-allocated home save location.  Add 8 to account
2524     // for the return address.
2525     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2526     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2527         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2528
2529     MMI.getWinEHFuncInfo(Fn)
2530         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2531         FuncInfo->getRegSaveFrameIndex();
2532
2533     // Store the second integer parameter (rdx) into rsp+16 relative to the
2534     // stack pointer at the entry of the function.
2535     SDValue RSFIN =
2536         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2537     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2538     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2539     Chain = DAG.getStore(
2540         Val.getValue(1), dl, Val, RSFIN,
2541         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2542         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2543   }
2544
2545   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2546     // Find the largest legal vector type.
2547     MVT VecVT = MVT::Other;
2548     // FIXME: Only some x86_32 calling conventions support AVX512.
2549     if (Subtarget->hasAVX512() &&
2550         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2551                      CallConv == CallingConv::Intel_OCL_BI)))
2552       VecVT = MVT::v16f32;
2553     else if (Subtarget->hasAVX())
2554       VecVT = MVT::v8f32;
2555     else if (Subtarget->hasSSE2())
2556       VecVT = MVT::v4f32;
2557
2558     // We forward some GPRs and some vector types.
2559     SmallVector<MVT, 2> RegParmTypes;
2560     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2561     RegParmTypes.push_back(IntVT);
2562     if (VecVT != MVT::Other)
2563       RegParmTypes.push_back(VecVT);
2564
2565     // Compute the set of forwarded registers. The rest are scratch.
2566     SmallVectorImpl<ForwardedRegister> &Forwards =
2567         FuncInfo->getForwardedMustTailRegParms();
2568     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2569
2570     // Conservatively forward AL on x86_64, since it might be used for varargs.
2571     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2572       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2573       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2574     }
2575
2576     // Copy all forwards from physical to virtual registers.
2577     for (ForwardedRegister &F : Forwards) {
2578       // FIXME: Can we use a less constrained schedule?
2579       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2580       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2581       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2582     }
2583   }
2584
2585   // Some CCs need callee pop.
2586   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2587                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2588     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2589   } else {
2590     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2591     // If this is an sret function, the return should pop the hidden pointer.
2592     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2593         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2594         argsAreStructReturn(Ins) == StackStructReturn)
2595       FuncInfo->setBytesToPopOnReturn(4);
2596   }
2597
2598   if (!Is64Bit) {
2599     // RegSaveFrameIndex is X86-64 only.
2600     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2601     if (CallConv == CallingConv::X86_FastCall ||
2602         CallConv == CallingConv::X86_ThisCall)
2603       // fastcc functions can't have varargs.
2604       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2605   }
2606
2607   FuncInfo->setArgumentStackSize(StackSize);
2608
2609   if (IsWinEHParent) {
2610     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2611     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2612     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2613     SDValue Neg2 = DAG.getConstant(-2, MVT::i64);
2614     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2615                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2616                          /*isVolatile=*/true,
2617                          /*isNonTemporal=*/false, /*Alignment=*/0);
2618   }
2619
2620   return Chain;
2621 }
2622
2623 SDValue
2624 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2625                                     SDValue StackPtr, SDValue Arg,
2626                                     SDLoc dl, SelectionDAG &DAG,
2627                                     const CCValAssign &VA,
2628                                     ISD::ArgFlagsTy Flags) const {
2629   unsigned LocMemOffset = VA.getLocMemOffset();
2630   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2631   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2632   if (Flags.isByVal())
2633     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2634
2635   return DAG.getStore(Chain, dl, Arg, PtrOff,
2636                       MachinePointerInfo::getStack(LocMemOffset),
2637                       false, false, 0);
2638 }
2639
2640 /// Emit a load of return address if tail call
2641 /// optimization is performed and it is required.
2642 SDValue
2643 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2644                                            SDValue &OutRetAddr, SDValue Chain,
2645                                            bool IsTailCall, bool Is64Bit,
2646                                            int FPDiff, SDLoc dl) const {
2647   // Adjust the Return address stack slot.
2648   EVT VT = getPointerTy();
2649   OutRetAddr = getReturnAddressFrameIndex(DAG);
2650
2651   // Load the "old" Return address.
2652   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2653                            false, false, false, 0);
2654   return SDValue(OutRetAddr.getNode(), 1);
2655 }
2656
2657 /// Emit a store of the return address if tail call
2658 /// optimization is performed and it is required (FPDiff!=0).
2659 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2660                                         SDValue Chain, SDValue RetAddrFrIdx,
2661                                         EVT PtrVT, unsigned SlotSize,
2662                                         int FPDiff, SDLoc dl) {
2663   // Store the return address to the appropriate stack slot.
2664   if (!FPDiff) return Chain;
2665   // Calculate the new stack slot for the return address.
2666   int NewReturnAddrFI =
2667     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2668                                          false);
2669   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2670   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2671                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2672                        false, false, 0);
2673   return Chain;
2674 }
2675
2676 SDValue
2677 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2678                              SmallVectorImpl<SDValue> &InVals) const {
2679   SelectionDAG &DAG                     = CLI.DAG;
2680   SDLoc &dl                             = CLI.DL;
2681   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2682   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2683   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2684   SDValue Chain                         = CLI.Chain;
2685   SDValue Callee                        = CLI.Callee;
2686   CallingConv::ID CallConv              = CLI.CallConv;
2687   bool &isTailCall                      = CLI.IsTailCall;
2688   bool isVarArg                         = CLI.IsVarArg;
2689
2690   MachineFunction &MF = DAG.getMachineFunction();
2691   bool Is64Bit        = Subtarget->is64Bit();
2692   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2693   StructReturnType SR = callIsStructReturn(Outs);
2694   bool IsSibcall      = false;
2695   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2696
2697   if (MF.getTarget().Options.DisableTailCalls)
2698     isTailCall = false;
2699
2700   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2701   if (IsMustTail) {
2702     // Force this to be a tail call.  The verifier rules are enough to ensure
2703     // that we can lower this successfully without moving the return address
2704     // around.
2705     isTailCall = true;
2706   } else if (isTailCall) {
2707     // Check if it's really possible to do a tail call.
2708     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2709                     isVarArg, SR != NotStructReturn,
2710                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2711                     Outs, OutVals, Ins, DAG);
2712
2713     // Sibcalls are automatically detected tailcalls which do not require
2714     // ABI changes.
2715     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2716       IsSibcall = true;
2717
2718     if (isTailCall)
2719       ++NumTailCalls;
2720   }
2721
2722   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2723          "Var args not supported with calling convention fastcc, ghc or hipe");
2724
2725   // Analyze operands of the call, assigning locations to each operand.
2726   SmallVector<CCValAssign, 16> ArgLocs;
2727   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2728
2729   // Allocate shadow area for Win64
2730   if (IsWin64)
2731     CCInfo.AllocateStack(32, 8);
2732
2733   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2734
2735   // Get a count of how many bytes are to be pushed on the stack.
2736   unsigned NumBytes = CCInfo.getNextStackOffset();
2737   if (IsSibcall)
2738     // This is a sibcall. The memory operands are available in caller's
2739     // own caller's stack.
2740     NumBytes = 0;
2741   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2742            IsTailCallConvention(CallConv))
2743     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2744
2745   int FPDiff = 0;
2746   if (isTailCall && !IsSibcall && !IsMustTail) {
2747     // Lower arguments at fp - stackoffset + fpdiff.
2748     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2749
2750     FPDiff = NumBytesCallerPushed - NumBytes;
2751
2752     // Set the delta of movement of the returnaddr stackslot.
2753     // But only set if delta is greater than previous delta.
2754     if (FPDiff < X86Info->getTCReturnAddrDelta())
2755       X86Info->setTCReturnAddrDelta(FPDiff);
2756   }
2757
2758   unsigned NumBytesToPush = NumBytes;
2759   unsigned NumBytesToPop = NumBytes;
2760
2761   // If we have an inalloca argument, all stack space has already been allocated
2762   // for us and be right at the top of the stack.  We don't support multiple
2763   // arguments passed in memory when using inalloca.
2764   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2765     NumBytesToPush = 0;
2766     if (!ArgLocs.back().isMemLoc())
2767       report_fatal_error("cannot use inalloca attribute on a register "
2768                          "parameter");
2769     if (ArgLocs.back().getLocMemOffset() != 0)
2770       report_fatal_error("any parameter with the inalloca attribute must be "
2771                          "the only memory argument");
2772   }
2773
2774   if (!IsSibcall)
2775     Chain = DAG.getCALLSEQ_START(
2776         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2777
2778   SDValue RetAddrFrIdx;
2779   // Load return address for tail calls.
2780   if (isTailCall && FPDiff)
2781     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2782                                     Is64Bit, FPDiff, dl);
2783
2784   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2785   SmallVector<SDValue, 8> MemOpChains;
2786   SDValue StackPtr;
2787
2788   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2789   // of tail call optimization arguments are handle later.
2790   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2791   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2792     // Skip inalloca arguments, they have already been written.
2793     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2794     if (Flags.isInAlloca())
2795       continue;
2796
2797     CCValAssign &VA = ArgLocs[i];
2798     EVT RegVT = VA.getLocVT();
2799     SDValue Arg = OutVals[i];
2800     bool isByVal = Flags.isByVal();
2801
2802     // Promote the value if needed.
2803     switch (VA.getLocInfo()) {
2804     default: llvm_unreachable("Unknown loc info!");
2805     case CCValAssign::Full: break;
2806     case CCValAssign::SExt:
2807       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2808       break;
2809     case CCValAssign::ZExt:
2810       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2811       break;
2812     case CCValAssign::AExt:
2813       if (RegVT.is128BitVector()) {
2814         // Special case: passing MMX values in XMM registers.
2815         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2816         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2817         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2818       } else
2819         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2820       break;
2821     case CCValAssign::BCvt:
2822       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2823       break;
2824     case CCValAssign::Indirect: {
2825       // Store the argument.
2826       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2827       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2828       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2829                            MachinePointerInfo::getFixedStack(FI),
2830                            false, false, 0);
2831       Arg = SpillSlot;
2832       break;
2833     }
2834     }
2835
2836     if (VA.isRegLoc()) {
2837       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2838       if (isVarArg && IsWin64) {
2839         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2840         // shadow reg if callee is a varargs function.
2841         unsigned ShadowReg = 0;
2842         switch (VA.getLocReg()) {
2843         case X86::XMM0: ShadowReg = X86::RCX; break;
2844         case X86::XMM1: ShadowReg = X86::RDX; break;
2845         case X86::XMM2: ShadowReg = X86::R8; break;
2846         case X86::XMM3: ShadowReg = X86::R9; break;
2847         }
2848         if (ShadowReg)
2849           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2850       }
2851     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2852       assert(VA.isMemLoc());
2853       if (!StackPtr.getNode())
2854         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2855                                       getPointerTy());
2856       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2857                                              dl, DAG, VA, Flags));
2858     }
2859   }
2860
2861   if (!MemOpChains.empty())
2862     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2863
2864   if (Subtarget->isPICStyleGOT()) {
2865     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2866     // GOT pointer.
2867     if (!isTailCall) {
2868       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2869                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2870     } else {
2871       // If we are tail calling and generating PIC/GOT style code load the
2872       // address of the callee into ECX. The value in ecx is used as target of
2873       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2874       // for tail calls on PIC/GOT architectures. Normally we would just put the
2875       // address of GOT into ebx and then call target@PLT. But for tail calls
2876       // ebx would be restored (since ebx is callee saved) before jumping to the
2877       // target@PLT.
2878
2879       // Note: The actual moving to ECX is done further down.
2880       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2881       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2882           !G->getGlobal()->hasProtectedVisibility())
2883         Callee = LowerGlobalAddress(Callee, DAG);
2884       else if (isa<ExternalSymbolSDNode>(Callee))
2885         Callee = LowerExternalSymbol(Callee, DAG);
2886     }
2887   }
2888
2889   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2890     // From AMD64 ABI document:
2891     // For calls that may call functions that use varargs or stdargs
2892     // (prototype-less calls or calls to functions containing ellipsis (...) in
2893     // the declaration) %al is used as hidden argument to specify the number
2894     // of SSE registers used. The contents of %al do not need to match exactly
2895     // the number of registers, but must be an ubound on the number of SSE
2896     // registers used and is in the range 0 - 8 inclusive.
2897
2898     // Count the number of XMM registers allocated.
2899     static const MCPhysReg XMMArgRegs[] = {
2900       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2901       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2902     };
2903     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2904     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2905            && "SSE registers cannot be used when SSE is disabled");
2906
2907     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2908                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2909   }
2910
2911   if (isVarArg && IsMustTail) {
2912     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2913     for (const auto &F : Forwards) {
2914       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2915       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2916     }
2917   }
2918
2919   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2920   // don't need this because the eligibility check rejects calls that require
2921   // shuffling arguments passed in memory.
2922   if (!IsSibcall && isTailCall) {
2923     // Force all the incoming stack arguments to be loaded from the stack
2924     // before any new outgoing arguments are stored to the stack, because the
2925     // outgoing stack slots may alias the incoming argument stack slots, and
2926     // the alias isn't otherwise explicit. This is slightly more conservative
2927     // than necessary, because it means that each store effectively depends
2928     // on every argument instead of just those arguments it would clobber.
2929     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2930
2931     SmallVector<SDValue, 8> MemOpChains2;
2932     SDValue FIN;
2933     int FI = 0;
2934     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2935       CCValAssign &VA = ArgLocs[i];
2936       if (VA.isRegLoc())
2937         continue;
2938       assert(VA.isMemLoc());
2939       SDValue Arg = OutVals[i];
2940       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2941       // Skip inalloca arguments.  They don't require any work.
2942       if (Flags.isInAlloca())
2943         continue;
2944       // Create frame index.
2945       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2946       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2947       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2948       FIN = DAG.getFrameIndex(FI, getPointerTy());
2949
2950       if (Flags.isByVal()) {
2951         // Copy relative to framepointer.
2952         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2953         if (!StackPtr.getNode())
2954           StackPtr = DAG.getCopyFromReg(Chain, dl,
2955                                         RegInfo->getStackRegister(),
2956                                         getPointerTy());
2957         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2958
2959         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2960                                                          ArgChain,
2961                                                          Flags, DAG, dl));
2962       } else {
2963         // Store relative to framepointer.
2964         MemOpChains2.push_back(
2965           DAG.getStore(ArgChain, dl, Arg, FIN,
2966                        MachinePointerInfo::getFixedStack(FI),
2967                        false, false, 0));
2968       }
2969     }
2970
2971     if (!MemOpChains2.empty())
2972       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2973
2974     // Store the return address to the appropriate stack slot.
2975     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2976                                      getPointerTy(), RegInfo->getSlotSize(),
2977                                      FPDiff, dl);
2978   }
2979
2980   // Build a sequence of copy-to-reg nodes chained together with token chain
2981   // and flag operands which copy the outgoing args into registers.
2982   SDValue InFlag;
2983   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2984     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2985                              RegsToPass[i].second, InFlag);
2986     InFlag = Chain.getValue(1);
2987   }
2988
2989   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2990     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2991     // In the 64-bit large code model, we have to make all calls
2992     // through a register, since the call instruction's 32-bit
2993     // pc-relative offset may not be large enough to hold the whole
2994     // address.
2995   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
2996     // If the callee is a GlobalAddress node (quite common, every direct call
2997     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2998     // it.
2999     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3000
3001     // We should use extra load for direct calls to dllimported functions in
3002     // non-JIT mode.
3003     const GlobalValue *GV = G->getGlobal();
3004     if (!GV->hasDLLImportStorageClass()) {
3005       unsigned char OpFlags = 0;
3006       bool ExtraLoad = false;
3007       unsigned WrapperKind = ISD::DELETED_NODE;
3008
3009       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3010       // external symbols most go through the PLT in PIC mode.  If the symbol
3011       // has hidden or protected visibility, or if it is static or local, then
3012       // we don't need to use the PLT - we can directly call it.
3013       if (Subtarget->isTargetELF() &&
3014           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3015           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3016         OpFlags = X86II::MO_PLT;
3017       } else if (Subtarget->isPICStyleStubAny() &&
3018                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3019                  (!Subtarget->getTargetTriple().isMacOSX() ||
3020                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3021         // PC-relative references to external symbols should go through $stub,
3022         // unless we're building with the leopard linker or later, which
3023         // automatically synthesizes these stubs.
3024         OpFlags = X86II::MO_DARWIN_STUB;
3025       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3026                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3027         // If the function is marked as non-lazy, generate an indirect call
3028         // which loads from the GOT directly. This avoids runtime overhead
3029         // at the cost of eager binding (and one extra byte of encoding).
3030         OpFlags = X86II::MO_GOTPCREL;
3031         WrapperKind = X86ISD::WrapperRIP;
3032         ExtraLoad = true;
3033       }
3034
3035       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3036                                           G->getOffset(), OpFlags);
3037
3038       // Add a wrapper if needed.
3039       if (WrapperKind != ISD::DELETED_NODE)
3040         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3041       // Add extra indirection if needed.
3042       if (ExtraLoad)
3043         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3044                              MachinePointerInfo::getGOT(),
3045                              false, false, false, 0);
3046     }
3047   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3048     unsigned char OpFlags = 0;
3049
3050     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3051     // external symbols should go through the PLT.
3052     if (Subtarget->isTargetELF() &&
3053         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3054       OpFlags = X86II::MO_PLT;
3055     } else if (Subtarget->isPICStyleStubAny() &&
3056                (!Subtarget->getTargetTriple().isMacOSX() ||
3057                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3058       // PC-relative references to external symbols should go through $stub,
3059       // unless we're building with the leopard linker or later, which
3060       // automatically synthesizes these stubs.
3061       OpFlags = X86II::MO_DARWIN_STUB;
3062     }
3063
3064     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3065                                          OpFlags);
3066   } else if (Subtarget->isTarget64BitILP32() &&
3067              Callee->getValueType(0) == MVT::i32) {
3068     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3069     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3070   }
3071
3072   // Returns a chain & a flag for retval copy to use.
3073   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3074   SmallVector<SDValue, 8> Ops;
3075
3076   if (!IsSibcall && isTailCall) {
3077     Chain = DAG.getCALLSEQ_END(Chain,
3078                                DAG.getIntPtrConstant(NumBytesToPop, true),
3079                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3080     InFlag = Chain.getValue(1);
3081   }
3082
3083   Ops.push_back(Chain);
3084   Ops.push_back(Callee);
3085
3086   if (isTailCall)
3087     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3088
3089   // Add argument registers to the end of the list so that they are known live
3090   // into the call.
3091   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3092     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3093                                   RegsToPass[i].second.getValueType()));
3094
3095   // Add a register mask operand representing the call-preserved registers.
3096   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3097   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3098   assert(Mask && "Missing call preserved mask for calling convention");
3099   Ops.push_back(DAG.getRegisterMask(Mask));
3100
3101   if (InFlag.getNode())
3102     Ops.push_back(InFlag);
3103
3104   if (isTailCall) {
3105     // We used to do:
3106     //// If this is the first return lowered for this function, add the regs
3107     //// to the liveout set for the function.
3108     // This isn't right, although it's probably harmless on x86; liveouts
3109     // should be computed from returns not tail calls.  Consider a void
3110     // function making a tail call to a function returning int.
3111     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3112   }
3113
3114   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3115   InFlag = Chain.getValue(1);
3116
3117   // Create the CALLSEQ_END node.
3118   unsigned NumBytesForCalleeToPop;
3119   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3120                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3121     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3122   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3123            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3124            SR == StackStructReturn)
3125     // If this is a call to a struct-return function, the callee
3126     // pops the hidden struct pointer, so we have to push it back.
3127     // This is common for Darwin/X86, Linux & Mingw32 targets.
3128     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3129     NumBytesForCalleeToPop = 4;
3130   else
3131     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3132
3133   // Returns a flag for retval copy to use.
3134   if (!IsSibcall) {
3135     Chain = DAG.getCALLSEQ_END(Chain,
3136                                DAG.getIntPtrConstant(NumBytesToPop, true),
3137                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3138                                                      true),
3139                                InFlag, dl);
3140     InFlag = Chain.getValue(1);
3141   }
3142
3143   // Handle result values, copying them out of physregs into vregs that we
3144   // return.
3145   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3146                          Ins, dl, DAG, InVals);
3147 }
3148
3149 //===----------------------------------------------------------------------===//
3150 //                Fast Calling Convention (tail call) implementation
3151 //===----------------------------------------------------------------------===//
3152
3153 //  Like std call, callee cleans arguments, convention except that ECX is
3154 //  reserved for storing the tail called function address. Only 2 registers are
3155 //  free for argument passing (inreg). Tail call optimization is performed
3156 //  provided:
3157 //                * tailcallopt is enabled
3158 //                * caller/callee are fastcc
3159 //  On X86_64 architecture with GOT-style position independent code only local
3160 //  (within module) calls are supported at the moment.
3161 //  To keep the stack aligned according to platform abi the function
3162 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3163 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3164 //  If a tail called function callee has more arguments than the caller the
3165 //  caller needs to make sure that there is room to move the RETADDR to. This is
3166 //  achieved by reserving an area the size of the argument delta right after the
3167 //  original RETADDR, but before the saved framepointer or the spilled registers
3168 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3169 //  stack layout:
3170 //    arg1
3171 //    arg2
3172 //    RETADDR
3173 //    [ new RETADDR
3174 //      move area ]
3175 //    (possible EBP)
3176 //    ESI
3177 //    EDI
3178 //    local1 ..
3179
3180 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3181 /// for a 16 byte align requirement.
3182 unsigned
3183 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3184                                                SelectionDAG& DAG) const {
3185   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3186   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3187   unsigned StackAlignment = TFI.getStackAlignment();
3188   uint64_t AlignMask = StackAlignment - 1;
3189   int64_t Offset = StackSize;
3190   unsigned SlotSize = RegInfo->getSlotSize();
3191   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3192     // Number smaller than 12 so just add the difference.
3193     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3194   } else {
3195     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3196     Offset = ((~AlignMask) & Offset) + StackAlignment +
3197       (StackAlignment-SlotSize);
3198   }
3199   return Offset;
3200 }
3201
3202 /// MatchingStackOffset - Return true if the given stack call argument is
3203 /// already available in the same position (relatively) of the caller's
3204 /// incoming argument stack.
3205 static
3206 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3207                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3208                          const X86InstrInfo *TII) {
3209   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3210   int FI = INT_MAX;
3211   if (Arg.getOpcode() == ISD::CopyFromReg) {
3212     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3213     if (!TargetRegisterInfo::isVirtualRegister(VR))
3214       return false;
3215     MachineInstr *Def = MRI->getVRegDef(VR);
3216     if (!Def)
3217       return false;
3218     if (!Flags.isByVal()) {
3219       if (!TII->isLoadFromStackSlot(Def, FI))
3220         return false;
3221     } else {
3222       unsigned Opcode = Def->getOpcode();
3223       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3224            Opcode == X86::LEA64_32r) &&
3225           Def->getOperand(1).isFI()) {
3226         FI = Def->getOperand(1).getIndex();
3227         Bytes = Flags.getByValSize();
3228       } else
3229         return false;
3230     }
3231   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3232     if (Flags.isByVal())
3233       // ByVal argument is passed in as a pointer but it's now being
3234       // dereferenced. e.g.
3235       // define @foo(%struct.X* %A) {
3236       //   tail call @bar(%struct.X* byval %A)
3237       // }
3238       return false;
3239     SDValue Ptr = Ld->getBasePtr();
3240     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3241     if (!FINode)
3242       return false;
3243     FI = FINode->getIndex();
3244   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3245     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3246     FI = FINode->getIndex();
3247     Bytes = Flags.getByValSize();
3248   } else
3249     return false;
3250
3251   assert(FI != INT_MAX);
3252   if (!MFI->isFixedObjectIndex(FI))
3253     return false;
3254   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3255 }
3256
3257 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3258 /// for tail call optimization. Targets which want to do tail call
3259 /// optimization should implement this function.
3260 bool
3261 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3262                                                      CallingConv::ID CalleeCC,
3263                                                      bool isVarArg,
3264                                                      bool isCalleeStructRet,
3265                                                      bool isCallerStructRet,
3266                                                      Type *RetTy,
3267                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3268                                     const SmallVectorImpl<SDValue> &OutVals,
3269                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3270                                                      SelectionDAG &DAG) const {
3271   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3272     return false;
3273
3274   // If -tailcallopt is specified, make fastcc functions tail-callable.
3275   const MachineFunction &MF = DAG.getMachineFunction();
3276   const Function *CallerF = MF.getFunction();
3277
3278   // If the function return type is x86_fp80 and the callee return type is not,
3279   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3280   // perform a tailcall optimization here.
3281   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3282     return false;
3283
3284   CallingConv::ID CallerCC = CallerF->getCallingConv();
3285   bool CCMatch = CallerCC == CalleeCC;
3286   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3287   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3288
3289   // Win64 functions have extra shadow space for argument homing. Don't do the
3290   // sibcall if the caller and callee have mismatched expectations for this
3291   // space.
3292   if (IsCalleeWin64 != IsCallerWin64)
3293     return false;
3294
3295   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3296     if (IsTailCallConvention(CalleeCC) && CCMatch)
3297       return true;
3298     return false;
3299   }
3300
3301   // Look for obvious safe cases to perform tail call optimization that do not
3302   // require ABI changes. This is what gcc calls sibcall.
3303
3304   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3305   // emit a special epilogue.
3306   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3307   if (RegInfo->needsStackRealignment(MF))
3308     return false;
3309
3310   // Also avoid sibcall optimization if either caller or callee uses struct
3311   // return semantics.
3312   if (isCalleeStructRet || isCallerStructRet)
3313     return false;
3314
3315   // An stdcall/thiscall caller is expected to clean up its arguments; the
3316   // callee isn't going to do that.
3317   // FIXME: this is more restrictive than needed. We could produce a tailcall
3318   // when the stack adjustment matches. For example, with a thiscall that takes
3319   // only one argument.
3320   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3321                    CallerCC == CallingConv::X86_ThisCall))
3322     return false;
3323
3324   // Do not sibcall optimize vararg calls unless all arguments are passed via
3325   // registers.
3326   if (isVarArg && !Outs.empty()) {
3327
3328     // Optimizing for varargs on Win64 is unlikely to be safe without
3329     // additional testing.
3330     if (IsCalleeWin64 || IsCallerWin64)
3331       return false;
3332
3333     SmallVector<CCValAssign, 16> ArgLocs;
3334     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3335                    *DAG.getContext());
3336
3337     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3338     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3339       if (!ArgLocs[i].isRegLoc())
3340         return false;
3341   }
3342
3343   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3344   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3345   // this into a sibcall.
3346   bool Unused = false;
3347   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3348     if (!Ins[i].Used) {
3349       Unused = true;
3350       break;
3351     }
3352   }
3353   if (Unused) {
3354     SmallVector<CCValAssign, 16> RVLocs;
3355     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3356                    *DAG.getContext());
3357     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3358     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3359       CCValAssign &VA = RVLocs[i];
3360       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3361         return false;
3362     }
3363   }
3364
3365   // If the calling conventions do not match, then we'd better make sure the
3366   // results are returned in the same way as what the caller expects.
3367   if (!CCMatch) {
3368     SmallVector<CCValAssign, 16> RVLocs1;
3369     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3370                     *DAG.getContext());
3371     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3372
3373     SmallVector<CCValAssign, 16> RVLocs2;
3374     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3375                     *DAG.getContext());
3376     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3377
3378     if (RVLocs1.size() != RVLocs2.size())
3379       return false;
3380     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3381       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3382         return false;
3383       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3384         return false;
3385       if (RVLocs1[i].isRegLoc()) {
3386         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3387           return false;
3388       } else {
3389         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3390           return false;
3391       }
3392     }
3393   }
3394
3395   // If the callee takes no arguments then go on to check the results of the
3396   // call.
3397   if (!Outs.empty()) {
3398     // Check if stack adjustment is needed. For now, do not do this if any
3399     // argument is passed on the stack.
3400     SmallVector<CCValAssign, 16> ArgLocs;
3401     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3402                    *DAG.getContext());
3403
3404     // Allocate shadow area for Win64
3405     if (IsCalleeWin64)
3406       CCInfo.AllocateStack(32, 8);
3407
3408     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3409     if (CCInfo.getNextStackOffset()) {
3410       MachineFunction &MF = DAG.getMachineFunction();
3411       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3412         return false;
3413
3414       // Check if the arguments are already laid out in the right way as
3415       // the caller's fixed stack objects.
3416       MachineFrameInfo *MFI = MF.getFrameInfo();
3417       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3418       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3419       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3420         CCValAssign &VA = ArgLocs[i];
3421         SDValue Arg = OutVals[i];
3422         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3423         if (VA.getLocInfo() == CCValAssign::Indirect)
3424           return false;
3425         if (!VA.isRegLoc()) {
3426           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3427                                    MFI, MRI, TII))
3428             return false;
3429         }
3430       }
3431     }
3432
3433     // If the tailcall address may be in a register, then make sure it's
3434     // possible to register allocate for it. In 32-bit, the call address can
3435     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3436     // callee-saved registers are restored. These happen to be the same
3437     // registers used to pass 'inreg' arguments so watch out for those.
3438     if (!Subtarget->is64Bit() &&
3439         ((!isa<GlobalAddressSDNode>(Callee) &&
3440           !isa<ExternalSymbolSDNode>(Callee)) ||
3441          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3442       unsigned NumInRegs = 0;
3443       // In PIC we need an extra register to formulate the address computation
3444       // for the callee.
3445       unsigned MaxInRegs =
3446         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3447
3448       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3449         CCValAssign &VA = ArgLocs[i];
3450         if (!VA.isRegLoc())
3451           continue;
3452         unsigned Reg = VA.getLocReg();
3453         switch (Reg) {
3454         default: break;
3455         case X86::EAX: case X86::EDX: case X86::ECX:
3456           if (++NumInRegs == MaxInRegs)
3457             return false;
3458           break;
3459         }
3460       }
3461     }
3462   }
3463
3464   return true;
3465 }
3466
3467 FastISel *
3468 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3469                                   const TargetLibraryInfo *libInfo) const {
3470   return X86::createFastISel(funcInfo, libInfo);
3471 }
3472
3473 //===----------------------------------------------------------------------===//
3474 //                           Other Lowering Hooks
3475 //===----------------------------------------------------------------------===//
3476
3477 static bool MayFoldLoad(SDValue Op) {
3478   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3479 }
3480
3481 static bool MayFoldIntoStore(SDValue Op) {
3482   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3483 }
3484
3485 static bool isTargetShuffle(unsigned Opcode) {
3486   switch(Opcode) {
3487   default: return false;
3488   case X86ISD::BLENDI:
3489   case X86ISD::PSHUFB:
3490   case X86ISD::PSHUFD:
3491   case X86ISD::PSHUFHW:
3492   case X86ISD::PSHUFLW:
3493   case X86ISD::SHUFP:
3494   case X86ISD::PALIGNR:
3495   case X86ISD::MOVLHPS:
3496   case X86ISD::MOVLHPD:
3497   case X86ISD::MOVHLPS:
3498   case X86ISD::MOVLPS:
3499   case X86ISD::MOVLPD:
3500   case X86ISD::MOVSHDUP:
3501   case X86ISD::MOVSLDUP:
3502   case X86ISD::MOVDDUP:
3503   case X86ISD::MOVSS:
3504   case X86ISD::MOVSD:
3505   case X86ISD::UNPCKL:
3506   case X86ISD::UNPCKH:
3507   case X86ISD::VPERMILPI:
3508   case X86ISD::VPERM2X128:
3509   case X86ISD::VPERMI:
3510     return true;
3511   }
3512 }
3513
3514 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3515                                     SDValue V1, unsigned TargetMask,
3516                                     SelectionDAG &DAG) {
3517   switch(Opc) {
3518   default: llvm_unreachable("Unknown x86 shuffle node");
3519   case X86ISD::PSHUFD:
3520   case X86ISD::PSHUFHW:
3521   case X86ISD::PSHUFLW:
3522   case X86ISD::VPERMILPI:
3523   case X86ISD::VPERMI:
3524     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3525   }
3526 }
3527
3528 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3529                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3530   switch(Opc) {
3531   default: llvm_unreachable("Unknown x86 shuffle node");
3532   case X86ISD::MOVLHPS:
3533   case X86ISD::MOVLHPD:
3534   case X86ISD::MOVHLPS:
3535   case X86ISD::MOVLPS:
3536   case X86ISD::MOVLPD:
3537   case X86ISD::MOVSS:
3538   case X86ISD::MOVSD:
3539   case X86ISD::UNPCKL:
3540   case X86ISD::UNPCKH:
3541     return DAG.getNode(Opc, dl, VT, V1, V2);
3542   }
3543 }
3544
3545 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3546   MachineFunction &MF = DAG.getMachineFunction();
3547   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3548   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3549   int ReturnAddrIndex = FuncInfo->getRAIndex();
3550
3551   if (ReturnAddrIndex == 0) {
3552     // Set up a frame object for the return address.
3553     unsigned SlotSize = RegInfo->getSlotSize();
3554     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3555                                                            -(int64_t)SlotSize,
3556                                                            false);
3557     FuncInfo->setRAIndex(ReturnAddrIndex);
3558   }
3559
3560   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3561 }
3562
3563 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3564                                        bool hasSymbolicDisplacement) {
3565   // Offset should fit into 32 bit immediate field.
3566   if (!isInt<32>(Offset))
3567     return false;
3568
3569   // If we don't have a symbolic displacement - we don't have any extra
3570   // restrictions.
3571   if (!hasSymbolicDisplacement)
3572     return true;
3573
3574   // FIXME: Some tweaks might be needed for medium code model.
3575   if (M != CodeModel::Small && M != CodeModel::Kernel)
3576     return false;
3577
3578   // For small code model we assume that latest object is 16MB before end of 31
3579   // bits boundary. We may also accept pretty large negative constants knowing
3580   // that all objects are in the positive half of address space.
3581   if (M == CodeModel::Small && Offset < 16*1024*1024)
3582     return true;
3583
3584   // For kernel code model we know that all object resist in the negative half
3585   // of 32bits address space. We may not accept negative offsets, since they may
3586   // be just off and we may accept pretty large positive ones.
3587   if (M == CodeModel::Kernel && Offset >= 0)
3588     return true;
3589
3590   return false;
3591 }
3592
3593 /// isCalleePop - Determines whether the callee is required to pop its
3594 /// own arguments. Callee pop is necessary to support tail calls.
3595 bool X86::isCalleePop(CallingConv::ID CallingConv,
3596                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3597   switch (CallingConv) {
3598   default:
3599     return false;
3600   case CallingConv::X86_StdCall:
3601   case CallingConv::X86_FastCall:
3602   case CallingConv::X86_ThisCall:
3603     return !is64Bit;
3604   case CallingConv::Fast:
3605   case CallingConv::GHC:
3606   case CallingConv::HiPE:
3607     if (IsVarArg)
3608       return false;
3609     return TailCallOpt;
3610   }
3611 }
3612
3613 /// \brief Return true if the condition is an unsigned comparison operation.
3614 static bool isX86CCUnsigned(unsigned X86CC) {
3615   switch (X86CC) {
3616   default: llvm_unreachable("Invalid integer condition!");
3617   case X86::COND_E:     return true;
3618   case X86::COND_G:     return false;
3619   case X86::COND_GE:    return false;
3620   case X86::COND_L:     return false;
3621   case X86::COND_LE:    return false;
3622   case X86::COND_NE:    return true;
3623   case X86::COND_B:     return true;
3624   case X86::COND_A:     return true;
3625   case X86::COND_BE:    return true;
3626   case X86::COND_AE:    return true;
3627   }
3628   llvm_unreachable("covered switch fell through?!");
3629 }
3630
3631 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3632 /// specific condition code, returning the condition code and the LHS/RHS of the
3633 /// comparison to make.
3634 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3635                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3636   if (!isFP) {
3637     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3638       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3639         // X > -1   -> X == 0, jump !sign.
3640         RHS = DAG.getConstant(0, RHS.getValueType());
3641         return X86::COND_NS;
3642       }
3643       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3644         // X < 0   -> X == 0, jump on sign.
3645         return X86::COND_S;
3646       }
3647       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3648         // X < 1   -> X <= 0
3649         RHS = DAG.getConstant(0, RHS.getValueType());
3650         return X86::COND_LE;
3651       }
3652     }
3653
3654     switch (SetCCOpcode) {
3655     default: llvm_unreachable("Invalid integer condition!");
3656     case ISD::SETEQ:  return X86::COND_E;
3657     case ISD::SETGT:  return X86::COND_G;
3658     case ISD::SETGE:  return X86::COND_GE;
3659     case ISD::SETLT:  return X86::COND_L;
3660     case ISD::SETLE:  return X86::COND_LE;
3661     case ISD::SETNE:  return X86::COND_NE;
3662     case ISD::SETULT: return X86::COND_B;
3663     case ISD::SETUGT: return X86::COND_A;
3664     case ISD::SETULE: return X86::COND_BE;
3665     case ISD::SETUGE: return X86::COND_AE;
3666     }
3667   }
3668
3669   // First determine if it is required or is profitable to flip the operands.
3670
3671   // If LHS is a foldable load, but RHS is not, flip the condition.
3672   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3673       !ISD::isNON_EXTLoad(RHS.getNode())) {
3674     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3675     std::swap(LHS, RHS);
3676   }
3677
3678   switch (SetCCOpcode) {
3679   default: break;
3680   case ISD::SETOLT:
3681   case ISD::SETOLE:
3682   case ISD::SETUGT:
3683   case ISD::SETUGE:
3684     std::swap(LHS, RHS);
3685     break;
3686   }
3687
3688   // On a floating point condition, the flags are set as follows:
3689   // ZF  PF  CF   op
3690   //  0 | 0 | 0 | X > Y
3691   //  0 | 0 | 1 | X < Y
3692   //  1 | 0 | 0 | X == Y
3693   //  1 | 1 | 1 | unordered
3694   switch (SetCCOpcode) {
3695   default: llvm_unreachable("Condcode should be pre-legalized away");
3696   case ISD::SETUEQ:
3697   case ISD::SETEQ:   return X86::COND_E;
3698   case ISD::SETOLT:              // flipped
3699   case ISD::SETOGT:
3700   case ISD::SETGT:   return X86::COND_A;
3701   case ISD::SETOLE:              // flipped
3702   case ISD::SETOGE:
3703   case ISD::SETGE:   return X86::COND_AE;
3704   case ISD::SETUGT:              // flipped
3705   case ISD::SETULT:
3706   case ISD::SETLT:   return X86::COND_B;
3707   case ISD::SETUGE:              // flipped
3708   case ISD::SETULE:
3709   case ISD::SETLE:   return X86::COND_BE;
3710   case ISD::SETONE:
3711   case ISD::SETNE:   return X86::COND_NE;
3712   case ISD::SETUO:   return X86::COND_P;
3713   case ISD::SETO:    return X86::COND_NP;
3714   case ISD::SETOEQ:
3715   case ISD::SETUNE:  return X86::COND_INVALID;
3716   }
3717 }
3718
3719 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3720 /// code. Current x86 isa includes the following FP cmov instructions:
3721 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3722 static bool hasFPCMov(unsigned X86CC) {
3723   switch (X86CC) {
3724   default:
3725     return false;
3726   case X86::COND_B:
3727   case X86::COND_BE:
3728   case X86::COND_E:
3729   case X86::COND_P:
3730   case X86::COND_A:
3731   case X86::COND_AE:
3732   case X86::COND_NE:
3733   case X86::COND_NP:
3734     return true;
3735   }
3736 }
3737
3738 /// isFPImmLegal - Returns true if the target can instruction select the
3739 /// specified FP immediate natively. If false, the legalizer will
3740 /// materialize the FP immediate as a load from a constant pool.
3741 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3742   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3743     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3744       return true;
3745   }
3746   return false;
3747 }
3748
3749 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3750                                               ISD::LoadExtType ExtTy,
3751                                               EVT NewVT) const {
3752   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3753   // relocation target a movq or addq instruction: don't let the load shrink.
3754   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3755   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3756     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3757       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3758   return true;
3759 }
3760
3761 /// \brief Returns true if it is beneficial to convert a load of a constant
3762 /// to just the constant itself.
3763 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3764                                                           Type *Ty) const {
3765   assert(Ty->isIntegerTy());
3766
3767   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3768   if (BitSize == 0 || BitSize > 64)
3769     return false;
3770   return true;
3771 }
3772
3773 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3774                                                 unsigned Index) const {
3775   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3776     return false;
3777
3778   return (Index == 0 || Index == ResVT.getVectorNumElements());
3779 }
3780
3781 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3782   // Speculate cttz only if we can directly use TZCNT.
3783   return Subtarget->hasBMI();
3784 }
3785
3786 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3787   // Speculate ctlz only if we can directly use LZCNT.
3788   return Subtarget->hasLZCNT();
3789 }
3790
3791 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3792 /// the specified range (L, H].
3793 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3794   return (Val < 0) || (Val >= Low && Val < Hi);
3795 }
3796
3797 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3798 /// specified value.
3799 static bool isUndefOrEqual(int Val, int CmpVal) {
3800   return (Val < 0 || Val == CmpVal);
3801 }
3802
3803 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3804 /// from position Pos and ending in Pos+Size, falls within the specified
3805 /// sequential range (Low, Low+Size]. or is undef.
3806 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3807                                        unsigned Pos, unsigned Size, int Low) {
3808   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3809     if (!isUndefOrEqual(Mask[i], Low))
3810       return false;
3811   return true;
3812 }
3813
3814 /// isVEXTRACTIndex - Return true if the specified
3815 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3816 /// suitable for instruction that extract 128 or 256 bit vectors
3817 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3818   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3819   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3820     return false;
3821
3822   // The index should be aligned on a vecWidth-bit boundary.
3823   uint64_t Index =
3824     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3825
3826   MVT VT = N->getSimpleValueType(0);
3827   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3828   bool Result = (Index * ElSize) % vecWidth == 0;
3829
3830   return Result;
3831 }
3832
3833 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3834 /// operand specifies a subvector insert that is suitable for input to
3835 /// insertion of 128 or 256-bit subvectors
3836 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3837   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3838   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3839     return false;
3840   // The index should be aligned on a vecWidth-bit boundary.
3841   uint64_t Index =
3842     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3843
3844   MVT VT = N->getSimpleValueType(0);
3845   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3846   bool Result = (Index * ElSize) % vecWidth == 0;
3847
3848   return Result;
3849 }
3850
3851 bool X86::isVINSERT128Index(SDNode *N) {
3852   return isVINSERTIndex(N, 128);
3853 }
3854
3855 bool X86::isVINSERT256Index(SDNode *N) {
3856   return isVINSERTIndex(N, 256);
3857 }
3858
3859 bool X86::isVEXTRACT128Index(SDNode *N) {
3860   return isVEXTRACTIndex(N, 128);
3861 }
3862
3863 bool X86::isVEXTRACT256Index(SDNode *N) {
3864   return isVEXTRACTIndex(N, 256);
3865 }
3866
3867 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3868   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3869   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3870     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3871
3872   uint64_t Index =
3873     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3874
3875   MVT VecVT = N->getOperand(0).getSimpleValueType();
3876   MVT ElVT = VecVT.getVectorElementType();
3877
3878   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3879   return Index / NumElemsPerChunk;
3880 }
3881
3882 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3883   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3884   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3885     llvm_unreachable("Illegal insert subvector for VINSERT");
3886
3887   uint64_t Index =
3888     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3889
3890   MVT VecVT = N->getSimpleValueType(0);
3891   MVT ElVT = VecVT.getVectorElementType();
3892
3893   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3894   return Index / NumElemsPerChunk;
3895 }
3896
3897 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3898 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3899 /// and VINSERTI128 instructions.
3900 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3901   return getExtractVEXTRACTImmediate(N, 128);
3902 }
3903
3904 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3905 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3906 /// and VINSERTI64x4 instructions.
3907 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3908   return getExtractVEXTRACTImmediate(N, 256);
3909 }
3910
3911 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3912 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3913 /// and VINSERTI128 instructions.
3914 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3915   return getInsertVINSERTImmediate(N, 128);
3916 }
3917
3918 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3919 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3920 /// and VINSERTI64x4 instructions.
3921 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3922   return getInsertVINSERTImmediate(N, 256);
3923 }
3924
3925 /// isZero - Returns true if Elt is a constant integer zero
3926 static bool isZero(SDValue V) {
3927   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3928   return C && C->isNullValue();
3929 }
3930
3931 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3932 /// constant +0.0.
3933 bool X86::isZeroNode(SDValue Elt) {
3934   if (isZero(Elt))
3935     return true;
3936   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3937     return CFP->getValueAPF().isPosZero();
3938   return false;
3939 }
3940
3941 /// getZeroVector - Returns a vector of specified type with all zero elements.
3942 ///
3943 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
3944                              SelectionDAG &DAG, SDLoc dl) {
3945   assert(VT.isVector() && "Expected a vector type");
3946
3947   // Always build SSE zero vectors as <4 x i32> bitcasted
3948   // to their dest type. This ensures they get CSE'd.
3949   SDValue Vec;
3950   if (VT.is128BitVector()) {  // SSE
3951     if (Subtarget->hasSSE2()) {  // SSE2
3952       SDValue Cst = DAG.getConstant(0, MVT::i32);
3953       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3954     } else { // SSE1
3955       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
3956       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3957     }
3958   } else if (VT.is256BitVector()) { // AVX
3959     if (Subtarget->hasInt256()) { // AVX2
3960       SDValue Cst = DAG.getConstant(0, MVT::i32);
3961       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3962       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
3963     } else {
3964       // 256-bit logic and arithmetic instructions in AVX are all
3965       // floating-point, no support for integer ops. Emit fp zeroed vectors.
3966       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
3967       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3968       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
3969     }
3970   } else if (VT.is512BitVector()) { // AVX-512
3971       SDValue Cst = DAG.getConstant(0, MVT::i32);
3972       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
3973                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3974       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
3975   } else if (VT.getScalarType() == MVT::i1) {
3976
3977     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
3978             && "Unexpected vector type");
3979     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
3980             && "Unexpected vector type");
3981     SDValue Cst = DAG.getConstant(0, MVT::i1);
3982     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
3983     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
3984   } else
3985     llvm_unreachable("Unexpected vector type");
3986
3987   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3988 }
3989
3990 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
3991                                 SelectionDAG &DAG, SDLoc dl,
3992                                 unsigned vectorWidth) {
3993   assert((vectorWidth == 128 || vectorWidth == 256) &&
3994          "Unsupported vector width");
3995   EVT VT = Vec.getValueType();
3996   EVT ElVT = VT.getVectorElementType();
3997   unsigned Factor = VT.getSizeInBits()/vectorWidth;
3998   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
3999                                   VT.getVectorNumElements()/Factor);
4000
4001   // Extract from UNDEF is UNDEF.
4002   if (Vec.getOpcode() == ISD::UNDEF)
4003     return DAG.getUNDEF(ResultVT);
4004
4005   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4006   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4007
4008   // This is the index of the first element of the vectorWidth-bit chunk
4009   // we want.
4010   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4011                                * ElemsPerChunk);
4012
4013   // If the input is a buildvector just emit a smaller one.
4014   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4015     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4016                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4017                                     ElemsPerChunk));
4018
4019   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
4020   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4021 }
4022
4023 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4024 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4025 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4026 /// instructions or a simple subregister reference. Idx is an index in the
4027 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4028 /// lowering EXTRACT_VECTOR_ELT operations easier.
4029 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4030                                    SelectionDAG &DAG, SDLoc dl) {
4031   assert((Vec.getValueType().is256BitVector() ||
4032           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4033   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4034 }
4035
4036 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4037 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4038                                    SelectionDAG &DAG, SDLoc dl) {
4039   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4040   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4041 }
4042
4043 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4044                                unsigned IdxVal, SelectionDAG &DAG,
4045                                SDLoc dl, unsigned vectorWidth) {
4046   assert((vectorWidth == 128 || vectorWidth == 256) &&
4047          "Unsupported vector width");
4048   // Inserting UNDEF is Result
4049   if (Vec.getOpcode() == ISD::UNDEF)
4050     return Result;
4051   EVT VT = Vec.getValueType();
4052   EVT ElVT = VT.getVectorElementType();
4053   EVT ResultVT = Result.getValueType();
4054
4055   // Insert the relevant vectorWidth bits.
4056   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4057
4058   // This is the index of the first element of the vectorWidth-bit chunk
4059   // we want.
4060   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4061                                * ElemsPerChunk);
4062
4063   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
4064   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4065 }
4066
4067 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4068 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4069 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4070 /// simple superregister reference.  Idx is an index in the 128 bits
4071 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4072 /// lowering INSERT_VECTOR_ELT operations easier.
4073 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4074                                   SelectionDAG &DAG, SDLoc dl) {
4075   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4076
4077   // For insertion into the zero index (low half) of a 256-bit vector, it is
4078   // more efficient to generate a blend with immediate instead of an insert*128.
4079   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4080   // extend the subvector to the size of the result vector. Make sure that
4081   // we are not recursing on that node by checking for undef here.
4082   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4083       Result.getOpcode() != ISD::UNDEF) {
4084     EVT ResultVT = Result.getValueType();
4085     SDValue ZeroIndex = DAG.getIntPtrConstant(0);
4086     SDValue Undef = DAG.getUNDEF(ResultVT);
4087     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4088                                  Vec, ZeroIndex);
4089
4090     // The blend instruction, and therefore its mask, depend on the data type.
4091     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4092     if (ScalarType.isFloatingPoint()) {
4093       // Choose either vblendps (float) or vblendpd (double).
4094       unsigned ScalarSize = ScalarType.getSizeInBits();
4095       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4096       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4097       SDValue Mask = DAG.getConstant(MaskVal, MVT::i8);
4098       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4099     }
4100
4101     const X86Subtarget &Subtarget =
4102     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4103
4104     // AVX2 is needed for 256-bit integer blend support.
4105     // Integers must be cast to 32-bit because there is only vpblendd;
4106     // vpblendw can't be used for this because it has a handicapped mask.
4107
4108     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4109     // is still more efficient than using the wrong domain vinsertf128 that
4110     // will be created by InsertSubVector().
4111     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4112
4113     SDValue Mask = DAG.getConstant(0x0f, MVT::i8);
4114     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4115     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4116     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4117   }
4118
4119   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4120 }
4121
4122 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4123                                   SelectionDAG &DAG, SDLoc dl) {
4124   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4125   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4126 }
4127
4128 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4129 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4130 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4131 /// large BUILD_VECTORS.
4132 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4133                                    unsigned NumElems, SelectionDAG &DAG,
4134                                    SDLoc dl) {
4135   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4136   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4137 }
4138
4139 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4140                                    unsigned NumElems, SelectionDAG &DAG,
4141                                    SDLoc dl) {
4142   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4143   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4144 }
4145
4146 /// getOnesVector - Returns a vector of specified type with all bits set.
4147 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4148 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4149 /// Then bitcast to their original type, ensuring they get CSE'd.
4150 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4151                              SDLoc dl) {
4152   assert(VT.isVector() && "Expected a vector type");
4153
4154   SDValue Cst = DAG.getConstant(~0U, MVT::i32);
4155   SDValue Vec;
4156   if (VT.is256BitVector()) {
4157     if (HasInt256) { // AVX2
4158       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4159       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4160     } else { // AVX
4161       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4162       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4163     }
4164   } else if (VT.is128BitVector()) {
4165     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4166   } else
4167     llvm_unreachable("Unexpected vector type");
4168
4169   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4170 }
4171
4172 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4173 /// operation of specified width.
4174 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4175                        SDValue V2) {
4176   unsigned NumElems = VT.getVectorNumElements();
4177   SmallVector<int, 8> Mask;
4178   Mask.push_back(NumElems);
4179   for (unsigned i = 1; i != NumElems; ++i)
4180     Mask.push_back(i);
4181   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4182 }
4183
4184 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4185 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4186                           SDValue V2) {
4187   unsigned NumElems = VT.getVectorNumElements();
4188   SmallVector<int, 8> Mask;
4189   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4190     Mask.push_back(i);
4191     Mask.push_back(i + NumElems);
4192   }
4193   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4194 }
4195
4196 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4197 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4198                           SDValue V2) {
4199   unsigned NumElems = VT.getVectorNumElements();
4200   SmallVector<int, 8> Mask;
4201   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4202     Mask.push_back(i + Half);
4203     Mask.push_back(i + NumElems + Half);
4204   }
4205   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4206 }
4207
4208 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4209 /// vector of zero or undef vector.  This produces a shuffle where the low
4210 /// element of V2 is swizzled into the zero/undef vector, landing at element
4211 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4212 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4213                                            bool IsZero,
4214                                            const X86Subtarget *Subtarget,
4215                                            SelectionDAG &DAG) {
4216   MVT VT = V2.getSimpleValueType();
4217   SDValue V1 = IsZero
4218     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4219   unsigned NumElems = VT.getVectorNumElements();
4220   SmallVector<int, 16> MaskVec;
4221   for (unsigned i = 0; i != NumElems; ++i)
4222     // If this is the insertion idx, put the low elt of V2 here.
4223     MaskVec.push_back(i == Idx ? NumElems : i);
4224   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4225 }
4226
4227 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4228 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4229 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4230 /// shuffles which use a single input multiple times, and in those cases it will
4231 /// adjust the mask to only have indices within that single input.
4232 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4233                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4234   unsigned NumElems = VT.getVectorNumElements();
4235   SDValue ImmN;
4236
4237   IsUnary = false;
4238   bool IsFakeUnary = false;
4239   switch(N->getOpcode()) {
4240   case X86ISD::BLENDI:
4241     ImmN = N->getOperand(N->getNumOperands()-1);
4242     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4243     break;
4244   case X86ISD::SHUFP:
4245     ImmN = N->getOperand(N->getNumOperands()-1);
4246     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4247     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4248     break;
4249   case X86ISD::UNPCKH:
4250     DecodeUNPCKHMask(VT, Mask);
4251     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4252     break;
4253   case X86ISD::UNPCKL:
4254     DecodeUNPCKLMask(VT, Mask);
4255     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4256     break;
4257   case X86ISD::MOVHLPS:
4258     DecodeMOVHLPSMask(NumElems, Mask);
4259     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4260     break;
4261   case X86ISD::MOVLHPS:
4262     DecodeMOVLHPSMask(NumElems, Mask);
4263     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4264     break;
4265   case X86ISD::PALIGNR:
4266     ImmN = N->getOperand(N->getNumOperands()-1);
4267     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4268     break;
4269   case X86ISD::PSHUFD:
4270   case X86ISD::VPERMILPI:
4271     ImmN = N->getOperand(N->getNumOperands()-1);
4272     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4273     IsUnary = true;
4274     break;
4275   case X86ISD::PSHUFHW:
4276     ImmN = N->getOperand(N->getNumOperands()-1);
4277     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4278     IsUnary = true;
4279     break;
4280   case X86ISD::PSHUFLW:
4281     ImmN = N->getOperand(N->getNumOperands()-1);
4282     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4283     IsUnary = true;
4284     break;
4285   case X86ISD::PSHUFB: {
4286     IsUnary = true;
4287     SDValue MaskNode = N->getOperand(1);
4288     while (MaskNode->getOpcode() == ISD::BITCAST)
4289       MaskNode = MaskNode->getOperand(0);
4290
4291     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4292       // If we have a build-vector, then things are easy.
4293       EVT VT = MaskNode.getValueType();
4294       assert(VT.isVector() &&
4295              "Can't produce a non-vector with a build_vector!");
4296       if (!VT.isInteger())
4297         return false;
4298
4299       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4300
4301       SmallVector<uint64_t, 32> RawMask;
4302       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4303         SDValue Op = MaskNode->getOperand(i);
4304         if (Op->getOpcode() == ISD::UNDEF) {
4305           RawMask.push_back((uint64_t)SM_SentinelUndef);
4306           continue;
4307         }
4308         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4309         if (!CN)
4310           return false;
4311         APInt MaskElement = CN->getAPIntValue();
4312
4313         // We now have to decode the element which could be any integer size and
4314         // extract each byte of it.
4315         for (int j = 0; j < NumBytesPerElement; ++j) {
4316           // Note that this is x86 and so always little endian: the low byte is
4317           // the first byte of the mask.
4318           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4319           MaskElement = MaskElement.lshr(8);
4320         }
4321       }
4322       DecodePSHUFBMask(RawMask, Mask);
4323       break;
4324     }
4325
4326     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4327     if (!MaskLoad)
4328       return false;
4329
4330     SDValue Ptr = MaskLoad->getBasePtr();
4331     if (Ptr->getOpcode() == X86ISD::Wrapper)
4332       Ptr = Ptr->getOperand(0);
4333
4334     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4335     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4336       return false;
4337
4338     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4339       DecodePSHUFBMask(C, Mask);
4340       if (Mask.empty())
4341         return false;
4342       break;
4343     }
4344
4345     return false;
4346   }
4347   case X86ISD::VPERMI:
4348     ImmN = N->getOperand(N->getNumOperands()-1);
4349     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4350     IsUnary = true;
4351     break;
4352   case X86ISD::MOVSS:
4353   case X86ISD::MOVSD:
4354     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4355     break;
4356   case X86ISD::VPERM2X128:
4357     ImmN = N->getOperand(N->getNumOperands()-1);
4358     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4359     if (Mask.empty()) return false;
4360     break;
4361   case X86ISD::MOVSLDUP:
4362     DecodeMOVSLDUPMask(VT, Mask);
4363     IsUnary = true;
4364     break;
4365   case X86ISD::MOVSHDUP:
4366     DecodeMOVSHDUPMask(VT, Mask);
4367     IsUnary = true;
4368     break;
4369   case X86ISD::MOVDDUP:
4370     DecodeMOVDDUPMask(VT, Mask);
4371     IsUnary = true;
4372     break;
4373   case X86ISD::MOVLHPD:
4374   case X86ISD::MOVLPD:
4375   case X86ISD::MOVLPS:
4376     // Not yet implemented
4377     return false;
4378   default: llvm_unreachable("unknown target shuffle node");
4379   }
4380
4381   // If we have a fake unary shuffle, the shuffle mask is spread across two
4382   // inputs that are actually the same node. Re-map the mask to always point
4383   // into the first input.
4384   if (IsFakeUnary)
4385     for (int &M : Mask)
4386       if (M >= (int)Mask.size())
4387         M -= Mask.size();
4388
4389   return true;
4390 }
4391
4392 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4393 /// element of the result of the vector shuffle.
4394 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4395                                    unsigned Depth) {
4396   if (Depth == 6)
4397     return SDValue();  // Limit search depth.
4398
4399   SDValue V = SDValue(N, 0);
4400   EVT VT = V.getValueType();
4401   unsigned Opcode = V.getOpcode();
4402
4403   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4404   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4405     int Elt = SV->getMaskElt(Index);
4406
4407     if (Elt < 0)
4408       return DAG.getUNDEF(VT.getVectorElementType());
4409
4410     unsigned NumElems = VT.getVectorNumElements();
4411     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4412                                          : SV->getOperand(1);
4413     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4414   }
4415
4416   // Recurse into target specific vector shuffles to find scalars.
4417   if (isTargetShuffle(Opcode)) {
4418     MVT ShufVT = V.getSimpleValueType();
4419     unsigned NumElems = ShufVT.getVectorNumElements();
4420     SmallVector<int, 16> ShuffleMask;
4421     bool IsUnary;
4422
4423     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4424       return SDValue();
4425
4426     int Elt = ShuffleMask[Index];
4427     if (Elt < 0)
4428       return DAG.getUNDEF(ShufVT.getVectorElementType());
4429
4430     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4431                                          : N->getOperand(1);
4432     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4433                                Depth+1);
4434   }
4435
4436   // Actual nodes that may contain scalar elements
4437   if (Opcode == ISD::BITCAST) {
4438     V = V.getOperand(0);
4439     EVT SrcVT = V.getValueType();
4440     unsigned NumElems = VT.getVectorNumElements();
4441
4442     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4443       return SDValue();
4444   }
4445
4446   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4447     return (Index == 0) ? V.getOperand(0)
4448                         : DAG.getUNDEF(VT.getVectorElementType());
4449
4450   if (V.getOpcode() == ISD::BUILD_VECTOR)
4451     return V.getOperand(Index);
4452
4453   return SDValue();
4454 }
4455
4456 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4457 ///
4458 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4459                                        unsigned NumNonZero, unsigned NumZero,
4460                                        SelectionDAG &DAG,
4461                                        const X86Subtarget* Subtarget,
4462                                        const TargetLowering &TLI) {
4463   if (NumNonZero > 8)
4464     return SDValue();
4465
4466   SDLoc dl(Op);
4467   SDValue V;
4468   bool First = true;
4469
4470   // SSE4.1 - use PINSRB to insert each byte directly.
4471   if (Subtarget->hasSSE41()) {
4472     for (unsigned i = 0; i < 16; ++i) {
4473       bool isNonZero = (NonZeros & (1 << i)) != 0;
4474       if (isNonZero) {
4475         if (First) {
4476           if (NumZero)
4477             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4478           else
4479             V = DAG.getUNDEF(MVT::v16i8);
4480           First = false;
4481         }
4482         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4483                         MVT::v16i8, V, Op.getOperand(i),
4484                         DAG.getIntPtrConstant(i));
4485       }
4486     }
4487
4488     return V;
4489   }
4490
4491   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4492   for (unsigned i = 0; i < 16; ++i) {
4493     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4494     if (ThisIsNonZero && First) {
4495       if (NumZero)
4496         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4497       else
4498         V = DAG.getUNDEF(MVT::v8i16);
4499       First = false;
4500     }
4501
4502     if ((i & 1) != 0) {
4503       SDValue ThisElt, LastElt;
4504       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4505       if (LastIsNonZero) {
4506         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4507                               MVT::i16, Op.getOperand(i-1));
4508       }
4509       if (ThisIsNonZero) {
4510         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4511         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4512                               ThisElt, DAG.getConstant(8, MVT::i8));
4513         if (LastIsNonZero)
4514           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4515       } else
4516         ThisElt = LastElt;
4517
4518       if (ThisElt.getNode())
4519         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4520                         DAG.getIntPtrConstant(i/2));
4521     }
4522   }
4523
4524   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4525 }
4526
4527 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4528 ///
4529 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4530                                      unsigned NumNonZero, unsigned NumZero,
4531                                      SelectionDAG &DAG,
4532                                      const X86Subtarget* Subtarget,
4533                                      const TargetLowering &TLI) {
4534   if (NumNonZero > 4)
4535     return SDValue();
4536
4537   SDLoc dl(Op);
4538   SDValue V;
4539   bool First = true;
4540   for (unsigned i = 0; i < 8; ++i) {
4541     bool isNonZero = (NonZeros & (1 << i)) != 0;
4542     if (isNonZero) {
4543       if (First) {
4544         if (NumZero)
4545           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4546         else
4547           V = DAG.getUNDEF(MVT::v8i16);
4548         First = false;
4549       }
4550       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4551                       MVT::v8i16, V, Op.getOperand(i),
4552                       DAG.getIntPtrConstant(i));
4553     }
4554   }
4555
4556   return V;
4557 }
4558
4559 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4560 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4561                                      const X86Subtarget *Subtarget,
4562                                      const TargetLowering &TLI) {
4563   // Find all zeroable elements.
4564   std::bitset<4> Zeroable;
4565   for (int i=0; i < 4; ++i) {
4566     SDValue Elt = Op->getOperand(i);
4567     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4568   }
4569   assert(Zeroable.size() - Zeroable.count() > 1 &&
4570          "We expect at least two non-zero elements!");
4571
4572   // We only know how to deal with build_vector nodes where elements are either
4573   // zeroable or extract_vector_elt with constant index.
4574   SDValue FirstNonZero;
4575   unsigned FirstNonZeroIdx;
4576   for (unsigned i=0; i < 4; ++i) {
4577     if (Zeroable[i])
4578       continue;
4579     SDValue Elt = Op->getOperand(i);
4580     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4581         !isa<ConstantSDNode>(Elt.getOperand(1)))
4582       return SDValue();
4583     // Make sure that this node is extracting from a 128-bit vector.
4584     MVT VT = Elt.getOperand(0).getSimpleValueType();
4585     if (!VT.is128BitVector())
4586       return SDValue();
4587     if (!FirstNonZero.getNode()) {
4588       FirstNonZero = Elt;
4589       FirstNonZeroIdx = i;
4590     }
4591   }
4592
4593   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4594   SDValue V1 = FirstNonZero.getOperand(0);
4595   MVT VT = V1.getSimpleValueType();
4596
4597   // See if this build_vector can be lowered as a blend with zero.
4598   SDValue Elt;
4599   unsigned EltMaskIdx, EltIdx;
4600   int Mask[4];
4601   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4602     if (Zeroable[EltIdx]) {
4603       // The zero vector will be on the right hand side.
4604       Mask[EltIdx] = EltIdx+4;
4605       continue;
4606     }
4607
4608     Elt = Op->getOperand(EltIdx);
4609     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4610     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4611     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4612       break;
4613     Mask[EltIdx] = EltIdx;
4614   }
4615
4616   if (EltIdx == 4) {
4617     // Let the shuffle legalizer deal with blend operations.
4618     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4619     if (V1.getSimpleValueType() != VT)
4620       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4621     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4622   }
4623
4624   // See if we can lower this build_vector to a INSERTPS.
4625   if (!Subtarget->hasSSE41())
4626     return SDValue();
4627
4628   SDValue V2 = Elt.getOperand(0);
4629   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4630     V1 = SDValue();
4631
4632   bool CanFold = true;
4633   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4634     if (Zeroable[i])
4635       continue;
4636
4637     SDValue Current = Op->getOperand(i);
4638     SDValue SrcVector = Current->getOperand(0);
4639     if (!V1.getNode())
4640       V1 = SrcVector;
4641     CanFold = SrcVector == V1 &&
4642       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4643   }
4644
4645   if (!CanFold)
4646     return SDValue();
4647
4648   assert(V1.getNode() && "Expected at least two non-zero elements!");
4649   if (V1.getSimpleValueType() != MVT::v4f32)
4650     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4651   if (V2.getSimpleValueType() != MVT::v4f32)
4652     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4653
4654   // Ok, we can emit an INSERTPS instruction.
4655   unsigned ZMask = Zeroable.to_ulong();
4656
4657   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4658   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4659   SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
4660                                DAG.getIntPtrConstant(InsertPSMask));
4661   return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
4662 }
4663
4664 /// Return a vector logical shift node.
4665 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4666                          unsigned NumBits, SelectionDAG &DAG,
4667                          const TargetLowering &TLI, SDLoc dl) {
4668   assert(VT.is128BitVector() && "Unknown type for VShift");
4669   MVT ShVT = MVT::v2i64;
4670   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4671   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4672   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4673   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4674   SDValue ShiftVal = DAG.getConstant(NumBits/8, ScalarShiftTy);
4675   return DAG.getNode(ISD::BITCAST, dl, VT,
4676                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4677 }
4678
4679 static SDValue
4680 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4681
4682   // Check if the scalar load can be widened into a vector load. And if
4683   // the address is "base + cst" see if the cst can be "absorbed" into
4684   // the shuffle mask.
4685   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4686     SDValue Ptr = LD->getBasePtr();
4687     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4688       return SDValue();
4689     EVT PVT = LD->getValueType(0);
4690     if (PVT != MVT::i32 && PVT != MVT::f32)
4691       return SDValue();
4692
4693     int FI = -1;
4694     int64_t Offset = 0;
4695     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4696       FI = FINode->getIndex();
4697       Offset = 0;
4698     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4699                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4700       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4701       Offset = Ptr.getConstantOperandVal(1);
4702       Ptr = Ptr.getOperand(0);
4703     } else {
4704       return SDValue();
4705     }
4706
4707     // FIXME: 256-bit vector instructions don't require a strict alignment,
4708     // improve this code to support it better.
4709     unsigned RequiredAlign = VT.getSizeInBits()/8;
4710     SDValue Chain = LD->getChain();
4711     // Make sure the stack object alignment is at least 16 or 32.
4712     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4713     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4714       if (MFI->isFixedObjectIndex(FI)) {
4715         // Can't change the alignment. FIXME: It's possible to compute
4716         // the exact stack offset and reference FI + adjust offset instead.
4717         // If someone *really* cares about this. That's the way to implement it.
4718         return SDValue();
4719       } else {
4720         MFI->setObjectAlignment(FI, RequiredAlign);
4721       }
4722     }
4723
4724     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4725     // Ptr + (Offset & ~15).
4726     if (Offset < 0)
4727       return SDValue();
4728     if ((Offset % RequiredAlign) & 3)
4729       return SDValue();
4730     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4731     if (StartOffset)
4732       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
4733                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4734
4735     int EltNo = (Offset - StartOffset) >> 2;
4736     unsigned NumElems = VT.getVectorNumElements();
4737
4738     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4739     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4740                              LD->getPointerInfo().getWithOffset(StartOffset),
4741                              false, false, false, 0);
4742
4743     SmallVector<int, 8> Mask(NumElems, EltNo);
4744
4745     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4746   }
4747
4748   return SDValue();
4749 }
4750
4751 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4752 /// elements can be replaced by a single large load which has the same value as
4753 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4754 ///
4755 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4756 ///
4757 /// FIXME: we'd also like to handle the case where the last elements are zero
4758 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4759 /// There's even a handy isZeroNode for that purpose.
4760 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4761                                         SDLoc &DL, SelectionDAG &DAG,
4762                                         bool isAfterLegalize) {
4763   unsigned NumElems = Elts.size();
4764
4765   LoadSDNode *LDBase = nullptr;
4766   unsigned LastLoadedElt = -1U;
4767
4768   // For each element in the initializer, see if we've found a load or an undef.
4769   // If we don't find an initial load element, or later load elements are
4770   // non-consecutive, bail out.
4771   for (unsigned i = 0; i < NumElems; ++i) {
4772     SDValue Elt = Elts[i];
4773     // Look through a bitcast.
4774     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4775       Elt = Elt.getOperand(0);
4776     if (!Elt.getNode() ||
4777         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4778       return SDValue();
4779     if (!LDBase) {
4780       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4781         return SDValue();
4782       LDBase = cast<LoadSDNode>(Elt.getNode());
4783       LastLoadedElt = i;
4784       continue;
4785     }
4786     if (Elt.getOpcode() == ISD::UNDEF)
4787       continue;
4788
4789     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4790     EVT LdVT = Elt.getValueType();
4791     // Each loaded element must be the correct fractional portion of the
4792     // requested vector load.
4793     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4794       return SDValue();
4795     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4796       return SDValue();
4797     LastLoadedElt = i;
4798   }
4799
4800   // If we have found an entire vector of loads and undefs, then return a large
4801   // load of the entire vector width starting at the base pointer.  If we found
4802   // consecutive loads for the low half, generate a vzext_load node.
4803   if (LastLoadedElt == NumElems - 1) {
4804     assert(LDBase && "Did not find base load for merging consecutive loads");
4805     EVT EltVT = LDBase->getValueType(0);
4806     // Ensure that the input vector size for the merged loads matches the
4807     // cumulative size of the input elements.
4808     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4809       return SDValue();
4810
4811     if (isAfterLegalize &&
4812         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4813       return SDValue();
4814
4815     SDValue NewLd = SDValue();
4816
4817     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4818                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4819                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4820                         LDBase->getAlignment());
4821
4822     if (LDBase->hasAnyUseOfValue(1)) {
4823       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4824                                      SDValue(LDBase, 1),
4825                                      SDValue(NewLd.getNode(), 1));
4826       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4827       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4828                              SDValue(NewLd.getNode(), 1));
4829     }
4830
4831     return NewLd;
4832   }
4833
4834   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4835   //of a v4i32 / v4f32. It's probably worth generalizing.
4836   EVT EltVT = VT.getVectorElementType();
4837   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4838       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4839     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4840     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4841     SDValue ResNode =
4842         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4843                                 LDBase->getPointerInfo(),
4844                                 LDBase->getAlignment(),
4845                                 false/*isVolatile*/, true/*ReadMem*/,
4846                                 false/*WriteMem*/);
4847
4848     // Make sure the newly-created LOAD is in the same position as LDBase in
4849     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4850     // update uses of LDBase's output chain to use the TokenFactor.
4851     if (LDBase->hasAnyUseOfValue(1)) {
4852       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4853                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4854       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4855       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4856                              SDValue(ResNode.getNode(), 1));
4857     }
4858
4859     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4860   }
4861   return SDValue();
4862 }
4863
4864 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4865 /// to generate a splat value for the following cases:
4866 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4867 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4868 /// a scalar load, or a constant.
4869 /// The VBROADCAST node is returned when a pattern is found,
4870 /// or SDValue() otherwise.
4871 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4872                                     SelectionDAG &DAG) {
4873   // VBROADCAST requires AVX.
4874   // TODO: Splats could be generated for non-AVX CPUs using SSE
4875   // instructions, but there's less potential gain for only 128-bit vectors.
4876   if (!Subtarget->hasAVX())
4877     return SDValue();
4878
4879   MVT VT = Op.getSimpleValueType();
4880   SDLoc dl(Op);
4881
4882   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4883          "Unsupported vector type for broadcast.");
4884
4885   SDValue Ld;
4886   bool ConstSplatVal;
4887
4888   switch (Op.getOpcode()) {
4889     default:
4890       // Unknown pattern found.
4891       return SDValue();
4892
4893     case ISD::BUILD_VECTOR: {
4894       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4895       BitVector UndefElements;
4896       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4897
4898       // We need a splat of a single value to use broadcast, and it doesn't
4899       // make any sense if the value is only in one element of the vector.
4900       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4901         return SDValue();
4902
4903       Ld = Splat;
4904       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4905                        Ld.getOpcode() == ISD::ConstantFP);
4906
4907       // Make sure that all of the users of a non-constant load are from the
4908       // BUILD_VECTOR node.
4909       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4910         return SDValue();
4911       break;
4912     }
4913
4914     case ISD::VECTOR_SHUFFLE: {
4915       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4916
4917       // Shuffles must have a splat mask where the first element is
4918       // broadcasted.
4919       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4920         return SDValue();
4921
4922       SDValue Sc = Op.getOperand(0);
4923       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4924           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4925
4926         if (!Subtarget->hasInt256())
4927           return SDValue();
4928
4929         // Use the register form of the broadcast instruction available on AVX2.
4930         if (VT.getSizeInBits() >= 256)
4931           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4932         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4933       }
4934
4935       Ld = Sc.getOperand(0);
4936       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4937                        Ld.getOpcode() == ISD::ConstantFP);
4938
4939       // The scalar_to_vector node and the suspected
4940       // load node must have exactly one user.
4941       // Constants may have multiple users.
4942
4943       // AVX-512 has register version of the broadcast
4944       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4945         Ld.getValueType().getSizeInBits() >= 32;
4946       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4947           !hasRegVer))
4948         return SDValue();
4949       break;
4950     }
4951   }
4952
4953   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4954   bool IsGE256 = (VT.getSizeInBits() >= 256);
4955
4956   // When optimizing for size, generate up to 5 extra bytes for a broadcast
4957   // instruction to save 8 or more bytes of constant pool data.
4958   // TODO: If multiple splats are generated to load the same constant,
4959   // it may be detrimental to overall size. There needs to be a way to detect
4960   // that condition to know if this is truly a size win.
4961   const Function *F = DAG.getMachineFunction().getFunction();
4962   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4963
4964   // Handle broadcasting a single constant scalar from the constant pool
4965   // into a vector.
4966   // On Sandybridge (no AVX2), it is still better to load a constant vector
4967   // from the constant pool and not to broadcast it from a scalar.
4968   // But override that restriction when optimizing for size.
4969   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
4970   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
4971     EVT CVT = Ld.getValueType();
4972     assert(!CVT.isVector() && "Must not broadcast a vector type");
4973
4974     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
4975     // For size optimization, also splat v2f64 and v2i64, and for size opt
4976     // with AVX2, also splat i8 and i16.
4977     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
4978     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4979         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
4980       const Constant *C = nullptr;
4981       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4982         C = CI->getConstantIntValue();
4983       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4984         C = CF->getConstantFPValue();
4985
4986       assert(C && "Invalid constant type");
4987
4988       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4989       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
4990       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4991       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4992                        MachinePointerInfo::getConstantPool(),
4993                        false, false, false, Alignment);
4994
4995       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4996     }
4997   }
4998
4999   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5000
5001   // Handle AVX2 in-register broadcasts.
5002   if (!IsLoad && Subtarget->hasInt256() &&
5003       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5004     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5005
5006   // The scalar source must be a normal load.
5007   if (!IsLoad)
5008     return SDValue();
5009
5010   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5011       (Subtarget->hasVLX() && ScalarSize == 64))
5012     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5013
5014   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5015   // double since there is no vbroadcastsd xmm
5016   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5017     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5018       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5019   }
5020
5021   // Unsupported broadcast.
5022   return SDValue();
5023 }
5024
5025 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5026 /// underlying vector and index.
5027 ///
5028 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5029 /// index.
5030 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5031                                          SDValue ExtIdx) {
5032   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5033   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5034     return Idx;
5035
5036   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5037   // lowered this:
5038   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5039   // to:
5040   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5041   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5042   //                           undef)
5043   //                       Constant<0>)
5044   // In this case the vector is the extract_subvector expression and the index
5045   // is 2, as specified by the shuffle.
5046   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5047   SDValue ShuffleVec = SVOp->getOperand(0);
5048   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5049   assert(ShuffleVecVT.getVectorElementType() ==
5050          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5051
5052   int ShuffleIdx = SVOp->getMaskElt(Idx);
5053   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5054     ExtractedFromVec = ShuffleVec;
5055     return ShuffleIdx;
5056   }
5057   return Idx;
5058 }
5059
5060 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5061   MVT VT = Op.getSimpleValueType();
5062
5063   // Skip if insert_vec_elt is not supported.
5064   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5065   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5066     return SDValue();
5067
5068   SDLoc DL(Op);
5069   unsigned NumElems = Op.getNumOperands();
5070
5071   SDValue VecIn1;
5072   SDValue VecIn2;
5073   SmallVector<unsigned, 4> InsertIndices;
5074   SmallVector<int, 8> Mask(NumElems, -1);
5075
5076   for (unsigned i = 0; i != NumElems; ++i) {
5077     unsigned Opc = Op.getOperand(i).getOpcode();
5078
5079     if (Opc == ISD::UNDEF)
5080       continue;
5081
5082     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5083       // Quit if more than 1 elements need inserting.
5084       if (InsertIndices.size() > 1)
5085         return SDValue();
5086
5087       InsertIndices.push_back(i);
5088       continue;
5089     }
5090
5091     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5092     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5093     // Quit if non-constant index.
5094     if (!isa<ConstantSDNode>(ExtIdx))
5095       return SDValue();
5096     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5097
5098     // Quit if extracted from vector of different type.
5099     if (ExtractedFromVec.getValueType() != VT)
5100       return SDValue();
5101
5102     if (!VecIn1.getNode())
5103       VecIn1 = ExtractedFromVec;
5104     else if (VecIn1 != ExtractedFromVec) {
5105       if (!VecIn2.getNode())
5106         VecIn2 = ExtractedFromVec;
5107       else if (VecIn2 != ExtractedFromVec)
5108         // Quit if more than 2 vectors to shuffle
5109         return SDValue();
5110     }
5111
5112     if (ExtractedFromVec == VecIn1)
5113       Mask[i] = Idx;
5114     else if (ExtractedFromVec == VecIn2)
5115       Mask[i] = Idx + NumElems;
5116   }
5117
5118   if (!VecIn1.getNode())
5119     return SDValue();
5120
5121   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5122   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5123   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5124     unsigned Idx = InsertIndices[i];
5125     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5126                      DAG.getIntPtrConstant(Idx));
5127   }
5128
5129   return NV;
5130 }
5131
5132 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5133 SDValue
5134 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5135
5136   MVT VT = Op.getSimpleValueType();
5137   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5138          "Unexpected type in LowerBUILD_VECTORvXi1!");
5139
5140   SDLoc dl(Op);
5141   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5142     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5143     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5144     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5145   }
5146
5147   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5148     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5149     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5150     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5151   }
5152
5153   bool AllContants = true;
5154   uint64_t Immediate = 0;
5155   int NonConstIdx = -1;
5156   bool IsSplat = true;
5157   unsigned NumNonConsts = 0;
5158   unsigned NumConsts = 0;
5159   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5160     SDValue In = Op.getOperand(idx);
5161     if (In.getOpcode() == ISD::UNDEF)
5162       continue;
5163     if (!isa<ConstantSDNode>(In)) {
5164       AllContants = false;
5165       NonConstIdx = idx;
5166       NumNonConsts++;
5167     } else {
5168       NumConsts++;
5169       if (cast<ConstantSDNode>(In)->getZExtValue())
5170       Immediate |= (1ULL << idx);
5171     }
5172     if (In != Op.getOperand(0))
5173       IsSplat = false;
5174   }
5175
5176   if (AllContants) {
5177     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5178       DAG.getConstant(Immediate, MVT::i16));
5179     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5180                        DAG.getIntPtrConstant(0));
5181   }
5182
5183   if (NumNonConsts == 1 && NonConstIdx != 0) {
5184     SDValue DstVec;
5185     if (NumConsts) {
5186       SDValue VecAsImm = DAG.getConstant(Immediate,
5187                                          MVT::getIntegerVT(VT.getSizeInBits()));
5188       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5189     }
5190     else
5191       DstVec = DAG.getUNDEF(VT);
5192     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5193                        Op.getOperand(NonConstIdx),
5194                        DAG.getIntPtrConstant(NonConstIdx));
5195   }
5196   if (!IsSplat && (NonConstIdx != 0))
5197     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5198   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5199   SDValue Select;
5200   if (IsSplat)
5201     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5202                           DAG.getConstant(-1, SelectVT),
5203                           DAG.getConstant(0, SelectVT));
5204   else
5205     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5206                          DAG.getConstant((Immediate | 1), SelectVT),
5207                          DAG.getConstant(Immediate, SelectVT));
5208   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5209 }
5210
5211 /// \brief Return true if \p N implements a horizontal binop and return the
5212 /// operands for the horizontal binop into V0 and V1.
5213 ///
5214 /// This is a helper function of LowerToHorizontalOp().
5215 /// This function checks that the build_vector \p N in input implements a
5216 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5217 /// operation to match.
5218 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5219 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5220 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5221 /// arithmetic sub.
5222 ///
5223 /// This function only analyzes elements of \p N whose indices are
5224 /// in range [BaseIdx, LastIdx).
5225 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5226                               SelectionDAG &DAG,
5227                               unsigned BaseIdx, unsigned LastIdx,
5228                               SDValue &V0, SDValue &V1) {
5229   EVT VT = N->getValueType(0);
5230
5231   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5232   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5233          "Invalid Vector in input!");
5234
5235   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5236   bool CanFold = true;
5237   unsigned ExpectedVExtractIdx = BaseIdx;
5238   unsigned NumElts = LastIdx - BaseIdx;
5239   V0 = DAG.getUNDEF(VT);
5240   V1 = DAG.getUNDEF(VT);
5241
5242   // Check if N implements a horizontal binop.
5243   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5244     SDValue Op = N->getOperand(i + BaseIdx);
5245
5246     // Skip UNDEFs.
5247     if (Op->getOpcode() == ISD::UNDEF) {
5248       // Update the expected vector extract index.
5249       if (i * 2 == NumElts)
5250         ExpectedVExtractIdx = BaseIdx;
5251       ExpectedVExtractIdx += 2;
5252       continue;
5253     }
5254
5255     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5256
5257     if (!CanFold)
5258       break;
5259
5260     SDValue Op0 = Op.getOperand(0);
5261     SDValue Op1 = Op.getOperand(1);
5262
5263     // Try to match the following pattern:
5264     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5265     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5266         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5267         Op0.getOperand(0) == Op1.getOperand(0) &&
5268         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5269         isa<ConstantSDNode>(Op1.getOperand(1)));
5270     if (!CanFold)
5271       break;
5272
5273     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5274     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5275
5276     if (i * 2 < NumElts) {
5277       if (V0.getOpcode() == ISD::UNDEF) {
5278         V0 = Op0.getOperand(0);
5279         if (V0.getValueType() != VT)
5280           return false;
5281       }
5282     } else {
5283       if (V1.getOpcode() == ISD::UNDEF) {
5284         V1 = Op0.getOperand(0);
5285         if (V1.getValueType() != VT)
5286           return false;
5287       }
5288       if (i * 2 == NumElts)
5289         ExpectedVExtractIdx = BaseIdx;
5290     }
5291
5292     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5293     if (I0 == ExpectedVExtractIdx)
5294       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5295     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5296       // Try to match the following dag sequence:
5297       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5298       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5299     } else
5300       CanFold = false;
5301
5302     ExpectedVExtractIdx += 2;
5303   }
5304
5305   return CanFold;
5306 }
5307
5308 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5309 /// a concat_vector.
5310 ///
5311 /// This is a helper function of LowerToHorizontalOp().
5312 /// This function expects two 256-bit vectors called V0 and V1.
5313 /// At first, each vector is split into two separate 128-bit vectors.
5314 /// Then, the resulting 128-bit vectors are used to implement two
5315 /// horizontal binary operations.
5316 ///
5317 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5318 ///
5319 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5320 /// the two new horizontal binop.
5321 /// When Mode is set, the first horizontal binop dag node would take as input
5322 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5323 /// horizontal binop dag node would take as input the lower 128-bit of V1
5324 /// and the upper 128-bit of V1.
5325 ///   Example:
5326 ///     HADD V0_LO, V0_HI
5327 ///     HADD V1_LO, V1_HI
5328 ///
5329 /// Otherwise, the first horizontal binop dag node takes as input the lower
5330 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5331 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5332 ///   Example:
5333 ///     HADD V0_LO, V1_LO
5334 ///     HADD V0_HI, V1_HI
5335 ///
5336 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5337 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5338 /// the upper 128-bits of the result.
5339 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5340                                      SDLoc DL, SelectionDAG &DAG,
5341                                      unsigned X86Opcode, bool Mode,
5342                                      bool isUndefLO, bool isUndefHI) {
5343   EVT VT = V0.getValueType();
5344   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5345          "Invalid nodes in input!");
5346
5347   unsigned NumElts = VT.getVectorNumElements();
5348   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5349   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5350   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5351   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5352   EVT NewVT = V0_LO.getValueType();
5353
5354   SDValue LO = DAG.getUNDEF(NewVT);
5355   SDValue HI = DAG.getUNDEF(NewVT);
5356
5357   if (Mode) {
5358     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5359     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5360       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5361     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5362       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5363   } else {
5364     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5365     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5366                        V1_LO->getOpcode() != ISD::UNDEF))
5367       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5368
5369     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5370                        V1_HI->getOpcode() != ISD::UNDEF))
5371       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5372   }
5373
5374   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5375 }
5376
5377 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5378 /// node.
5379 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5380                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5381   EVT VT = BV->getValueType(0);
5382   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5383       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5384     return SDValue();
5385
5386   SDLoc DL(BV);
5387   unsigned NumElts = VT.getVectorNumElements();
5388   SDValue InVec0 = DAG.getUNDEF(VT);
5389   SDValue InVec1 = DAG.getUNDEF(VT);
5390
5391   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5392           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5393
5394   // Odd-numbered elements in the input build vector are obtained from
5395   // adding two integer/float elements.
5396   // Even-numbered elements in the input build vector are obtained from
5397   // subtracting two integer/float elements.
5398   unsigned ExpectedOpcode = ISD::FSUB;
5399   unsigned NextExpectedOpcode = ISD::FADD;
5400   bool AddFound = false;
5401   bool SubFound = false;
5402
5403   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5404     SDValue Op = BV->getOperand(i);
5405
5406     // Skip 'undef' values.
5407     unsigned Opcode = Op.getOpcode();
5408     if (Opcode == ISD::UNDEF) {
5409       std::swap(ExpectedOpcode, NextExpectedOpcode);
5410       continue;
5411     }
5412
5413     // Early exit if we found an unexpected opcode.
5414     if (Opcode != ExpectedOpcode)
5415       return SDValue();
5416
5417     SDValue Op0 = Op.getOperand(0);
5418     SDValue Op1 = Op.getOperand(1);
5419
5420     // Try to match the following pattern:
5421     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5422     // Early exit if we cannot match that sequence.
5423     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5424         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5425         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5426         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5427         Op0.getOperand(1) != Op1.getOperand(1))
5428       return SDValue();
5429
5430     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5431     if (I0 != i)
5432       return SDValue();
5433
5434     // We found a valid add/sub node. Update the information accordingly.
5435     if (i & 1)
5436       AddFound = true;
5437     else
5438       SubFound = true;
5439
5440     // Update InVec0 and InVec1.
5441     if (InVec0.getOpcode() == ISD::UNDEF) {
5442       InVec0 = Op0.getOperand(0);
5443       if (InVec0.getValueType() != VT)
5444         return SDValue();
5445     }
5446     if (InVec1.getOpcode() == ISD::UNDEF) {
5447       InVec1 = Op1.getOperand(0);
5448       if (InVec1.getValueType() != VT)
5449         return SDValue();
5450     }
5451
5452     // Make sure that operands in input to each add/sub node always
5453     // come from a same pair of vectors.
5454     if (InVec0 != Op0.getOperand(0)) {
5455       if (ExpectedOpcode == ISD::FSUB)
5456         return SDValue();
5457
5458       // FADD is commutable. Try to commute the operands
5459       // and then test again.
5460       std::swap(Op0, Op1);
5461       if (InVec0 != Op0.getOperand(0))
5462         return SDValue();
5463     }
5464
5465     if (InVec1 != Op1.getOperand(0))
5466       return SDValue();
5467
5468     // Update the pair of expected opcodes.
5469     std::swap(ExpectedOpcode, NextExpectedOpcode);
5470   }
5471
5472   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5473   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5474       InVec1.getOpcode() != ISD::UNDEF)
5475     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5476
5477   return SDValue();
5478 }
5479
5480 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5481 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5482                                    const X86Subtarget *Subtarget,
5483                                    SelectionDAG &DAG) {
5484   EVT VT = BV->getValueType(0);
5485   unsigned NumElts = VT.getVectorNumElements();
5486   unsigned NumUndefsLO = 0;
5487   unsigned NumUndefsHI = 0;
5488   unsigned Half = NumElts/2;
5489
5490   // Count the number of UNDEF operands in the build_vector in input.
5491   for (unsigned i = 0, e = Half; i != e; ++i)
5492     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5493       NumUndefsLO++;
5494
5495   for (unsigned i = Half, e = NumElts; i != e; ++i)
5496     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5497       NumUndefsHI++;
5498
5499   // Early exit if this is either a build_vector of all UNDEFs or all the
5500   // operands but one are UNDEF.
5501   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5502     return SDValue();
5503
5504   SDLoc DL(BV);
5505   SDValue InVec0, InVec1;
5506   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5507     // Try to match an SSE3 float HADD/HSUB.
5508     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5509       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5510
5511     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5512       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5513   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5514     // Try to match an SSSE3 integer HADD/HSUB.
5515     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5516       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5517
5518     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5519       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5520   }
5521
5522   if (!Subtarget->hasAVX())
5523     return SDValue();
5524
5525   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5526     // Try to match an AVX horizontal add/sub of packed single/double
5527     // precision floating point values from 256-bit vectors.
5528     SDValue InVec2, InVec3;
5529     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5530         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5531         ((InVec0.getOpcode() == ISD::UNDEF ||
5532           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5533         ((InVec1.getOpcode() == ISD::UNDEF ||
5534           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5535       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5536
5537     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5538         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5539         ((InVec0.getOpcode() == ISD::UNDEF ||
5540           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5541         ((InVec1.getOpcode() == ISD::UNDEF ||
5542           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5543       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5544   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5545     // Try to match an AVX2 horizontal add/sub of signed integers.
5546     SDValue InVec2, InVec3;
5547     unsigned X86Opcode;
5548     bool CanFold = true;
5549
5550     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5551         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5552         ((InVec0.getOpcode() == ISD::UNDEF ||
5553           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5554         ((InVec1.getOpcode() == ISD::UNDEF ||
5555           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5556       X86Opcode = X86ISD::HADD;
5557     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5558         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5559         ((InVec0.getOpcode() == ISD::UNDEF ||
5560           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5561         ((InVec1.getOpcode() == ISD::UNDEF ||
5562           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5563       X86Opcode = X86ISD::HSUB;
5564     else
5565       CanFold = false;
5566
5567     if (CanFold) {
5568       // Fold this build_vector into a single horizontal add/sub.
5569       // Do this only if the target has AVX2.
5570       if (Subtarget->hasAVX2())
5571         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5572
5573       // Do not try to expand this build_vector into a pair of horizontal
5574       // add/sub if we can emit a pair of scalar add/sub.
5575       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5576         return SDValue();
5577
5578       // Convert this build_vector into a pair of horizontal binop followed by
5579       // a concat vector.
5580       bool isUndefLO = NumUndefsLO == Half;
5581       bool isUndefHI = NumUndefsHI == Half;
5582       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5583                                    isUndefLO, isUndefHI);
5584     }
5585   }
5586
5587   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5588        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5589     unsigned X86Opcode;
5590     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5591       X86Opcode = X86ISD::HADD;
5592     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5593       X86Opcode = X86ISD::HSUB;
5594     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5595       X86Opcode = X86ISD::FHADD;
5596     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5597       X86Opcode = X86ISD::FHSUB;
5598     else
5599       return SDValue();
5600
5601     // Don't try to expand this build_vector into a pair of horizontal add/sub
5602     // if we can simply emit a pair of scalar add/sub.
5603     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5604       return SDValue();
5605
5606     // Convert this build_vector into two horizontal add/sub followed by
5607     // a concat vector.
5608     bool isUndefLO = NumUndefsLO == Half;
5609     bool isUndefHI = NumUndefsHI == Half;
5610     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5611                                  isUndefLO, isUndefHI);
5612   }
5613
5614   return SDValue();
5615 }
5616
5617 SDValue
5618 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5619   SDLoc dl(Op);
5620
5621   MVT VT = Op.getSimpleValueType();
5622   MVT ExtVT = VT.getVectorElementType();
5623   unsigned NumElems = Op.getNumOperands();
5624
5625   // Generate vectors for predicate vectors.
5626   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5627     return LowerBUILD_VECTORvXi1(Op, DAG);
5628
5629   // Vectors containing all zeros can be matched by pxor and xorps later
5630   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5631     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5632     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5633     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5634       return Op;
5635
5636     return getZeroVector(VT, Subtarget, DAG, dl);
5637   }
5638
5639   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5640   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5641   // vpcmpeqd on 256-bit vectors.
5642   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5643     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5644       return Op;
5645
5646     if (!VT.is512BitVector())
5647       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5648   }
5649
5650   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5651   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5652     return AddSub;
5653   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5654     return HorizontalOp;
5655   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5656     return Broadcast;
5657
5658   unsigned EVTBits = ExtVT.getSizeInBits();
5659
5660   unsigned NumZero  = 0;
5661   unsigned NumNonZero = 0;
5662   unsigned NonZeros = 0;
5663   bool IsAllConstants = true;
5664   SmallSet<SDValue, 8> Values;
5665   for (unsigned i = 0; i < NumElems; ++i) {
5666     SDValue Elt = Op.getOperand(i);
5667     if (Elt.getOpcode() == ISD::UNDEF)
5668       continue;
5669     Values.insert(Elt);
5670     if (Elt.getOpcode() != ISD::Constant &&
5671         Elt.getOpcode() != ISD::ConstantFP)
5672       IsAllConstants = false;
5673     if (X86::isZeroNode(Elt))
5674       NumZero++;
5675     else {
5676       NonZeros |= (1 << i);
5677       NumNonZero++;
5678     }
5679   }
5680
5681   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5682   if (NumNonZero == 0)
5683     return DAG.getUNDEF(VT);
5684
5685   // Special case for single non-zero, non-undef, element.
5686   if (NumNonZero == 1) {
5687     unsigned Idx = countTrailingZeros(NonZeros);
5688     SDValue Item = Op.getOperand(Idx);
5689
5690     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5691     // the value are obviously zero, truncate the value to i32 and do the
5692     // insertion that way.  Only do this if the value is non-constant or if the
5693     // value is a constant being inserted into element 0.  It is cheaper to do
5694     // a constant pool load than it is to do a movd + shuffle.
5695     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5696         (!IsAllConstants || Idx == 0)) {
5697       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5698         // Handle SSE only.
5699         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5700         EVT VecVT = MVT::v4i32;
5701
5702         // Truncate the value (which may itself be a constant) to i32, and
5703         // convert it to a vector with movd (S2V+shuffle to zero extend).
5704         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5705         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5706         return DAG.getNode(
5707             ISD::BITCAST, dl, VT,
5708             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5709       }
5710     }
5711
5712     // If we have a constant or non-constant insertion into the low element of
5713     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5714     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5715     // depending on what the source datatype is.
5716     if (Idx == 0) {
5717       if (NumZero == 0)
5718         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5719
5720       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5721           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5722         if (VT.is512BitVector()) {
5723           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5724           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5725                              Item, DAG.getIntPtrConstant(0));
5726         }
5727         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5728                "Expected an SSE value type!");
5729         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5730         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5731         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5732       }
5733
5734       // We can't directly insert an i8 or i16 into a vector, so zero extend
5735       // it to i32 first.
5736       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5737         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5738         if (VT.is256BitVector()) {
5739           if (Subtarget->hasAVX()) {
5740             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5741             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5742           } else {
5743             // Without AVX, we need to extend to a 128-bit vector and then
5744             // insert into the 256-bit vector.
5745             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5746             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5747             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5748           }
5749         } else {
5750           assert(VT.is128BitVector() && "Expected an SSE value type!");
5751           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5752           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5753         }
5754         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5755       }
5756     }
5757
5758     // Is it a vector logical left shift?
5759     if (NumElems == 2 && Idx == 1 &&
5760         X86::isZeroNode(Op.getOperand(0)) &&
5761         !X86::isZeroNode(Op.getOperand(1))) {
5762       unsigned NumBits = VT.getSizeInBits();
5763       return getVShift(true, VT,
5764                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5765                                    VT, Op.getOperand(1)),
5766                        NumBits/2, DAG, *this, dl);
5767     }
5768
5769     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5770       return SDValue();
5771
5772     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5773     // is a non-constant being inserted into an element other than the low one,
5774     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5775     // movd/movss) to move this into the low element, then shuffle it into
5776     // place.
5777     if (EVTBits == 32) {
5778       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5779       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5780     }
5781   }
5782
5783   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5784   if (Values.size() == 1) {
5785     if (EVTBits == 32) {
5786       // Instead of a shuffle like this:
5787       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5788       // Check if it's possible to issue this instead.
5789       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5790       unsigned Idx = countTrailingZeros(NonZeros);
5791       SDValue Item = Op.getOperand(Idx);
5792       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5793         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5794     }
5795     return SDValue();
5796   }
5797
5798   // A vector full of immediates; various special cases are already
5799   // handled, so this is best done with a single constant-pool load.
5800   if (IsAllConstants)
5801     return SDValue();
5802
5803   // For AVX-length vectors, see if we can use a vector load to get all of the
5804   // elements, otherwise build the individual 128-bit pieces and use
5805   // shuffles to put them in place.
5806   if (VT.is256BitVector() || VT.is512BitVector()) {
5807     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5808
5809     // Check for a build vector of consecutive loads.
5810     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5811       return LD;
5812
5813     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5814
5815     // Build both the lower and upper subvector.
5816     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5817                                 makeArrayRef(&V[0], NumElems/2));
5818     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5819                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5820
5821     // Recreate the wider vector with the lower and upper part.
5822     if (VT.is256BitVector())
5823       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5824     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5825   }
5826
5827   // Let legalizer expand 2-wide build_vectors.
5828   if (EVTBits == 64) {
5829     if (NumNonZero == 1) {
5830       // One half is zero or undef.
5831       unsigned Idx = countTrailingZeros(NonZeros);
5832       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5833                                  Op.getOperand(Idx));
5834       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5835     }
5836     return SDValue();
5837   }
5838
5839   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5840   if (EVTBits == 8 && NumElems == 16)
5841     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5842                                         Subtarget, *this))
5843       return V;
5844
5845   if (EVTBits == 16 && NumElems == 8)
5846     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5847                                       Subtarget, *this))
5848       return V;
5849
5850   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5851   if (EVTBits == 32 && NumElems == 4)
5852     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5853       return V;
5854
5855   // If element VT is == 32 bits, turn it into a number of shuffles.
5856   SmallVector<SDValue, 8> V(NumElems);
5857   if (NumElems == 4 && NumZero > 0) {
5858     for (unsigned i = 0; i < 4; ++i) {
5859       bool isZero = !(NonZeros & (1 << i));
5860       if (isZero)
5861         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5862       else
5863         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5864     }
5865
5866     for (unsigned i = 0; i < 2; ++i) {
5867       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5868         default: break;
5869         case 0:
5870           V[i] = V[i*2];  // Must be a zero vector.
5871           break;
5872         case 1:
5873           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5874           break;
5875         case 2:
5876           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5877           break;
5878         case 3:
5879           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5880           break;
5881       }
5882     }
5883
5884     bool Reverse1 = (NonZeros & 0x3) == 2;
5885     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5886     int MaskVec[] = {
5887       Reverse1 ? 1 : 0,
5888       Reverse1 ? 0 : 1,
5889       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5890       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5891     };
5892     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5893   }
5894
5895   if (Values.size() > 1 && VT.is128BitVector()) {
5896     // Check for a build vector of consecutive loads.
5897     for (unsigned i = 0; i < NumElems; ++i)
5898       V[i] = Op.getOperand(i);
5899
5900     // Check for elements which are consecutive loads.
5901     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5902       return LD;
5903
5904     // Check for a build vector from mostly shuffle plus few inserting.
5905     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5906       return Sh;
5907
5908     // For SSE 4.1, use insertps to put the high elements into the low element.
5909     if (Subtarget->hasSSE41()) {
5910       SDValue Result;
5911       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5912         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5913       else
5914         Result = DAG.getUNDEF(VT);
5915
5916       for (unsigned i = 1; i < NumElems; ++i) {
5917         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5918         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5919                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5920       }
5921       return Result;
5922     }
5923
5924     // Otherwise, expand into a number of unpckl*, start by extending each of
5925     // our (non-undef) elements to the full vector width with the element in the
5926     // bottom slot of the vector (which generates no code for SSE).
5927     for (unsigned i = 0; i < NumElems; ++i) {
5928       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5929         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5930       else
5931         V[i] = DAG.getUNDEF(VT);
5932     }
5933
5934     // Next, we iteratively mix elements, e.g. for v4f32:
5935     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5936     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5937     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5938     unsigned EltStride = NumElems >> 1;
5939     while (EltStride != 0) {
5940       for (unsigned i = 0; i < EltStride; ++i) {
5941         // If V[i+EltStride] is undef and this is the first round of mixing,
5942         // then it is safe to just drop this shuffle: V[i] is already in the
5943         // right place, the one element (since it's the first round) being
5944         // inserted as undef can be dropped.  This isn't safe for successive
5945         // rounds because they will permute elements within both vectors.
5946         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5947             EltStride == NumElems/2)
5948           continue;
5949
5950         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5951       }
5952       EltStride >>= 1;
5953     }
5954     return V[0];
5955   }
5956   return SDValue();
5957 }
5958
5959 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5960 // to create 256-bit vectors from two other 128-bit ones.
5961 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5962   SDLoc dl(Op);
5963   MVT ResVT = Op.getSimpleValueType();
5964
5965   assert((ResVT.is256BitVector() ||
5966           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5967
5968   SDValue V1 = Op.getOperand(0);
5969   SDValue V2 = Op.getOperand(1);
5970   unsigned NumElems = ResVT.getVectorNumElements();
5971   if (ResVT.is256BitVector())
5972     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5973
5974   if (Op.getNumOperands() == 4) {
5975     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5976                                 ResVT.getVectorNumElements()/2);
5977     SDValue V3 = Op.getOperand(2);
5978     SDValue V4 = Op.getOperand(3);
5979     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
5980       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
5981   }
5982   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5983 }
5984
5985 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
5986                                        const X86Subtarget *Subtarget,
5987                                        SelectionDAG & DAG) {
5988   SDLoc dl(Op);
5989   MVT ResVT = Op.getSimpleValueType();
5990   unsigned NumOfOperands = Op.getNumOperands();
5991
5992   assert(isPowerOf2_32(NumOfOperands) &&
5993          "Unexpected number of operands in CONCAT_VECTORS");
5994
5995   if (NumOfOperands > 2) {
5996     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5997                                   ResVT.getVectorNumElements()/2);
5998     SmallVector<SDValue, 2> Ops;
5999     for (unsigned i = 0; i < NumOfOperands/2; i++)
6000       Ops.push_back(Op.getOperand(i));
6001     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6002     Ops.clear();
6003     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6004       Ops.push_back(Op.getOperand(i));
6005     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6006     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6007   }
6008
6009   SDValue V1 = Op.getOperand(0);
6010   SDValue V2 = Op.getOperand(1);
6011   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6012   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6013
6014   if (IsZeroV1 && IsZeroV2)
6015     return getZeroVector(ResVT, Subtarget, DAG, dl);
6016
6017   SDValue ZeroIdx = DAG.getIntPtrConstant(0);
6018   SDValue Undef = DAG.getUNDEF(ResVT);
6019   unsigned NumElems = ResVT.getVectorNumElements();
6020   SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
6021
6022   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6023   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6024   if (IsZeroV1)
6025     return V2;
6026
6027   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6028   // Zero the upper bits of V1
6029   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6030   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6031   if (IsZeroV2)
6032     return V1;
6033   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6034 }
6035
6036 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6037                                    const X86Subtarget *Subtarget,
6038                                    SelectionDAG &DAG) {
6039   MVT VT = Op.getSimpleValueType();
6040   if (VT.getVectorElementType() == MVT::i1)
6041     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6042
6043   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6044          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6045           Op.getNumOperands() == 4)));
6046
6047   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6048   // from two other 128-bit ones.
6049
6050   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6051   return LowerAVXCONCAT_VECTORS(Op, DAG);
6052 }
6053
6054
6055 //===----------------------------------------------------------------------===//
6056 // Vector shuffle lowering
6057 //
6058 // This is an experimental code path for lowering vector shuffles on x86. It is
6059 // designed to handle arbitrary vector shuffles and blends, gracefully
6060 // degrading performance as necessary. It works hard to recognize idiomatic
6061 // shuffles and lower them to optimal instruction patterns without leaving
6062 // a framework that allows reasonably efficient handling of all vector shuffle
6063 // patterns.
6064 //===----------------------------------------------------------------------===//
6065
6066 /// \brief Tiny helper function to identify a no-op mask.
6067 ///
6068 /// This is a somewhat boring predicate function. It checks whether the mask
6069 /// array input, which is assumed to be a single-input shuffle mask of the kind
6070 /// used by the X86 shuffle instructions (not a fully general
6071 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6072 /// in-place shuffle are 'no-op's.
6073 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6074   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6075     if (Mask[i] != -1 && Mask[i] != i)
6076       return false;
6077   return true;
6078 }
6079
6080 /// \brief Helper function to classify a mask as a single-input mask.
6081 ///
6082 /// This isn't a generic single-input test because in the vector shuffle
6083 /// lowering we canonicalize single inputs to be the first input operand. This
6084 /// means we can more quickly test for a single input by only checking whether
6085 /// an input from the second operand exists. We also assume that the size of
6086 /// mask corresponds to the size of the input vectors which isn't true in the
6087 /// fully general case.
6088 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6089   for (int M : Mask)
6090     if (M >= (int)Mask.size())
6091       return false;
6092   return true;
6093 }
6094
6095 /// \brief Test whether there are elements crossing 128-bit lanes in this
6096 /// shuffle mask.
6097 ///
6098 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6099 /// and we routinely test for these.
6100 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6101   int LaneSize = 128 / VT.getScalarSizeInBits();
6102   int Size = Mask.size();
6103   for (int i = 0; i < Size; ++i)
6104     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6105       return true;
6106   return false;
6107 }
6108
6109 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6110 ///
6111 /// This checks a shuffle mask to see if it is performing the same
6112 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6113 /// that it is also not lane-crossing. It may however involve a blend from the
6114 /// same lane of a second vector.
6115 ///
6116 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6117 /// non-trivial to compute in the face of undef lanes. The representation is
6118 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6119 /// entries from both V1 and V2 inputs to the wider mask.
6120 static bool
6121 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6122                                 SmallVectorImpl<int> &RepeatedMask) {
6123   int LaneSize = 128 / VT.getScalarSizeInBits();
6124   RepeatedMask.resize(LaneSize, -1);
6125   int Size = Mask.size();
6126   for (int i = 0; i < Size; ++i) {
6127     if (Mask[i] < 0)
6128       continue;
6129     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6130       // This entry crosses lanes, so there is no way to model this shuffle.
6131       return false;
6132
6133     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6134     if (RepeatedMask[i % LaneSize] == -1)
6135       // This is the first non-undef entry in this slot of a 128-bit lane.
6136       RepeatedMask[i % LaneSize] =
6137           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6138     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6139       // Found a mismatch with the repeated mask.
6140       return false;
6141   }
6142   return true;
6143 }
6144
6145 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6146 /// arguments.
6147 ///
6148 /// This is a fast way to test a shuffle mask against a fixed pattern:
6149 ///
6150 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6151 ///
6152 /// It returns true if the mask is exactly as wide as the argument list, and
6153 /// each element of the mask is either -1 (signifying undef) or the value given
6154 /// in the argument.
6155 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6156                                 ArrayRef<int> ExpectedMask) {
6157   if (Mask.size() != ExpectedMask.size())
6158     return false;
6159
6160   int Size = Mask.size();
6161
6162   // If the values are build vectors, we can look through them to find
6163   // equivalent inputs that make the shuffles equivalent.
6164   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6165   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6166
6167   for (int i = 0; i < Size; ++i)
6168     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6169       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6170       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6171       if (!MaskBV || !ExpectedBV ||
6172           MaskBV->getOperand(Mask[i] % Size) !=
6173               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6174         return false;
6175     }
6176
6177   return true;
6178 }
6179
6180 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6181 ///
6182 /// This helper function produces an 8-bit shuffle immediate corresponding to
6183 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6184 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6185 /// example.
6186 ///
6187 /// NB: We rely heavily on "undef" masks preserving the input lane.
6188 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6189                                           SelectionDAG &DAG) {
6190   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6191   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6192   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6193   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6194   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6195
6196   unsigned Imm = 0;
6197   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6198   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6199   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6200   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6201   return DAG.getConstant(Imm, MVT::i8);
6202 }
6203
6204 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6205 ///
6206 /// This is used as a fallback approach when first class blend instructions are
6207 /// unavailable. Currently it is only suitable for integer vectors, but could
6208 /// be generalized for floating point vectors if desirable.
6209 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6210                                             SDValue V2, ArrayRef<int> Mask,
6211                                             SelectionDAG &DAG) {
6212   assert(VT.isInteger() && "Only supports integer vector types!");
6213   MVT EltVT = VT.getScalarType();
6214   int NumEltBits = EltVT.getSizeInBits();
6215   SDValue Zero = DAG.getConstant(0, EltVT);
6216   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), EltVT);
6217   SmallVector<SDValue, 16> MaskOps;
6218   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6219     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6220       return SDValue(); // Shuffled input!
6221     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6222   }
6223
6224   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6225   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6226   // We have to cast V2 around.
6227   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6228   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6229                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6230                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6231                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6232   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6233 }
6234
6235 /// \brief Try to emit a blend instruction for a shuffle.
6236 ///
6237 /// This doesn't do any checks for the availability of instructions for blending
6238 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6239 /// be matched in the backend with the type given. What it does check for is
6240 /// that the shuffle mask is in fact a blend.
6241 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6242                                          SDValue V2, ArrayRef<int> Mask,
6243                                          const X86Subtarget *Subtarget,
6244                                          SelectionDAG &DAG) {
6245   unsigned BlendMask = 0;
6246   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6247     if (Mask[i] >= Size) {
6248       if (Mask[i] != i + Size)
6249         return SDValue(); // Shuffled V2 input!
6250       BlendMask |= 1u << i;
6251       continue;
6252     }
6253     if (Mask[i] >= 0 && Mask[i] != i)
6254       return SDValue(); // Shuffled V1 input!
6255   }
6256   switch (VT.SimpleTy) {
6257   case MVT::v2f64:
6258   case MVT::v4f32:
6259   case MVT::v4f64:
6260   case MVT::v8f32:
6261     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6262                        DAG.getConstant(BlendMask, MVT::i8));
6263
6264   case MVT::v4i64:
6265   case MVT::v8i32:
6266     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6267     // FALLTHROUGH
6268   case MVT::v2i64:
6269   case MVT::v4i32:
6270     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6271     // that instruction.
6272     if (Subtarget->hasAVX2()) {
6273       // Scale the blend by the number of 32-bit dwords per element.
6274       int Scale =  VT.getScalarSizeInBits() / 32;
6275       BlendMask = 0;
6276       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6277         if (Mask[i] >= Size)
6278           for (int j = 0; j < Scale; ++j)
6279             BlendMask |= 1u << (i * Scale + j);
6280
6281       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6282       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6283       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6284       return DAG.getNode(ISD::BITCAST, DL, VT,
6285                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6286                                      DAG.getConstant(BlendMask, MVT::i8)));
6287     }
6288     // FALLTHROUGH
6289   case MVT::v8i16: {
6290     // For integer shuffles we need to expand the mask and cast the inputs to
6291     // v8i16s prior to blending.
6292     int Scale = 8 / VT.getVectorNumElements();
6293     BlendMask = 0;
6294     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6295       if (Mask[i] >= Size)
6296         for (int j = 0; j < Scale; ++j)
6297           BlendMask |= 1u << (i * Scale + j);
6298
6299     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6300     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6301     return DAG.getNode(ISD::BITCAST, DL, VT,
6302                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6303                                    DAG.getConstant(BlendMask, MVT::i8)));
6304   }
6305
6306   case MVT::v16i16: {
6307     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6308     SmallVector<int, 8> RepeatedMask;
6309     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6310       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6311       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6312       BlendMask = 0;
6313       for (int i = 0; i < 8; ++i)
6314         if (RepeatedMask[i] >= 16)
6315           BlendMask |= 1u << i;
6316       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6317                          DAG.getConstant(BlendMask, MVT::i8));
6318     }
6319   }
6320     // FALLTHROUGH
6321   case MVT::v16i8:
6322   case MVT::v32i8: {
6323     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6324            "256-bit byte-blends require AVX2 support!");
6325
6326     // Scale the blend by the number of bytes per element.
6327     int Scale = VT.getScalarSizeInBits() / 8;
6328
6329     // This form of blend is always done on bytes. Compute the byte vector
6330     // type.
6331     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6332
6333     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6334     // mix of LLVM's code generator and the x86 backend. We tell the code
6335     // generator that boolean values in the elements of an x86 vector register
6336     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6337     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6338     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6339     // of the element (the remaining are ignored) and 0 in that high bit would
6340     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6341     // the LLVM model for boolean values in vector elements gets the relevant
6342     // bit set, it is set backwards and over constrained relative to x86's
6343     // actual model.
6344     SmallVector<SDValue, 32> VSELECTMask;
6345     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6346       for (int j = 0; j < Scale; ++j)
6347         VSELECTMask.push_back(
6348             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6349                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8));
6350
6351     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6352     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6353     return DAG.getNode(
6354         ISD::BITCAST, DL, VT,
6355         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6356                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6357                     V1, V2));
6358   }
6359
6360   default:
6361     llvm_unreachable("Not a supported integer vector type!");
6362   }
6363 }
6364
6365 /// \brief Try to lower as a blend of elements from two inputs followed by
6366 /// a single-input permutation.
6367 ///
6368 /// This matches the pattern where we can blend elements from two inputs and
6369 /// then reduce the shuffle to a single-input permutation.
6370 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6371                                                    SDValue V2,
6372                                                    ArrayRef<int> Mask,
6373                                                    SelectionDAG &DAG) {
6374   // We build up the blend mask while checking whether a blend is a viable way
6375   // to reduce the shuffle.
6376   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6377   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6378
6379   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6380     if (Mask[i] < 0)
6381       continue;
6382
6383     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6384
6385     if (BlendMask[Mask[i] % Size] == -1)
6386       BlendMask[Mask[i] % Size] = Mask[i];
6387     else if (BlendMask[Mask[i] % Size] != Mask[i])
6388       return SDValue(); // Can't blend in the needed input!
6389
6390     PermuteMask[i] = Mask[i] % Size;
6391   }
6392
6393   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6394   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6395 }
6396
6397 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6398 /// blends and permutes.
6399 ///
6400 /// This matches the extremely common pattern for handling combined
6401 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6402 /// operations. It will try to pick the best arrangement of shuffles and
6403 /// blends.
6404 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6405                                                           SDValue V1,
6406                                                           SDValue V2,
6407                                                           ArrayRef<int> Mask,
6408                                                           SelectionDAG &DAG) {
6409   // Shuffle the input elements into the desired positions in V1 and V2 and
6410   // blend them together.
6411   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6412   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6413   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6414   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6415     if (Mask[i] >= 0 && Mask[i] < Size) {
6416       V1Mask[i] = Mask[i];
6417       BlendMask[i] = i;
6418     } else if (Mask[i] >= Size) {
6419       V2Mask[i] = Mask[i] - Size;
6420       BlendMask[i] = i + Size;
6421     }
6422
6423   // Try to lower with the simpler initial blend strategy unless one of the
6424   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6425   // shuffle may be able to fold with a load or other benefit. However, when
6426   // we'll have to do 2x as many shuffles in order to achieve this, blending
6427   // first is a better strategy.
6428   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6429     if (SDValue BlendPerm =
6430             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6431       return BlendPerm;
6432
6433   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6434   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6435   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6436 }
6437
6438 /// \brief Try to lower a vector shuffle as a byte rotation.
6439 ///
6440 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6441 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6442 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6443 /// try to generically lower a vector shuffle through such an pattern. It
6444 /// does not check for the profitability of lowering either as PALIGNR or
6445 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6446 /// This matches shuffle vectors that look like:
6447 ///
6448 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6449 ///
6450 /// Essentially it concatenates V1 and V2, shifts right by some number of
6451 /// elements, and takes the low elements as the result. Note that while this is
6452 /// specified as a *right shift* because x86 is little-endian, it is a *left
6453 /// rotate* of the vector lanes.
6454 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6455                                               SDValue V2,
6456                                               ArrayRef<int> Mask,
6457                                               const X86Subtarget *Subtarget,
6458                                               SelectionDAG &DAG) {
6459   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6460
6461   int NumElts = Mask.size();
6462   int NumLanes = VT.getSizeInBits() / 128;
6463   int NumLaneElts = NumElts / NumLanes;
6464
6465   // We need to detect various ways of spelling a rotation:
6466   //   [11, 12, 13, 14, 15,  0,  1,  2]
6467   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6468   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6469   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6470   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6471   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6472   int Rotation = 0;
6473   SDValue Lo, Hi;
6474   for (int l = 0; l < NumElts; l += NumLaneElts) {
6475     for (int i = 0; i < NumLaneElts; ++i) {
6476       if (Mask[l + i] == -1)
6477         continue;
6478       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6479
6480       // Get the mod-Size index and lane correct it.
6481       int LaneIdx = (Mask[l + i] % NumElts) - l;
6482       // Make sure it was in this lane.
6483       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6484         return SDValue();
6485
6486       // Determine where a rotated vector would have started.
6487       int StartIdx = i - LaneIdx;
6488       if (StartIdx == 0)
6489         // The identity rotation isn't interesting, stop.
6490         return SDValue();
6491
6492       // If we found the tail of a vector the rotation must be the missing
6493       // front. If we found the head of a vector, it must be how much of the
6494       // head.
6495       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6496
6497       if (Rotation == 0)
6498         Rotation = CandidateRotation;
6499       else if (Rotation != CandidateRotation)
6500         // The rotations don't match, so we can't match this mask.
6501         return SDValue();
6502
6503       // Compute which value this mask is pointing at.
6504       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6505
6506       // Compute which of the two target values this index should be assigned
6507       // to. This reflects whether the high elements are remaining or the low
6508       // elements are remaining.
6509       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6510
6511       // Either set up this value if we've not encountered it before, or check
6512       // that it remains consistent.
6513       if (!TargetV)
6514         TargetV = MaskV;
6515       else if (TargetV != MaskV)
6516         // This may be a rotation, but it pulls from the inputs in some
6517         // unsupported interleaving.
6518         return SDValue();
6519     }
6520   }
6521
6522   // Check that we successfully analyzed the mask, and normalize the results.
6523   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6524   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6525   if (!Lo)
6526     Lo = Hi;
6527   else if (!Hi)
6528     Hi = Lo;
6529
6530   // The actual rotate instruction rotates bytes, so we need to scale the
6531   // rotation based on how many bytes are in the vector lane.
6532   int Scale = 16 / NumLaneElts;
6533
6534   // SSSE3 targets can use the palignr instruction.
6535   if (Subtarget->hasSSSE3()) {
6536     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6537     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6538     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6539     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6540
6541     return DAG.getNode(ISD::BITCAST, DL, VT,
6542                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6543                                    DAG.getConstant(Rotation * Scale, MVT::i8)));
6544   }
6545
6546   assert(VT.getSizeInBits() == 128 &&
6547          "Rotate-based lowering only supports 128-bit lowering!");
6548   assert(Mask.size() <= 16 &&
6549          "Can shuffle at most 16 bytes in a 128-bit vector!");
6550
6551   // Default SSE2 implementation
6552   int LoByteShift = 16 - Rotation * Scale;
6553   int HiByteShift = Rotation * Scale;
6554
6555   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6556   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6557   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6558
6559   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6560                                 DAG.getConstant(LoByteShift, MVT::i8));
6561   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6562                                 DAG.getConstant(HiByteShift, MVT::i8));
6563   return DAG.getNode(ISD::BITCAST, DL, VT,
6564                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6565 }
6566
6567 /// \brief Compute whether each element of a shuffle is zeroable.
6568 ///
6569 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6570 /// Either it is an undef element in the shuffle mask, the element of the input
6571 /// referenced is undef, or the element of the input referenced is known to be
6572 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6573 /// as many lanes with this technique as possible to simplify the remaining
6574 /// shuffle.
6575 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6576                                                      SDValue V1, SDValue V2) {
6577   SmallBitVector Zeroable(Mask.size(), false);
6578
6579   while (V1.getOpcode() == ISD::BITCAST)
6580     V1 = V1->getOperand(0);
6581   while (V2.getOpcode() == ISD::BITCAST)
6582     V2 = V2->getOperand(0);
6583
6584   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6585   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6586
6587   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6588     int M = Mask[i];
6589     // Handle the easy cases.
6590     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6591       Zeroable[i] = true;
6592       continue;
6593     }
6594
6595     // If this is an index into a build_vector node (which has the same number
6596     // of elements), dig out the input value and use it.
6597     SDValue V = M < Size ? V1 : V2;
6598     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6599       continue;
6600
6601     SDValue Input = V.getOperand(M % Size);
6602     // The UNDEF opcode check really should be dead code here, but not quite
6603     // worth asserting on (it isn't invalid, just unexpected).
6604     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6605       Zeroable[i] = true;
6606   }
6607
6608   return Zeroable;
6609 }
6610
6611 /// \brief Try to emit a bitmask instruction for a shuffle.
6612 ///
6613 /// This handles cases where we can model a blend exactly as a bitmask due to
6614 /// one of the inputs being zeroable.
6615 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6616                                            SDValue V2, ArrayRef<int> Mask,
6617                                            SelectionDAG &DAG) {
6618   MVT EltVT = VT.getScalarType();
6619   int NumEltBits = EltVT.getSizeInBits();
6620   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6621   SDValue Zero = DAG.getConstant(0, IntEltVT);
6622   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
6623   if (EltVT.isFloatingPoint()) {
6624     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6625     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6626   }
6627   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6628   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6629   SDValue V;
6630   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6631     if (Zeroable[i])
6632       continue;
6633     if (Mask[i] % Size != i)
6634       return SDValue(); // Not a blend.
6635     if (!V)
6636       V = Mask[i] < Size ? V1 : V2;
6637     else if (V != (Mask[i] < Size ? V1 : V2))
6638       return SDValue(); // Can only let one input through the mask.
6639
6640     VMaskOps[i] = AllOnes;
6641   }
6642   if (!V)
6643     return SDValue(); // No non-zeroable elements!
6644
6645   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6646   V = DAG.getNode(VT.isFloatingPoint()
6647                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6648                   DL, VT, V, VMask);
6649   return V;
6650 }
6651
6652 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6653 ///
6654 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6655 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6656 /// matches elements from one of the input vectors shuffled to the left or
6657 /// right with zeroable elements 'shifted in'. It handles both the strictly
6658 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6659 /// quad word lane.
6660 ///
6661 /// PSHL : (little-endian) left bit shift.
6662 /// [ zz, 0, zz,  2 ]
6663 /// [ -1, 4, zz, -1 ]
6664 /// PSRL : (little-endian) right bit shift.
6665 /// [  1, zz,  3, zz]
6666 /// [ -1, -1,  7, zz]
6667 /// PSLLDQ : (little-endian) left byte shift
6668 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6669 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6670 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6671 /// PSRLDQ : (little-endian) right byte shift
6672 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6673 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6674 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6675 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6676                                          SDValue V2, ArrayRef<int> Mask,
6677                                          SelectionDAG &DAG) {
6678   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6679
6680   int Size = Mask.size();
6681   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6682
6683   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6684     for (int i = 0; i < Size; i += Scale)
6685       for (int j = 0; j < Shift; ++j)
6686         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6687           return false;
6688
6689     return true;
6690   };
6691
6692   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6693     for (int i = 0; i != Size; i += Scale) {
6694       unsigned Pos = Left ? i + Shift : i;
6695       unsigned Low = Left ? i : i + Shift;
6696       unsigned Len = Scale - Shift;
6697       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6698                                       Low + (V == V1 ? 0 : Size)))
6699         return SDValue();
6700     }
6701
6702     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6703     bool ByteShift = ShiftEltBits > 64;
6704     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6705                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6706     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6707
6708     // Normalize the scale for byte shifts to still produce an i64 element
6709     // type.
6710     Scale = ByteShift ? Scale / 2 : Scale;
6711
6712     // We need to round trip through the appropriate type for the shift.
6713     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6714     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6715     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6716            "Illegal integer vector type");
6717     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6718
6719     V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
6720     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6721   };
6722
6723   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6724   // keep doubling the size of the integer elements up to that. We can
6725   // then shift the elements of the integer vector by whole multiples of
6726   // their width within the elements of the larger integer vector. Test each
6727   // multiple to see if we can find a match with the moved element indices
6728   // and that the shifted in elements are all zeroable.
6729   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6730     for (int Shift = 1; Shift != Scale; ++Shift)
6731       for (bool Left : {true, false})
6732         if (CheckZeros(Shift, Scale, Left))
6733           for (SDValue V : {V1, V2})
6734             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6735               return Match;
6736
6737   // no match
6738   return SDValue();
6739 }
6740
6741 /// \brief Lower a vector shuffle as a zero or any extension.
6742 ///
6743 /// Given a specific number of elements, element bit width, and extension
6744 /// stride, produce either a zero or any extension based on the available
6745 /// features of the subtarget.
6746 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6747     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6748     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6749   assert(Scale > 1 && "Need a scale to extend.");
6750   int NumElements = VT.getVectorNumElements();
6751   int EltBits = VT.getScalarSizeInBits();
6752   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6753          "Only 8, 16, and 32 bit elements can be extended.");
6754   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6755
6756   // Found a valid zext mask! Try various lowering strategies based on the
6757   // input type and available ISA extensions.
6758   if (Subtarget->hasSSE41()) {
6759     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6760                                  NumElements / Scale);
6761     return DAG.getNode(ISD::BITCAST, DL, VT,
6762                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6763   }
6764
6765   // For any extends we can cheat for larger element sizes and use shuffle
6766   // instructions that can fold with a load and/or copy.
6767   if (AnyExt && EltBits == 32) {
6768     int PSHUFDMask[4] = {0, -1, 1, -1};
6769     return DAG.getNode(
6770         ISD::BITCAST, DL, VT,
6771         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6772                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6773                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
6774   }
6775   if (AnyExt && EltBits == 16 && Scale > 2) {
6776     int PSHUFDMask[4] = {0, -1, 0, -1};
6777     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6778                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6779                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
6780     int PSHUFHWMask[4] = {1, -1, -1, -1};
6781     return DAG.getNode(
6782         ISD::BITCAST, DL, VT,
6783         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6784                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6785                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
6786   }
6787
6788   // If this would require more than 2 unpack instructions to expand, use
6789   // pshufb when available. We can only use more than 2 unpack instructions
6790   // when zero extending i8 elements which also makes it easier to use pshufb.
6791   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6792     assert(NumElements == 16 && "Unexpected byte vector width!");
6793     SDValue PSHUFBMask[16];
6794     for (int i = 0; i < 16; ++i)
6795       PSHUFBMask[i] =
6796           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
6797     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6798     return DAG.getNode(ISD::BITCAST, DL, VT,
6799                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6800                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6801                                                MVT::v16i8, PSHUFBMask)));
6802   }
6803
6804   // Otherwise emit a sequence of unpacks.
6805   do {
6806     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6807     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6808                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6809     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6810     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6811     Scale /= 2;
6812     EltBits *= 2;
6813     NumElements /= 2;
6814   } while (Scale > 1);
6815   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6816 }
6817
6818 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6819 ///
6820 /// This routine will try to do everything in its power to cleverly lower
6821 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6822 /// check for the profitability of this lowering,  it tries to aggressively
6823 /// match this pattern. It will use all of the micro-architectural details it
6824 /// can to emit an efficient lowering. It handles both blends with all-zero
6825 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6826 /// masking out later).
6827 ///
6828 /// The reason we have dedicated lowering for zext-style shuffles is that they
6829 /// are both incredibly common and often quite performance sensitive.
6830 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6831     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6832     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6833   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6834
6835   int Bits = VT.getSizeInBits();
6836   int NumElements = VT.getVectorNumElements();
6837   assert(VT.getScalarSizeInBits() <= 32 &&
6838          "Exceeds 32-bit integer zero extension limit");
6839   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6840
6841   // Define a helper function to check a particular ext-scale and lower to it if
6842   // valid.
6843   auto Lower = [&](int Scale) -> SDValue {
6844     SDValue InputV;
6845     bool AnyExt = true;
6846     for (int i = 0; i < NumElements; ++i) {
6847       if (Mask[i] == -1)
6848         continue; // Valid anywhere but doesn't tell us anything.
6849       if (i % Scale != 0) {
6850         // Each of the extended elements need to be zeroable.
6851         if (!Zeroable[i])
6852           return SDValue();
6853
6854         // We no longer are in the anyext case.
6855         AnyExt = false;
6856         continue;
6857       }
6858
6859       // Each of the base elements needs to be consecutive indices into the
6860       // same input vector.
6861       SDValue V = Mask[i] < NumElements ? V1 : V2;
6862       if (!InputV)
6863         InputV = V;
6864       else if (InputV != V)
6865         return SDValue(); // Flip-flopping inputs.
6866
6867       if (Mask[i] % NumElements != i / Scale)
6868         return SDValue(); // Non-consecutive strided elements.
6869     }
6870
6871     // If we fail to find an input, we have a zero-shuffle which should always
6872     // have already been handled.
6873     // FIXME: Maybe handle this here in case during blending we end up with one?
6874     if (!InputV)
6875       return SDValue();
6876
6877     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6878         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6879   };
6880
6881   // The widest scale possible for extending is to a 64-bit integer.
6882   assert(Bits % 64 == 0 &&
6883          "The number of bits in a vector must be divisible by 64 on x86!");
6884   int NumExtElements = Bits / 64;
6885
6886   // Each iteration, try extending the elements half as much, but into twice as
6887   // many elements.
6888   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6889     assert(NumElements % NumExtElements == 0 &&
6890            "The input vector size must be divisible by the extended size.");
6891     if (SDValue V = Lower(NumElements / NumExtElements))
6892       return V;
6893   }
6894
6895   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6896   if (Bits != 128)
6897     return SDValue();
6898
6899   // Returns one of the source operands if the shuffle can be reduced to a
6900   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6901   auto CanZExtLowHalf = [&]() {
6902     for (int i = NumElements / 2; i != NumElements; ++i)
6903       if (!Zeroable[i])
6904         return SDValue();
6905     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6906       return V1;
6907     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6908       return V2;
6909     return SDValue();
6910   };
6911
6912   if (SDValue V = CanZExtLowHalf()) {
6913     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6914     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6915     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6916   }
6917
6918   // No viable ext lowering found.
6919   return SDValue();
6920 }
6921
6922 /// \brief Try to get a scalar value for a specific element of a vector.
6923 ///
6924 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6925 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6926                                               SelectionDAG &DAG) {
6927   MVT VT = V.getSimpleValueType();
6928   MVT EltVT = VT.getVectorElementType();
6929   while (V.getOpcode() == ISD::BITCAST)
6930     V = V.getOperand(0);
6931   // If the bitcasts shift the element size, we can't extract an equivalent
6932   // element from it.
6933   MVT NewVT = V.getSimpleValueType();
6934   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6935     return SDValue();
6936
6937   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6938       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
6939     // Ensure the scalar operand is the same size as the destination.
6940     // FIXME: Add support for scalar truncation where possible.
6941     SDValue S = V.getOperand(Idx);
6942     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
6943       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
6944   }
6945
6946   return SDValue();
6947 }
6948
6949 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6950 ///
6951 /// This is particularly important because the set of instructions varies
6952 /// significantly based on whether the operand is a load or not.
6953 static bool isShuffleFoldableLoad(SDValue V) {
6954   while (V.getOpcode() == ISD::BITCAST)
6955     V = V.getOperand(0);
6956
6957   return ISD::isNON_EXTLoad(V.getNode());
6958 }
6959
6960 /// \brief Try to lower insertion of a single element into a zero vector.
6961 ///
6962 /// This is a common pattern that we have especially efficient patterns to lower
6963 /// across all subtarget feature sets.
6964 static SDValue lowerVectorShuffleAsElementInsertion(
6965     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6966     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6967   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6968   MVT ExtVT = VT;
6969   MVT EltVT = VT.getVectorElementType();
6970
6971   int V2Index = std::find_if(Mask.begin(), Mask.end(),
6972                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
6973                 Mask.begin();
6974   bool IsV1Zeroable = true;
6975   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6976     if (i != V2Index && !Zeroable[i]) {
6977       IsV1Zeroable = false;
6978       break;
6979     }
6980
6981   // Check for a single input from a SCALAR_TO_VECTOR node.
6982   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
6983   // all the smarts here sunk into that routine. However, the current
6984   // lowering of BUILD_VECTOR makes that nearly impossible until the old
6985   // vector shuffle lowering is dead.
6986   if (SDValue V2S = getScalarValueForVectorElement(
6987           V2, Mask[V2Index] - Mask.size(), DAG)) {
6988     // We need to zext the scalar if it is smaller than an i32.
6989     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
6990     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
6991       // Using zext to expand a narrow element won't work for non-zero
6992       // insertions.
6993       if (!IsV1Zeroable)
6994         return SDValue();
6995
6996       // Zero-extend directly to i32.
6997       ExtVT = MVT::v4i32;
6998       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
6999     }
7000     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7001   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7002              EltVT == MVT::i16) {
7003     // Either not inserting from the low element of the input or the input
7004     // element size is too small to use VZEXT_MOVL to clear the high bits.
7005     return SDValue();
7006   }
7007
7008   if (!IsV1Zeroable) {
7009     // If V1 can't be treated as a zero vector we have fewer options to lower
7010     // this. We can't support integer vectors or non-zero targets cheaply, and
7011     // the V1 elements can't be permuted in any way.
7012     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7013     if (!VT.isFloatingPoint() || V2Index != 0)
7014       return SDValue();
7015     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7016     V1Mask[V2Index] = -1;
7017     if (!isNoopShuffleMask(V1Mask))
7018       return SDValue();
7019     // This is essentially a special case blend operation, but if we have
7020     // general purpose blend operations, they are always faster. Bail and let
7021     // the rest of the lowering handle these as blends.
7022     if (Subtarget->hasSSE41())
7023       return SDValue();
7024
7025     // Otherwise, use MOVSD or MOVSS.
7026     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7027            "Only two types of floating point element types to handle!");
7028     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7029                        ExtVT, V1, V2);
7030   }
7031
7032   // This lowering only works for the low element with floating point vectors.
7033   if (VT.isFloatingPoint() && V2Index != 0)
7034     return SDValue();
7035
7036   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7037   if (ExtVT != VT)
7038     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7039
7040   if (V2Index != 0) {
7041     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7042     // the desired position. Otherwise it is more efficient to do a vector
7043     // shift left. We know that we can do a vector shift left because all
7044     // the inputs are zero.
7045     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7046       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7047       V2Shuffle[V2Index] = 0;
7048       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7049     } else {
7050       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7051       V2 = DAG.getNode(
7052           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7053           DAG.getConstant(
7054               V2Index * EltVT.getSizeInBits()/8,
7055               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7056       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7057     }
7058   }
7059   return V2;
7060 }
7061
7062 /// \brief Try to lower broadcast of a single element.
7063 ///
7064 /// For convenience, this code also bundles all of the subtarget feature set
7065 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7066 /// a convenient way to factor it out.
7067 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7068                                              ArrayRef<int> Mask,
7069                                              const X86Subtarget *Subtarget,
7070                                              SelectionDAG &DAG) {
7071   if (!Subtarget->hasAVX())
7072     return SDValue();
7073   if (VT.isInteger() && !Subtarget->hasAVX2())
7074     return SDValue();
7075
7076   // Check that the mask is a broadcast.
7077   int BroadcastIdx = -1;
7078   for (int M : Mask)
7079     if (M >= 0 && BroadcastIdx == -1)
7080       BroadcastIdx = M;
7081     else if (M >= 0 && M != BroadcastIdx)
7082       return SDValue();
7083
7084   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7085                                             "a sorted mask where the broadcast "
7086                                             "comes from V1.");
7087
7088   // Go up the chain of (vector) values to find a scalar load that we can
7089   // combine with the broadcast.
7090   for (;;) {
7091     switch (V.getOpcode()) {
7092     case ISD::CONCAT_VECTORS: {
7093       int OperandSize = Mask.size() / V.getNumOperands();
7094       V = V.getOperand(BroadcastIdx / OperandSize);
7095       BroadcastIdx %= OperandSize;
7096       continue;
7097     }
7098
7099     case ISD::INSERT_SUBVECTOR: {
7100       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7101       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7102       if (!ConstantIdx)
7103         break;
7104
7105       int BeginIdx = (int)ConstantIdx->getZExtValue();
7106       int EndIdx =
7107           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7108       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7109         BroadcastIdx -= BeginIdx;
7110         V = VInner;
7111       } else {
7112         V = VOuter;
7113       }
7114       continue;
7115     }
7116     }
7117     break;
7118   }
7119
7120   // Check if this is a broadcast of a scalar. We special case lowering
7121   // for scalars so that we can more effectively fold with loads.
7122   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7123       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7124     V = V.getOperand(BroadcastIdx);
7125
7126     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7127     // Only AVX2 has register broadcasts.
7128     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7129       return SDValue();
7130   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7131     // We can't broadcast from a vector register without AVX2, and we can only
7132     // broadcast from the zero-element of a vector register.
7133     return SDValue();
7134   }
7135
7136   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7137 }
7138
7139 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7140 // INSERTPS when the V1 elements are already in the correct locations
7141 // because otherwise we can just always use two SHUFPS instructions which
7142 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7143 // perform INSERTPS if a single V1 element is out of place and all V2
7144 // elements are zeroable.
7145 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7146                                             ArrayRef<int> Mask,
7147                                             SelectionDAG &DAG) {
7148   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7149   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7150   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7151   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7152
7153   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7154
7155   unsigned ZMask = 0;
7156   int V1DstIndex = -1;
7157   int V2DstIndex = -1;
7158   bool V1UsedInPlace = false;
7159
7160   for (int i = 0; i < 4; ++i) {
7161     // Synthesize a zero mask from the zeroable elements (includes undefs).
7162     if (Zeroable[i]) {
7163       ZMask |= 1 << i;
7164       continue;
7165     }
7166
7167     // Flag if we use any V1 inputs in place.
7168     if (i == Mask[i]) {
7169       V1UsedInPlace = true;
7170       continue;
7171     }
7172
7173     // We can only insert a single non-zeroable element.
7174     if (V1DstIndex != -1 || V2DstIndex != -1)
7175       return SDValue();
7176
7177     if (Mask[i] < 4) {
7178       // V1 input out of place for insertion.
7179       V1DstIndex = i;
7180     } else {
7181       // V2 input for insertion.
7182       V2DstIndex = i;
7183     }
7184   }
7185
7186   // Don't bother if we have no (non-zeroable) element for insertion.
7187   if (V1DstIndex == -1 && V2DstIndex == -1)
7188     return SDValue();
7189
7190   // Determine element insertion src/dst indices. The src index is from the
7191   // start of the inserted vector, not the start of the concatenated vector.
7192   unsigned V2SrcIndex = 0;
7193   if (V1DstIndex != -1) {
7194     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7195     // and don't use the original V2 at all.
7196     V2SrcIndex = Mask[V1DstIndex];
7197     V2DstIndex = V1DstIndex;
7198     V2 = V1;
7199   } else {
7200     V2SrcIndex = Mask[V2DstIndex] - 4;
7201   }
7202
7203   // If no V1 inputs are used in place, then the result is created only from
7204   // the zero mask and the V2 insertion - so remove V1 dependency.
7205   if (!V1UsedInPlace)
7206     V1 = DAG.getUNDEF(MVT::v4f32);
7207
7208   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7209   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7210
7211   // Insert the V2 element into the desired position.
7212   SDLoc DL(Op);
7213   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7214                      DAG.getConstant(InsertPSMask, MVT::i8));
7215 }
7216
7217 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7218 /// UNPCK instruction.
7219 ///
7220 /// This specifically targets cases where we end up with alternating between
7221 /// the two inputs, and so can permute them into something that feeds a single
7222 /// UNPCK instruction. Note that this routine only targets integer vectors
7223 /// because for floating point vectors we have a generalized SHUFPS lowering
7224 /// strategy that handles everything that doesn't *exactly* match an unpack,
7225 /// making this clever lowering unnecessary.
7226 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7227                                           SDValue V2, ArrayRef<int> Mask,
7228                                           SelectionDAG &DAG) {
7229   assert(!VT.isFloatingPoint() &&
7230          "This routine only supports integer vectors.");
7231   assert(!isSingleInputShuffleMask(Mask) &&
7232          "This routine should only be used when blending two inputs.");
7233   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7234
7235   int Size = Mask.size();
7236
7237   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7238     return M >= 0 && M % Size < Size / 2;
7239   });
7240   int NumHiInputs = std::count_if(
7241       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7242
7243   bool UnpackLo = NumLoInputs >= NumHiInputs;
7244
7245   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7246     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7247     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7248
7249     for (int i = 0; i < Size; ++i) {
7250       if (Mask[i] < 0)
7251         continue;
7252
7253       // Each element of the unpack contains Scale elements from this mask.
7254       int UnpackIdx = i / Scale;
7255
7256       // We only handle the case where V1 feeds the first slots of the unpack.
7257       // We rely on canonicalization to ensure this is the case.
7258       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7259         return SDValue();
7260
7261       // Setup the mask for this input. The indexing is tricky as we have to
7262       // handle the unpack stride.
7263       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7264       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7265           Mask[i] % Size;
7266     }
7267
7268     // If we will have to shuffle both inputs to use the unpack, check whether
7269     // we can just unpack first and shuffle the result. If so, skip this unpack.
7270     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7271         !isNoopShuffleMask(V2Mask))
7272       return SDValue();
7273
7274     // Shuffle the inputs into place.
7275     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7276     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7277
7278     // Cast the inputs to the type we will use to unpack them.
7279     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7280     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7281
7282     // Unpack the inputs and cast the result back to the desired type.
7283     return DAG.getNode(ISD::BITCAST, DL, VT,
7284                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7285                                    DL, UnpackVT, V1, V2));
7286   };
7287
7288   // We try each unpack from the largest to the smallest to try and find one
7289   // that fits this mask.
7290   int OrigNumElements = VT.getVectorNumElements();
7291   int OrigScalarSize = VT.getScalarSizeInBits();
7292   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7293     int Scale = ScalarSize / OrigScalarSize;
7294     int NumElements = OrigNumElements / Scale;
7295     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7296     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7297       return Unpack;
7298   }
7299
7300   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7301   // initial unpack.
7302   if (NumLoInputs == 0 || NumHiInputs == 0) {
7303     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7304            "We have to have *some* inputs!");
7305     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7306
7307     // FIXME: We could consider the total complexity of the permute of each
7308     // possible unpacking. Or at the least we should consider how many
7309     // half-crossings are created.
7310     // FIXME: We could consider commuting the unpacks.
7311
7312     SmallVector<int, 32> PermMask;
7313     PermMask.assign(Size, -1);
7314     for (int i = 0; i < Size; ++i) {
7315       if (Mask[i] < 0)
7316         continue;
7317
7318       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7319
7320       PermMask[i] =
7321           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7322     }
7323     return DAG.getVectorShuffle(
7324         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7325                             DL, VT, V1, V2),
7326         DAG.getUNDEF(VT), PermMask);
7327   }
7328
7329   return SDValue();
7330 }
7331
7332 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7333 ///
7334 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7335 /// support for floating point shuffles but not integer shuffles. These
7336 /// instructions will incur a domain crossing penalty on some chips though so
7337 /// it is better to avoid lowering through this for integer vectors where
7338 /// possible.
7339 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7340                                        const X86Subtarget *Subtarget,
7341                                        SelectionDAG &DAG) {
7342   SDLoc DL(Op);
7343   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7344   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7345   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7346   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7347   ArrayRef<int> Mask = SVOp->getMask();
7348   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7349
7350   if (isSingleInputShuffleMask(Mask)) {
7351     // Use low duplicate instructions for masks that match their pattern.
7352     if (Subtarget->hasSSE3())
7353       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7354         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7355
7356     // Straight shuffle of a single input vector. Simulate this by using the
7357     // single input as both of the "inputs" to this instruction..
7358     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7359
7360     if (Subtarget->hasAVX()) {
7361       // If we have AVX, we can use VPERMILPS which will allow folding a load
7362       // into the shuffle.
7363       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7364                          DAG.getConstant(SHUFPDMask, MVT::i8));
7365     }
7366
7367     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7368                        DAG.getConstant(SHUFPDMask, MVT::i8));
7369   }
7370   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7371   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7372
7373   // If we have a single input, insert that into V1 if we can do so cheaply.
7374   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7375     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7376             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7377       return Insertion;
7378     // Try inverting the insertion since for v2 masks it is easy to do and we
7379     // can't reliably sort the mask one way or the other.
7380     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7381                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7382     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7383             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7384       return Insertion;
7385   }
7386
7387   // Try to use one of the special instruction patterns to handle two common
7388   // blend patterns if a zero-blend above didn't work.
7389   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7390       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7391     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7392       // We can either use a special instruction to load over the low double or
7393       // to move just the low double.
7394       return DAG.getNode(
7395           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7396           DL, MVT::v2f64, V2,
7397           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7398
7399   if (Subtarget->hasSSE41())
7400     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7401                                                   Subtarget, DAG))
7402       return Blend;
7403
7404   // Use dedicated unpack instructions for masks that match their pattern.
7405   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7406     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7407   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7408     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7409
7410   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7411   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7412                      DAG.getConstant(SHUFPDMask, MVT::i8));
7413 }
7414
7415 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7416 ///
7417 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7418 /// the integer unit to minimize domain crossing penalties. However, for blends
7419 /// it falls back to the floating point shuffle operation with appropriate bit
7420 /// casting.
7421 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7422                                        const X86Subtarget *Subtarget,
7423                                        SelectionDAG &DAG) {
7424   SDLoc DL(Op);
7425   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7426   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7427   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7428   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7429   ArrayRef<int> Mask = SVOp->getMask();
7430   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7431
7432   if (isSingleInputShuffleMask(Mask)) {
7433     // Check for being able to broadcast a single element.
7434     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7435                                                           Mask, Subtarget, DAG))
7436       return Broadcast;
7437
7438     // Straight shuffle of a single input vector. For everything from SSE2
7439     // onward this has a single fast instruction with no scary immediates.
7440     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7441     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7442     int WidenedMask[4] = {
7443         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7444         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7445     return DAG.getNode(
7446         ISD::BITCAST, DL, MVT::v2i64,
7447         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7448                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7449   }
7450   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7451   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7452   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7453   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7454
7455   // If we have a blend of two PACKUS operations an the blend aligns with the
7456   // low and half halves, we can just merge the PACKUS operations. This is
7457   // particularly important as it lets us merge shuffles that this routine itself
7458   // creates.
7459   auto GetPackNode = [](SDValue V) {
7460     while (V.getOpcode() == ISD::BITCAST)
7461       V = V.getOperand(0);
7462
7463     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7464   };
7465   if (SDValue V1Pack = GetPackNode(V1))
7466     if (SDValue V2Pack = GetPackNode(V2))
7467       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7468                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7469                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7470                                                   : V1Pack.getOperand(1),
7471                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7472                                                   : V2Pack.getOperand(1)));
7473
7474   // Try to use shift instructions.
7475   if (SDValue Shift =
7476           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7477     return Shift;
7478
7479   // When loading a scalar and then shuffling it into a vector we can often do
7480   // the insertion cheaply.
7481   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7482           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7483     return Insertion;
7484   // Try inverting the insertion since for v2 masks it is easy to do and we
7485   // can't reliably sort the mask one way or the other.
7486   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7487   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7488           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7489     return Insertion;
7490
7491   // We have different paths for blend lowering, but they all must use the
7492   // *exact* same predicate.
7493   bool IsBlendSupported = Subtarget->hasSSE41();
7494   if (IsBlendSupported)
7495     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7496                                                   Subtarget, DAG))
7497       return Blend;
7498
7499   // Use dedicated unpack instructions for masks that match their pattern.
7500   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7501     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7502   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7503     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7504
7505   // Try to use byte rotation instructions.
7506   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7507   if (Subtarget->hasSSSE3())
7508     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7509             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7510       return Rotate;
7511
7512   // If we have direct support for blends, we should lower by decomposing into
7513   // a permute. That will be faster than the domain cross.
7514   if (IsBlendSupported)
7515     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7516                                                       Mask, DAG);
7517
7518   // We implement this with SHUFPD which is pretty lame because it will likely
7519   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7520   // However, all the alternatives are still more cycles and newer chips don't
7521   // have this problem. It would be really nice if x86 had better shuffles here.
7522   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7523   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7524   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7525                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7526 }
7527
7528 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7529 ///
7530 /// This is used to disable more specialized lowerings when the shufps lowering
7531 /// will happen to be efficient.
7532 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7533   // This routine only handles 128-bit shufps.
7534   assert(Mask.size() == 4 && "Unsupported mask size!");
7535
7536   // To lower with a single SHUFPS we need to have the low half and high half
7537   // each requiring a single input.
7538   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7539     return false;
7540   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7541     return false;
7542
7543   return true;
7544 }
7545
7546 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7547 ///
7548 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7549 /// It makes no assumptions about whether this is the *best* lowering, it simply
7550 /// uses it.
7551 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7552                                             ArrayRef<int> Mask, SDValue V1,
7553                                             SDValue V2, SelectionDAG &DAG) {
7554   SDValue LowV = V1, HighV = V2;
7555   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7556
7557   int NumV2Elements =
7558       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7559
7560   if (NumV2Elements == 1) {
7561     int V2Index =
7562         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7563         Mask.begin();
7564
7565     // Compute the index adjacent to V2Index and in the same half by toggling
7566     // the low bit.
7567     int V2AdjIndex = V2Index ^ 1;
7568
7569     if (Mask[V2AdjIndex] == -1) {
7570       // Handles all the cases where we have a single V2 element and an undef.
7571       // This will only ever happen in the high lanes because we commute the
7572       // vector otherwise.
7573       if (V2Index < 2)
7574         std::swap(LowV, HighV);
7575       NewMask[V2Index] -= 4;
7576     } else {
7577       // Handle the case where the V2 element ends up adjacent to a V1 element.
7578       // To make this work, blend them together as the first step.
7579       int V1Index = V2AdjIndex;
7580       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7581       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7582                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7583
7584       // Now proceed to reconstruct the final blend as we have the necessary
7585       // high or low half formed.
7586       if (V2Index < 2) {
7587         LowV = V2;
7588         HighV = V1;
7589       } else {
7590         HighV = V2;
7591       }
7592       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7593       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7594     }
7595   } else if (NumV2Elements == 2) {
7596     if (Mask[0] < 4 && Mask[1] < 4) {
7597       // Handle the easy case where we have V1 in the low lanes and V2 in the
7598       // high lanes.
7599       NewMask[2] -= 4;
7600       NewMask[3] -= 4;
7601     } else if (Mask[2] < 4 && Mask[3] < 4) {
7602       // We also handle the reversed case because this utility may get called
7603       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7604       // arrange things in the right direction.
7605       NewMask[0] -= 4;
7606       NewMask[1] -= 4;
7607       HighV = V1;
7608       LowV = V2;
7609     } else {
7610       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7611       // trying to place elements directly, just blend them and set up the final
7612       // shuffle to place them.
7613
7614       // The first two blend mask elements are for V1, the second two are for
7615       // V2.
7616       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7617                           Mask[2] < 4 ? Mask[2] : Mask[3],
7618                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7619                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7620       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7621                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7622
7623       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7624       // a blend.
7625       LowV = HighV = V1;
7626       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7627       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7628       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7629       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7630     }
7631   }
7632   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7633                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7634 }
7635
7636 /// \brief Lower 4-lane 32-bit floating point shuffles.
7637 ///
7638 /// Uses instructions exclusively from the floating point unit to minimize
7639 /// domain crossing penalties, as these are sufficient to implement all v4f32
7640 /// shuffles.
7641 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7642                                        const X86Subtarget *Subtarget,
7643                                        SelectionDAG &DAG) {
7644   SDLoc DL(Op);
7645   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7646   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7647   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7648   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7649   ArrayRef<int> Mask = SVOp->getMask();
7650   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7651
7652   int NumV2Elements =
7653       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7654
7655   if (NumV2Elements == 0) {
7656     // Check for being able to broadcast a single element.
7657     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7658                                                           Mask, Subtarget, DAG))
7659       return Broadcast;
7660
7661     // Use even/odd duplicate instructions for masks that match their pattern.
7662     if (Subtarget->hasSSE3()) {
7663       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7664         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7665       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7666         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7667     }
7668
7669     if (Subtarget->hasAVX()) {
7670       // If we have AVX, we can use VPERMILPS which will allow folding a load
7671       // into the shuffle.
7672       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7673                          getV4X86ShuffleImm8ForMask(Mask, DAG));
7674     }
7675
7676     // Otherwise, use a straight shuffle of a single input vector. We pass the
7677     // input vector to both operands to simulate this with a SHUFPS.
7678     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7679                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7680   }
7681
7682   // There are special ways we can lower some single-element blends. However, we
7683   // have custom ways we can lower more complex single-element blends below that
7684   // we defer to if both this and BLENDPS fail to match, so restrict this to
7685   // when the V2 input is targeting element 0 of the mask -- that is the fast
7686   // case here.
7687   if (NumV2Elements == 1 && Mask[0] >= 4)
7688     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7689                                                          Mask, Subtarget, DAG))
7690       return V;
7691
7692   if (Subtarget->hasSSE41()) {
7693     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7694                                                   Subtarget, DAG))
7695       return Blend;
7696
7697     // Use INSERTPS if we can complete the shuffle efficiently.
7698     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7699       return V;
7700
7701     if (!isSingleSHUFPSMask(Mask))
7702       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7703               DL, MVT::v4f32, V1, V2, Mask, DAG))
7704         return BlendPerm;
7705   }
7706
7707   // Use dedicated unpack instructions for masks that match their pattern.
7708   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7709     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7710   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7711     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7712   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7713     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7714   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7715     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7716
7717   // Otherwise fall back to a SHUFPS lowering strategy.
7718   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7719 }
7720
7721 /// \brief Lower 4-lane i32 vector shuffles.
7722 ///
7723 /// We try to handle these with integer-domain shuffles where we can, but for
7724 /// blends we use the floating point domain blend instructions.
7725 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7726                                        const X86Subtarget *Subtarget,
7727                                        SelectionDAG &DAG) {
7728   SDLoc DL(Op);
7729   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7730   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7731   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7732   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7733   ArrayRef<int> Mask = SVOp->getMask();
7734   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7735
7736   // Whenever we can lower this as a zext, that instruction is strictly faster
7737   // than any alternative. It also allows us to fold memory operands into the
7738   // shuffle in many cases.
7739   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7740                                                          Mask, Subtarget, DAG))
7741     return ZExt;
7742
7743   int NumV2Elements =
7744       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7745
7746   if (NumV2Elements == 0) {
7747     // Check for being able to broadcast a single element.
7748     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7749                                                           Mask, Subtarget, DAG))
7750       return Broadcast;
7751
7752     // Straight shuffle of a single input vector. For everything from SSE2
7753     // onward this has a single fast instruction with no scary immediates.
7754     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7755     // but we aren't actually going to use the UNPCK instruction because doing
7756     // so prevents folding a load into this instruction or making a copy.
7757     const int UnpackLoMask[] = {0, 0, 1, 1};
7758     const int UnpackHiMask[] = {2, 2, 3, 3};
7759     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7760       Mask = UnpackLoMask;
7761     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7762       Mask = UnpackHiMask;
7763
7764     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7765                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7766   }
7767
7768   // Try to use shift instructions.
7769   if (SDValue Shift =
7770           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7771     return Shift;
7772
7773   // There are special ways we can lower some single-element blends.
7774   if (NumV2Elements == 1)
7775     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7776                                                          Mask, Subtarget, DAG))
7777       return V;
7778
7779   // We have different paths for blend lowering, but they all must use the
7780   // *exact* same predicate.
7781   bool IsBlendSupported = Subtarget->hasSSE41();
7782   if (IsBlendSupported)
7783     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7784                                                   Subtarget, DAG))
7785       return Blend;
7786
7787   if (SDValue Masked =
7788           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7789     return Masked;
7790
7791   // Use dedicated unpack instructions for masks that match their pattern.
7792   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7793     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7794   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7795     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7796   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7797     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7798   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7799     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7800
7801   // Try to use byte rotation instructions.
7802   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7803   if (Subtarget->hasSSSE3())
7804     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7805             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7806       return Rotate;
7807
7808   // If we have direct support for blends, we should lower by decomposing into
7809   // a permute. That will be faster than the domain cross.
7810   if (IsBlendSupported)
7811     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7812                                                       Mask, DAG);
7813
7814   // Try to lower by permuting the inputs into an unpack instruction.
7815   if (SDValue Unpack =
7816           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7817     return Unpack;
7818
7819   // We implement this with SHUFPS because it can blend from two vectors.
7820   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7821   // up the inputs, bypassing domain shift penalties that we would encur if we
7822   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7823   // relevant.
7824   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7825                      DAG.getVectorShuffle(
7826                          MVT::v4f32, DL,
7827                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7828                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7829 }
7830
7831 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7832 /// shuffle lowering, and the most complex part.
7833 ///
7834 /// The lowering strategy is to try to form pairs of input lanes which are
7835 /// targeted at the same half of the final vector, and then use a dword shuffle
7836 /// to place them onto the right half, and finally unpack the paired lanes into
7837 /// their final position.
7838 ///
7839 /// The exact breakdown of how to form these dword pairs and align them on the
7840 /// correct sides is really tricky. See the comments within the function for
7841 /// more of the details.
7842 ///
7843 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7844 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7845 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7846 /// vector, form the analogous 128-bit 8-element Mask.
7847 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7848     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7849     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7850   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7851   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7852
7853   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7854   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7855   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7856
7857   SmallVector<int, 4> LoInputs;
7858   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7859                [](int M) { return M >= 0; });
7860   std::sort(LoInputs.begin(), LoInputs.end());
7861   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7862   SmallVector<int, 4> HiInputs;
7863   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7864                [](int M) { return M >= 0; });
7865   std::sort(HiInputs.begin(), HiInputs.end());
7866   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7867   int NumLToL =
7868       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7869   int NumHToL = LoInputs.size() - NumLToL;
7870   int NumLToH =
7871       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7872   int NumHToH = HiInputs.size() - NumLToH;
7873   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7874   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7875   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7876   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7877
7878   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7879   // such inputs we can swap two of the dwords across the half mark and end up
7880   // with <=2 inputs to each half in each half. Once there, we can fall through
7881   // to the generic code below. For example:
7882   //
7883   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7884   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7885   //
7886   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7887   // and an existing 2-into-2 on the other half. In this case we may have to
7888   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7889   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7890   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7891   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7892   // half than the one we target for fixing) will be fixed when we re-enter this
7893   // path. We will also combine away any sequence of PSHUFD instructions that
7894   // result into a single instruction. Here is an example of the tricky case:
7895   //
7896   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7897   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7898   //
7899   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7900   //
7901   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7902   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7903   //
7904   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7905   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7906   //
7907   // The result is fine to be handled by the generic logic.
7908   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7909                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7910                           int AOffset, int BOffset) {
7911     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7912            "Must call this with A having 3 or 1 inputs from the A half.");
7913     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7914            "Must call this with B having 1 or 3 inputs from the B half.");
7915     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7916            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7917
7918     // Compute the index of dword with only one word among the three inputs in
7919     // a half by taking the sum of the half with three inputs and subtracting
7920     // the sum of the actual three inputs. The difference is the remaining
7921     // slot.
7922     int ADWord, BDWord;
7923     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7924     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7925     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7926     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7927     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7928     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7929     int TripleNonInputIdx =
7930         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7931     TripleDWord = TripleNonInputIdx / 2;
7932
7933     // We use xor with one to compute the adjacent DWord to whichever one the
7934     // OneInput is in.
7935     OneInputDWord = (OneInput / 2) ^ 1;
7936
7937     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7938     // and BToA inputs. If there is also such a problem with the BToB and AToB
7939     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7940     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7941     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7942     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7943       // Compute how many inputs will be flipped by swapping these DWords. We
7944       // need
7945       // to balance this to ensure we don't form a 3-1 shuffle in the other
7946       // half.
7947       int NumFlippedAToBInputs =
7948           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7949           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7950       int NumFlippedBToBInputs =
7951           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7952           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7953       if ((NumFlippedAToBInputs == 1 &&
7954            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7955           (NumFlippedBToBInputs == 1 &&
7956            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7957         // We choose whether to fix the A half or B half based on whether that
7958         // half has zero flipped inputs. At zero, we may not be able to fix it
7959         // with that half. We also bias towards fixing the B half because that
7960         // will more commonly be the high half, and we have to bias one way.
7961         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7962                                                        ArrayRef<int> Inputs) {
7963           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7964           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7965                                          PinnedIdx ^ 1) != Inputs.end();
7966           // Determine whether the free index is in the flipped dword or the
7967           // unflipped dword based on where the pinned index is. We use this bit
7968           // in an xor to conditionally select the adjacent dword.
7969           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7970           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7971                                              FixFreeIdx) != Inputs.end();
7972           if (IsFixIdxInput == IsFixFreeIdxInput)
7973             FixFreeIdx += 1;
7974           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7975                                         FixFreeIdx) != Inputs.end();
7976           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7977                  "We need to be changing the number of flipped inputs!");
7978           int PSHUFHalfMask[] = {0, 1, 2, 3};
7979           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7980           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7981                           MVT::v8i16, V,
7982                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7983
7984           for (int &M : Mask)
7985             if (M != -1 && M == FixIdx)
7986               M = FixFreeIdx;
7987             else if (M != -1 && M == FixFreeIdx)
7988               M = FixIdx;
7989         };
7990         if (NumFlippedBToBInputs != 0) {
7991           int BPinnedIdx =
7992               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7993           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7994         } else {
7995           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7996           int APinnedIdx =
7997               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7998           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7999         }
8000       }
8001     }
8002
8003     int PSHUFDMask[] = {0, 1, 2, 3};
8004     PSHUFDMask[ADWord] = BDWord;
8005     PSHUFDMask[BDWord] = ADWord;
8006     V = DAG.getNode(ISD::BITCAST, DL, VT,
8007                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8008                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8009                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8010
8011     // Adjust the mask to match the new locations of A and B.
8012     for (int &M : Mask)
8013       if (M != -1 && M/2 == ADWord)
8014         M = 2 * BDWord + M % 2;
8015       else if (M != -1 && M/2 == BDWord)
8016         M = 2 * ADWord + M % 2;
8017
8018     // Recurse back into this routine to re-compute state now that this isn't
8019     // a 3 and 1 problem.
8020     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8021                                                      DAG);
8022   };
8023   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8024     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8025   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8026     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8027
8028   // At this point there are at most two inputs to the low and high halves from
8029   // each half. That means the inputs can always be grouped into dwords and
8030   // those dwords can then be moved to the correct half with a dword shuffle.
8031   // We use at most one low and one high word shuffle to collect these paired
8032   // inputs into dwords, and finally a dword shuffle to place them.
8033   int PSHUFLMask[4] = {-1, -1, -1, -1};
8034   int PSHUFHMask[4] = {-1, -1, -1, -1};
8035   int PSHUFDMask[4] = {-1, -1, -1, -1};
8036
8037   // First fix the masks for all the inputs that are staying in their
8038   // original halves. This will then dictate the targets of the cross-half
8039   // shuffles.
8040   auto fixInPlaceInputs =
8041       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8042                     MutableArrayRef<int> SourceHalfMask,
8043                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8044     if (InPlaceInputs.empty())
8045       return;
8046     if (InPlaceInputs.size() == 1) {
8047       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8048           InPlaceInputs[0] - HalfOffset;
8049       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8050       return;
8051     }
8052     if (IncomingInputs.empty()) {
8053       // Just fix all of the in place inputs.
8054       for (int Input : InPlaceInputs) {
8055         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8056         PSHUFDMask[Input / 2] = Input / 2;
8057       }
8058       return;
8059     }
8060
8061     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8062     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8063         InPlaceInputs[0] - HalfOffset;
8064     // Put the second input next to the first so that they are packed into
8065     // a dword. We find the adjacent index by toggling the low bit.
8066     int AdjIndex = InPlaceInputs[0] ^ 1;
8067     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8068     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8069     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8070   };
8071   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8072   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8073
8074   // Now gather the cross-half inputs and place them into a free dword of
8075   // their target half.
8076   // FIXME: This operation could almost certainly be simplified dramatically to
8077   // look more like the 3-1 fixing operation.
8078   auto moveInputsToRightHalf = [&PSHUFDMask](
8079       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8080       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8081       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8082       int DestOffset) {
8083     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8084       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8085     };
8086     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8087                                                int Word) {
8088       int LowWord = Word & ~1;
8089       int HighWord = Word | 1;
8090       return isWordClobbered(SourceHalfMask, LowWord) ||
8091              isWordClobbered(SourceHalfMask, HighWord);
8092     };
8093
8094     if (IncomingInputs.empty())
8095       return;
8096
8097     if (ExistingInputs.empty()) {
8098       // Map any dwords with inputs from them into the right half.
8099       for (int Input : IncomingInputs) {
8100         // If the source half mask maps over the inputs, turn those into
8101         // swaps and use the swapped lane.
8102         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8103           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8104             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8105                 Input - SourceOffset;
8106             // We have to swap the uses in our half mask in one sweep.
8107             for (int &M : HalfMask)
8108               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8109                 M = Input;
8110               else if (M == Input)
8111                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8112           } else {
8113             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8114                        Input - SourceOffset &&
8115                    "Previous placement doesn't match!");
8116           }
8117           // Note that this correctly re-maps both when we do a swap and when
8118           // we observe the other side of the swap above. We rely on that to
8119           // avoid swapping the members of the input list directly.
8120           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8121         }
8122
8123         // Map the input's dword into the correct half.
8124         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8125           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8126         else
8127           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8128                      Input / 2 &&
8129                  "Previous placement doesn't match!");
8130       }
8131
8132       // And just directly shift any other-half mask elements to be same-half
8133       // as we will have mirrored the dword containing the element into the
8134       // same position within that half.
8135       for (int &M : HalfMask)
8136         if (M >= SourceOffset && M < SourceOffset + 4) {
8137           M = M - SourceOffset + DestOffset;
8138           assert(M >= 0 && "This should never wrap below zero!");
8139         }
8140       return;
8141     }
8142
8143     // Ensure we have the input in a viable dword of its current half. This
8144     // is particularly tricky because the original position may be clobbered
8145     // by inputs being moved and *staying* in that half.
8146     if (IncomingInputs.size() == 1) {
8147       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8148         int InputFixed = std::find(std::begin(SourceHalfMask),
8149                                    std::end(SourceHalfMask), -1) -
8150                          std::begin(SourceHalfMask) + SourceOffset;
8151         SourceHalfMask[InputFixed - SourceOffset] =
8152             IncomingInputs[0] - SourceOffset;
8153         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8154                      InputFixed);
8155         IncomingInputs[0] = InputFixed;
8156       }
8157     } else if (IncomingInputs.size() == 2) {
8158       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8159           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8160         // We have two non-adjacent or clobbered inputs we need to extract from
8161         // the source half. To do this, we need to map them into some adjacent
8162         // dword slot in the source mask.
8163         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8164                               IncomingInputs[1] - SourceOffset};
8165
8166         // If there is a free slot in the source half mask adjacent to one of
8167         // the inputs, place the other input in it. We use (Index XOR 1) to
8168         // compute an adjacent index.
8169         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8170             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8171           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8172           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8173           InputsFixed[1] = InputsFixed[0] ^ 1;
8174         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8175                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8176           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8177           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8178           InputsFixed[0] = InputsFixed[1] ^ 1;
8179         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8180                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8181           // The two inputs are in the same DWord but it is clobbered and the
8182           // adjacent DWord isn't used at all. Move both inputs to the free
8183           // slot.
8184           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8185           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8186           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8187           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8188         } else {
8189           // The only way we hit this point is if there is no clobbering
8190           // (because there are no off-half inputs to this half) and there is no
8191           // free slot adjacent to one of the inputs. In this case, we have to
8192           // swap an input with a non-input.
8193           for (int i = 0; i < 4; ++i)
8194             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8195                    "We can't handle any clobbers here!");
8196           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8197                  "Cannot have adjacent inputs here!");
8198
8199           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8200           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8201
8202           // We also have to update the final source mask in this case because
8203           // it may need to undo the above swap.
8204           for (int &M : FinalSourceHalfMask)
8205             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8206               M = InputsFixed[1] + SourceOffset;
8207             else if (M == InputsFixed[1] + SourceOffset)
8208               M = (InputsFixed[0] ^ 1) + SourceOffset;
8209
8210           InputsFixed[1] = InputsFixed[0] ^ 1;
8211         }
8212
8213         // Point everything at the fixed inputs.
8214         for (int &M : HalfMask)
8215           if (M == IncomingInputs[0])
8216             M = InputsFixed[0] + SourceOffset;
8217           else if (M == IncomingInputs[1])
8218             M = InputsFixed[1] + SourceOffset;
8219
8220         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8221         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8222       }
8223     } else {
8224       llvm_unreachable("Unhandled input size!");
8225     }
8226
8227     // Now hoist the DWord down to the right half.
8228     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8229     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8230     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8231     for (int &M : HalfMask)
8232       for (int Input : IncomingInputs)
8233         if (M == Input)
8234           M = FreeDWord * 2 + Input % 2;
8235   };
8236   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8237                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8238   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8239                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8240
8241   // Now enact all the shuffles we've computed to move the inputs into their
8242   // target half.
8243   if (!isNoopShuffleMask(PSHUFLMask))
8244     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8245                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8246   if (!isNoopShuffleMask(PSHUFHMask))
8247     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8248                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8249   if (!isNoopShuffleMask(PSHUFDMask))
8250     V = DAG.getNode(ISD::BITCAST, DL, VT,
8251                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8252                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8253                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8254
8255   // At this point, each half should contain all its inputs, and we can then
8256   // just shuffle them into their final position.
8257   assert(std::count_if(LoMask.begin(), LoMask.end(),
8258                        [](int M) { return M >= 4; }) == 0 &&
8259          "Failed to lift all the high half inputs to the low mask!");
8260   assert(std::count_if(HiMask.begin(), HiMask.end(),
8261                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8262          "Failed to lift all the low half inputs to the high mask!");
8263
8264   // Do a half shuffle for the low mask.
8265   if (!isNoopShuffleMask(LoMask))
8266     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8267                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
8268
8269   // Do a half shuffle with the high mask after shifting its values down.
8270   for (int &M : HiMask)
8271     if (M >= 0)
8272       M -= 4;
8273   if (!isNoopShuffleMask(HiMask))
8274     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8275                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
8276
8277   return V;
8278 }
8279
8280 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8281 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8282                                           SDValue V2, ArrayRef<int> Mask,
8283                                           SelectionDAG &DAG, bool &V1InUse,
8284                                           bool &V2InUse) {
8285   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8286   SDValue V1Mask[16];
8287   SDValue V2Mask[16];
8288   V1InUse = false;
8289   V2InUse = false;
8290
8291   int Size = Mask.size();
8292   int Scale = 16 / Size;
8293   for (int i = 0; i < 16; ++i) {
8294     if (Mask[i / Scale] == -1) {
8295       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8296     } else {
8297       const int ZeroMask = 0x80;
8298       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8299                                           : ZeroMask;
8300       int V2Idx = Mask[i / Scale] < Size
8301                       ? ZeroMask
8302                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8303       if (Zeroable[i / Scale])
8304         V1Idx = V2Idx = ZeroMask;
8305       V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
8306       V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
8307       V1InUse |= (ZeroMask != V1Idx);
8308       V2InUse |= (ZeroMask != V2Idx);
8309     }
8310   }
8311
8312   if (V1InUse)
8313     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8314                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8315                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8316   if (V2InUse)
8317     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8318                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8319                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8320
8321   // If we need shuffled inputs from both, blend the two.
8322   SDValue V;
8323   if (V1InUse && V2InUse)
8324     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8325   else
8326     V = V1InUse ? V1 : V2;
8327
8328   // Cast the result back to the correct type.
8329   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8330 }
8331
8332 /// \brief Generic lowering of 8-lane i16 shuffles.
8333 ///
8334 /// This handles both single-input shuffles and combined shuffle/blends with
8335 /// two inputs. The single input shuffles are immediately delegated to
8336 /// a dedicated lowering routine.
8337 ///
8338 /// The blends are lowered in one of three fundamental ways. If there are few
8339 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8340 /// of the input is significantly cheaper when lowered as an interleaving of
8341 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8342 /// halves of the inputs separately (making them have relatively few inputs)
8343 /// and then concatenate them.
8344 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8345                                        const X86Subtarget *Subtarget,
8346                                        SelectionDAG &DAG) {
8347   SDLoc DL(Op);
8348   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8349   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8350   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8351   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8352   ArrayRef<int> OrigMask = SVOp->getMask();
8353   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8354                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8355   MutableArrayRef<int> Mask(MaskStorage);
8356
8357   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8358
8359   // Whenever we can lower this as a zext, that instruction is strictly faster
8360   // than any alternative.
8361   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8362           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8363     return ZExt;
8364
8365   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8366   (void)isV1;
8367   auto isV2 = [](int M) { return M >= 8; };
8368
8369   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8370
8371   if (NumV2Inputs == 0) {
8372     // Check for being able to broadcast a single element.
8373     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8374                                                           Mask, Subtarget, DAG))
8375       return Broadcast;
8376
8377     // Try to use shift instructions.
8378     if (SDValue Shift =
8379             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8380       return Shift;
8381
8382     // Use dedicated unpack instructions for masks that match their pattern.
8383     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8384       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8385     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8386       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8387
8388     // Try to use byte rotation instructions.
8389     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8390                                                         Mask, Subtarget, DAG))
8391       return Rotate;
8392
8393     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8394                                                      Subtarget, DAG);
8395   }
8396
8397   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8398          "All single-input shuffles should be canonicalized to be V1-input "
8399          "shuffles.");
8400
8401   // Try to use shift instructions.
8402   if (SDValue Shift =
8403           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8404     return Shift;
8405
8406   // There are special ways we can lower some single-element blends.
8407   if (NumV2Inputs == 1)
8408     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8409                                                          Mask, Subtarget, DAG))
8410       return V;
8411
8412   // We have different paths for blend lowering, but they all must use the
8413   // *exact* same predicate.
8414   bool IsBlendSupported = Subtarget->hasSSE41();
8415   if (IsBlendSupported)
8416     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8417                                                   Subtarget, DAG))
8418       return Blend;
8419
8420   if (SDValue Masked =
8421           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8422     return Masked;
8423
8424   // Use dedicated unpack instructions for masks that match their pattern.
8425   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8426     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8427   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8428     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8429
8430   // Try to use byte rotation instructions.
8431   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8432           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8433     return Rotate;
8434
8435   if (SDValue BitBlend =
8436           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8437     return BitBlend;
8438
8439   if (SDValue Unpack =
8440           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8441     return Unpack;
8442
8443   // If we can't directly blend but can use PSHUFB, that will be better as it
8444   // can both shuffle and set up the inefficient blend.
8445   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8446     bool V1InUse, V2InUse;
8447     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8448                                       V1InUse, V2InUse);
8449   }
8450
8451   // We can always bit-blend if we have to so the fallback strategy is to
8452   // decompose into single-input permutes and blends.
8453   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8454                                                       Mask, DAG);
8455 }
8456
8457 /// \brief Check whether a compaction lowering can be done by dropping even
8458 /// elements and compute how many times even elements must be dropped.
8459 ///
8460 /// This handles shuffles which take every Nth element where N is a power of
8461 /// two. Example shuffle masks:
8462 ///
8463 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8464 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8465 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8466 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8467 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8468 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8469 ///
8470 /// Any of these lanes can of course be undef.
8471 ///
8472 /// This routine only supports N <= 3.
8473 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8474 /// for larger N.
8475 ///
8476 /// \returns N above, or the number of times even elements must be dropped if
8477 /// there is such a number. Otherwise returns zero.
8478 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8479   // Figure out whether we're looping over two inputs or just one.
8480   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8481
8482   // The modulus for the shuffle vector entries is based on whether this is
8483   // a single input or not.
8484   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8485   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8486          "We should only be called with masks with a power-of-2 size!");
8487
8488   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8489
8490   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8491   // and 2^3 simultaneously. This is because we may have ambiguity with
8492   // partially undef inputs.
8493   bool ViableForN[3] = {true, true, true};
8494
8495   for (int i = 0, e = Mask.size(); i < e; ++i) {
8496     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8497     // want.
8498     if (Mask[i] == -1)
8499       continue;
8500
8501     bool IsAnyViable = false;
8502     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8503       if (ViableForN[j]) {
8504         uint64_t N = j + 1;
8505
8506         // The shuffle mask must be equal to (i * 2^N) % M.
8507         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8508           IsAnyViable = true;
8509         else
8510           ViableForN[j] = false;
8511       }
8512     // Early exit if we exhaust the possible powers of two.
8513     if (!IsAnyViable)
8514       break;
8515   }
8516
8517   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8518     if (ViableForN[j])
8519       return j + 1;
8520
8521   // Return 0 as there is no viable power of two.
8522   return 0;
8523 }
8524
8525 /// \brief Generic lowering of v16i8 shuffles.
8526 ///
8527 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8528 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8529 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8530 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8531 /// back together.
8532 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8533                                        const X86Subtarget *Subtarget,
8534                                        SelectionDAG &DAG) {
8535   SDLoc DL(Op);
8536   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8537   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8538   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8539   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8540   ArrayRef<int> Mask = SVOp->getMask();
8541   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8542
8543   // Try to use shift instructions.
8544   if (SDValue Shift =
8545           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8546     return Shift;
8547
8548   // Try to use byte rotation instructions.
8549   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8550           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8551     return Rotate;
8552
8553   // Try to use a zext lowering.
8554   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8555           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8556     return ZExt;
8557
8558   int NumV2Elements =
8559       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8560
8561   // For single-input shuffles, there are some nicer lowering tricks we can use.
8562   if (NumV2Elements == 0) {
8563     // Check for being able to broadcast a single element.
8564     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8565                                                           Mask, Subtarget, DAG))
8566       return Broadcast;
8567
8568     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8569     // Notably, this handles splat and partial-splat shuffles more efficiently.
8570     // However, it only makes sense if the pre-duplication shuffle simplifies
8571     // things significantly. Currently, this means we need to be able to
8572     // express the pre-duplication shuffle as an i16 shuffle.
8573     //
8574     // FIXME: We should check for other patterns which can be widened into an
8575     // i16 shuffle as well.
8576     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8577       for (int i = 0; i < 16; i += 2)
8578         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8579           return false;
8580
8581       return true;
8582     };
8583     auto tryToWidenViaDuplication = [&]() -> SDValue {
8584       if (!canWidenViaDuplication(Mask))
8585         return SDValue();
8586       SmallVector<int, 4> LoInputs;
8587       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8588                    [](int M) { return M >= 0 && M < 8; });
8589       std::sort(LoInputs.begin(), LoInputs.end());
8590       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8591                      LoInputs.end());
8592       SmallVector<int, 4> HiInputs;
8593       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8594                    [](int M) { return M >= 8; });
8595       std::sort(HiInputs.begin(), HiInputs.end());
8596       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8597                      HiInputs.end());
8598
8599       bool TargetLo = LoInputs.size() >= HiInputs.size();
8600       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8601       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8602
8603       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8604       SmallDenseMap<int, int, 8> LaneMap;
8605       for (int I : InPlaceInputs) {
8606         PreDupI16Shuffle[I/2] = I/2;
8607         LaneMap[I] = I;
8608       }
8609       int j = TargetLo ? 0 : 4, je = j + 4;
8610       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8611         // Check if j is already a shuffle of this input. This happens when
8612         // there are two adjacent bytes after we move the low one.
8613         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8614           // If we haven't yet mapped the input, search for a slot into which
8615           // we can map it.
8616           while (j < je && PreDupI16Shuffle[j] != -1)
8617             ++j;
8618
8619           if (j == je)
8620             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8621             return SDValue();
8622
8623           // Map this input with the i16 shuffle.
8624           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8625         }
8626
8627         // Update the lane map based on the mapping we ended up with.
8628         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8629       }
8630       V1 = DAG.getNode(
8631           ISD::BITCAST, DL, MVT::v16i8,
8632           DAG.getVectorShuffle(MVT::v8i16, DL,
8633                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8634                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8635
8636       // Unpack the bytes to form the i16s that will be shuffled into place.
8637       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8638                        MVT::v16i8, V1, V1);
8639
8640       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8641       for (int i = 0; i < 16; ++i)
8642         if (Mask[i] != -1) {
8643           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8644           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8645           if (PostDupI16Shuffle[i / 2] == -1)
8646             PostDupI16Shuffle[i / 2] = MappedMask;
8647           else
8648             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8649                    "Conflicting entrties in the original shuffle!");
8650         }
8651       return DAG.getNode(
8652           ISD::BITCAST, DL, MVT::v16i8,
8653           DAG.getVectorShuffle(MVT::v8i16, DL,
8654                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8655                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8656     };
8657     if (SDValue V = tryToWidenViaDuplication())
8658       return V;
8659   }
8660
8661   // Use dedicated unpack instructions for masks that match their pattern.
8662   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8663                                          0, 16, 1, 17, 2, 18, 3, 19,
8664                                          // High half.
8665                                          4, 20, 5, 21, 6, 22, 7, 23}))
8666     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8667   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8668                                          8, 24, 9, 25, 10, 26, 11, 27,
8669                                          // High half.
8670                                          12, 28, 13, 29, 14, 30, 15, 31}))
8671     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8672
8673   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8674   // with PSHUFB. It is important to do this before we attempt to generate any
8675   // blends but after all of the single-input lowerings. If the single input
8676   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8677   // want to preserve that and we can DAG combine any longer sequences into
8678   // a PSHUFB in the end. But once we start blending from multiple inputs,
8679   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8680   // and there are *very* few patterns that would actually be faster than the
8681   // PSHUFB approach because of its ability to zero lanes.
8682   //
8683   // FIXME: The only exceptions to the above are blends which are exact
8684   // interleavings with direct instructions supporting them. We currently don't
8685   // handle those well here.
8686   if (Subtarget->hasSSSE3()) {
8687     bool V1InUse = false;
8688     bool V2InUse = false;
8689
8690     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8691                                                 DAG, V1InUse, V2InUse);
8692
8693     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8694     // do so. This avoids using them to handle blends-with-zero which is
8695     // important as a single pshufb is significantly faster for that.
8696     if (V1InUse && V2InUse) {
8697       if (Subtarget->hasSSE41())
8698         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8699                                                       Mask, Subtarget, DAG))
8700           return Blend;
8701
8702       // We can use an unpack to do the blending rather than an or in some
8703       // cases. Even though the or may be (very minorly) more efficient, we
8704       // preference this lowering because there are common cases where part of
8705       // the complexity of the shuffles goes away when we do the final blend as
8706       // an unpack.
8707       // FIXME: It might be worth trying to detect if the unpack-feeding
8708       // shuffles will both be pshufb, in which case we shouldn't bother with
8709       // this.
8710       if (SDValue Unpack =
8711               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8712         return Unpack;
8713     }
8714
8715     return PSHUFB;
8716   }
8717
8718   // There are special ways we can lower some single-element blends.
8719   if (NumV2Elements == 1)
8720     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8721                                                          Mask, Subtarget, DAG))
8722       return V;
8723
8724   if (SDValue BitBlend =
8725           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8726     return BitBlend;
8727
8728   // Check whether a compaction lowering can be done. This handles shuffles
8729   // which take every Nth element for some even N. See the helper function for
8730   // details.
8731   //
8732   // We special case these as they can be particularly efficiently handled with
8733   // the PACKUSB instruction on x86 and they show up in common patterns of
8734   // rearranging bytes to truncate wide elements.
8735   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8736     // NumEvenDrops is the power of two stride of the elements. Another way of
8737     // thinking about it is that we need to drop the even elements this many
8738     // times to get the original input.
8739     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8740
8741     // First we need to zero all the dropped bytes.
8742     assert(NumEvenDrops <= 3 &&
8743            "No support for dropping even elements more than 3 times.");
8744     // We use the mask type to pick which bytes are preserved based on how many
8745     // elements are dropped.
8746     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8747     SDValue ByteClearMask =
8748         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8749                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8750     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8751     if (!IsSingleInput)
8752       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8753
8754     // Now pack things back together.
8755     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8756     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8757     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8758     for (int i = 1; i < NumEvenDrops; ++i) {
8759       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8760       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8761     }
8762
8763     return Result;
8764   }
8765
8766   // Handle multi-input cases by blending single-input shuffles.
8767   if (NumV2Elements > 0)
8768     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8769                                                       Mask, DAG);
8770
8771   // The fallback path for single-input shuffles widens this into two v8i16
8772   // vectors with unpacks, shuffles those, and then pulls them back together
8773   // with a pack.
8774   SDValue V = V1;
8775
8776   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8777   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8778   for (int i = 0; i < 16; ++i)
8779     if (Mask[i] >= 0)
8780       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8781
8782   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8783
8784   SDValue VLoHalf, VHiHalf;
8785   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8786   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8787   // i16s.
8788   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8789                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8790       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8791                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8792     // Use a mask to drop the high bytes.
8793     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8794     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8795                      DAG.getConstant(0x00FF, MVT::v8i16));
8796
8797     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8798     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8799
8800     // Squash the masks to point directly into VLoHalf.
8801     for (int &M : LoBlendMask)
8802       if (M >= 0)
8803         M /= 2;
8804     for (int &M : HiBlendMask)
8805       if (M >= 0)
8806         M /= 2;
8807   } else {
8808     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8809     // VHiHalf so that we can blend them as i16s.
8810     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8811                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8812     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8813                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8814   }
8815
8816   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8817   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8818
8819   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8820 }
8821
8822 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8823 ///
8824 /// This routine breaks down the specific type of 128-bit shuffle and
8825 /// dispatches to the lowering routines accordingly.
8826 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8827                                         MVT VT, const X86Subtarget *Subtarget,
8828                                         SelectionDAG &DAG) {
8829   switch (VT.SimpleTy) {
8830   case MVT::v2i64:
8831     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8832   case MVT::v2f64:
8833     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8834   case MVT::v4i32:
8835     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8836   case MVT::v4f32:
8837     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8838   case MVT::v8i16:
8839     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8840   case MVT::v16i8:
8841     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8842
8843   default:
8844     llvm_unreachable("Unimplemented!");
8845   }
8846 }
8847
8848 /// \brief Helper function to test whether a shuffle mask could be
8849 /// simplified by widening the elements being shuffled.
8850 ///
8851 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8852 /// leaves it in an unspecified state.
8853 ///
8854 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8855 /// shuffle masks. The latter have the special property of a '-2' representing
8856 /// a zero-ed lane of a vector.
8857 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8858                                     SmallVectorImpl<int> &WidenedMask) {
8859   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8860     // If both elements are undef, its trivial.
8861     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8862       WidenedMask.push_back(SM_SentinelUndef);
8863       continue;
8864     }
8865
8866     // Check for an undef mask and a mask value properly aligned to fit with
8867     // a pair of values. If we find such a case, use the non-undef mask's value.
8868     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8869       WidenedMask.push_back(Mask[i + 1] / 2);
8870       continue;
8871     }
8872     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8873       WidenedMask.push_back(Mask[i] / 2);
8874       continue;
8875     }
8876
8877     // When zeroing, we need to spread the zeroing across both lanes to widen.
8878     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8879       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8880           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8881         WidenedMask.push_back(SM_SentinelZero);
8882         continue;
8883       }
8884       return false;
8885     }
8886
8887     // Finally check if the two mask values are adjacent and aligned with
8888     // a pair.
8889     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8890       WidenedMask.push_back(Mask[i] / 2);
8891       continue;
8892     }
8893
8894     // Otherwise we can't safely widen the elements used in this shuffle.
8895     return false;
8896   }
8897   assert(WidenedMask.size() == Mask.size() / 2 &&
8898          "Incorrect size of mask after widening the elements!");
8899
8900   return true;
8901 }
8902
8903 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8904 ///
8905 /// This routine just extracts two subvectors, shuffles them independently, and
8906 /// then concatenates them back together. This should work effectively with all
8907 /// AVX vector shuffle types.
8908 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8909                                           SDValue V2, ArrayRef<int> Mask,
8910                                           SelectionDAG &DAG) {
8911   assert(VT.getSizeInBits() >= 256 &&
8912          "Only for 256-bit or wider vector shuffles!");
8913   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8914   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8915
8916   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8917   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8918
8919   int NumElements = VT.getVectorNumElements();
8920   int SplitNumElements = NumElements / 2;
8921   MVT ScalarVT = VT.getScalarType();
8922   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8923
8924   // Rather than splitting build-vectors, just build two narrower build
8925   // vectors. This helps shuffling with splats and zeros.
8926   auto SplitVector = [&](SDValue V) {
8927     while (V.getOpcode() == ISD::BITCAST)
8928       V = V->getOperand(0);
8929
8930     MVT OrigVT = V.getSimpleValueType();
8931     int OrigNumElements = OrigVT.getVectorNumElements();
8932     int OrigSplitNumElements = OrigNumElements / 2;
8933     MVT OrigScalarVT = OrigVT.getScalarType();
8934     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8935
8936     SDValue LoV, HiV;
8937
8938     auto *BV = dyn_cast<BuildVectorSDNode>(V);
8939     if (!BV) {
8940       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8941                         DAG.getIntPtrConstant(0));
8942       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8943                         DAG.getIntPtrConstant(OrigSplitNumElements));
8944     } else {
8945
8946       SmallVector<SDValue, 16> LoOps, HiOps;
8947       for (int i = 0; i < OrigSplitNumElements; ++i) {
8948         LoOps.push_back(BV->getOperand(i));
8949         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8950       }
8951       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8952       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8953     }
8954     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8955                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8956   };
8957
8958   SDValue LoV1, HiV1, LoV2, HiV2;
8959   std::tie(LoV1, HiV1) = SplitVector(V1);
8960   std::tie(LoV2, HiV2) = SplitVector(V2);
8961
8962   // Now create two 4-way blends of these half-width vectors.
8963   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8964     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
8965     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
8966     for (int i = 0; i < SplitNumElements; ++i) {
8967       int M = HalfMask[i];
8968       if (M >= NumElements) {
8969         if (M >= NumElements + SplitNumElements)
8970           UseHiV2 = true;
8971         else
8972           UseLoV2 = true;
8973         V2BlendMask.push_back(M - NumElements);
8974         V1BlendMask.push_back(-1);
8975         BlendMask.push_back(SplitNumElements + i);
8976       } else if (M >= 0) {
8977         if (M >= SplitNumElements)
8978           UseHiV1 = true;
8979         else
8980           UseLoV1 = true;
8981         V2BlendMask.push_back(-1);
8982         V1BlendMask.push_back(M);
8983         BlendMask.push_back(i);
8984       } else {
8985         V2BlendMask.push_back(-1);
8986         V1BlendMask.push_back(-1);
8987         BlendMask.push_back(-1);
8988       }
8989     }
8990
8991     // Because the lowering happens after all combining takes place, we need to
8992     // manually combine these blend masks as much as possible so that we create
8993     // a minimal number of high-level vector shuffle nodes.
8994
8995     // First try just blending the halves of V1 or V2.
8996     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
8997       return DAG.getUNDEF(SplitVT);
8998     if (!UseLoV2 && !UseHiV2)
8999       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9000     if (!UseLoV1 && !UseHiV1)
9001       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9002
9003     SDValue V1Blend, V2Blend;
9004     if (UseLoV1 && UseHiV1) {
9005       V1Blend =
9006         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9007     } else {
9008       // We only use half of V1 so map the usage down into the final blend mask.
9009       V1Blend = UseLoV1 ? LoV1 : HiV1;
9010       for (int i = 0; i < SplitNumElements; ++i)
9011         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9012           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9013     }
9014     if (UseLoV2 && UseHiV2) {
9015       V2Blend =
9016         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9017     } else {
9018       // We only use half of V2 so map the usage down into the final blend mask.
9019       V2Blend = UseLoV2 ? LoV2 : HiV2;
9020       for (int i = 0; i < SplitNumElements; ++i)
9021         if (BlendMask[i] >= SplitNumElements)
9022           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9023     }
9024     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9025   };
9026   SDValue Lo = HalfBlend(LoMask);
9027   SDValue Hi = HalfBlend(HiMask);
9028   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9029 }
9030
9031 /// \brief Either split a vector in halves or decompose the shuffles and the
9032 /// blend.
9033 ///
9034 /// This is provided as a good fallback for many lowerings of non-single-input
9035 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9036 /// between splitting the shuffle into 128-bit components and stitching those
9037 /// back together vs. extracting the single-input shuffles and blending those
9038 /// results.
9039 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9040                                                 SDValue V2, ArrayRef<int> Mask,
9041                                                 SelectionDAG &DAG) {
9042   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9043                                             "lower single-input shuffles as it "
9044                                             "could then recurse on itself.");
9045   int Size = Mask.size();
9046
9047   // If this can be modeled as a broadcast of two elements followed by a blend,
9048   // prefer that lowering. This is especially important because broadcasts can
9049   // often fold with memory operands.
9050   auto DoBothBroadcast = [&] {
9051     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9052     for (int M : Mask)
9053       if (M >= Size) {
9054         if (V2BroadcastIdx == -1)
9055           V2BroadcastIdx = M - Size;
9056         else if (M - Size != V2BroadcastIdx)
9057           return false;
9058       } else if (M >= 0) {
9059         if (V1BroadcastIdx == -1)
9060           V1BroadcastIdx = M;
9061         else if (M != V1BroadcastIdx)
9062           return false;
9063       }
9064     return true;
9065   };
9066   if (DoBothBroadcast())
9067     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9068                                                       DAG);
9069
9070   // If the inputs all stem from a single 128-bit lane of each input, then we
9071   // split them rather than blending because the split will decompose to
9072   // unusually few instructions.
9073   int LaneCount = VT.getSizeInBits() / 128;
9074   int LaneSize = Size / LaneCount;
9075   SmallBitVector LaneInputs[2];
9076   LaneInputs[0].resize(LaneCount, false);
9077   LaneInputs[1].resize(LaneCount, false);
9078   for (int i = 0; i < Size; ++i)
9079     if (Mask[i] >= 0)
9080       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9081   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9082     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9083
9084   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9085   // that the decomposed single-input shuffles don't end up here.
9086   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9087 }
9088
9089 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9090 /// a permutation and blend of those lanes.
9091 ///
9092 /// This essentially blends the out-of-lane inputs to each lane into the lane
9093 /// from a permuted copy of the vector. This lowering strategy results in four
9094 /// instructions in the worst case for a single-input cross lane shuffle which
9095 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9096 /// of. Special cases for each particular shuffle pattern should be handled
9097 /// prior to trying this lowering.
9098 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9099                                                        SDValue V1, SDValue V2,
9100                                                        ArrayRef<int> Mask,
9101                                                        SelectionDAG &DAG) {
9102   // FIXME: This should probably be generalized for 512-bit vectors as well.
9103   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9104   int LaneSize = Mask.size() / 2;
9105
9106   // If there are only inputs from one 128-bit lane, splitting will in fact be
9107   // less expensive. The flags track whether the given lane contains an element
9108   // that crosses to another lane.
9109   bool LaneCrossing[2] = {false, false};
9110   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9111     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9112       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9113   if (!LaneCrossing[0] || !LaneCrossing[1])
9114     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9115
9116   if (isSingleInputShuffleMask(Mask)) {
9117     SmallVector<int, 32> FlippedBlendMask;
9118     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9119       FlippedBlendMask.push_back(
9120           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9121                                   ? Mask[i]
9122                                   : Mask[i] % LaneSize +
9123                                         (i / LaneSize) * LaneSize + Size));
9124
9125     // Flip the vector, and blend the results which should now be in-lane. The
9126     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9127     // 5 for the high source. The value 3 selects the high half of source 2 and
9128     // the value 2 selects the low half of source 2. We only use source 2 to
9129     // allow folding it into a memory operand.
9130     unsigned PERMMask = 3 | 2 << 4;
9131     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9132                                   V1, DAG.getConstant(PERMMask, MVT::i8));
9133     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9134   }
9135
9136   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9137   // will be handled by the above logic and a blend of the results, much like
9138   // other patterns in AVX.
9139   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9140 }
9141
9142 /// \brief Handle lowering 2-lane 128-bit shuffles.
9143 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9144                                         SDValue V2, ArrayRef<int> Mask,
9145                                         const X86Subtarget *Subtarget,
9146                                         SelectionDAG &DAG) {
9147   // TODO: If minimizing size and one of the inputs is a zero vector and the
9148   // the zero vector has only one use, we could use a VPERM2X128 to save the
9149   // instruction bytes needed to explicitly generate the zero vector.
9150
9151   // Blends are faster and handle all the non-lane-crossing cases.
9152   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9153                                                 Subtarget, DAG))
9154     return Blend;
9155
9156   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9157   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9158
9159   // If either input operand is a zero vector, use VPERM2X128 because its mask
9160   // allows us to replace the zero input with an implicit zero.
9161   if (!IsV1Zero && !IsV2Zero) {
9162     // Check for patterns which can be matched with a single insert of a 128-bit
9163     // subvector.
9164     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9165     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9166       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9167                                    VT.getVectorNumElements() / 2);
9168       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9169                                 DAG.getIntPtrConstant(0));
9170       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9171                                 OnlyUsesV1 ? V1 : V2, DAG.getIntPtrConstant(0));
9172       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9173     }
9174   }
9175
9176   // Otherwise form a 128-bit permutation. After accounting for undefs,
9177   // convert the 64-bit shuffle mask selection values into 128-bit
9178   // selection bits by dividing the indexes by 2 and shifting into positions
9179   // defined by a vperm2*128 instruction's immediate control byte.
9180
9181   // The immediate permute control byte looks like this:
9182   //    [1:0] - select 128 bits from sources for low half of destination
9183   //    [2]   - ignore
9184   //    [3]   - zero low half of destination
9185   //    [5:4] - select 128 bits from sources for high half of destination
9186   //    [6]   - ignore
9187   //    [7]   - zero high half of destination
9188
9189   int MaskLO = Mask[0];
9190   if (MaskLO == SM_SentinelUndef)
9191     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9192
9193   int MaskHI = Mask[2];
9194   if (MaskHI == SM_SentinelUndef)
9195     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9196
9197   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9198
9199   // If either input is a zero vector, replace it with an undef input.
9200   // Shuffle mask values <  4 are selecting elements of V1.
9201   // Shuffle mask values >= 4 are selecting elements of V2.
9202   // Adjust each half of the permute mask by clearing the half that was
9203   // selecting the zero vector and setting the zero mask bit.
9204   if (IsV1Zero) {
9205     V1 = DAG.getUNDEF(VT);
9206     if (MaskLO < 4)
9207       PermMask = (PermMask & 0xf0) | 0x08;
9208     if (MaskHI < 4)
9209       PermMask = (PermMask & 0x0f) | 0x80;
9210   }
9211   if (IsV2Zero) {
9212     V2 = DAG.getUNDEF(VT);
9213     if (MaskLO >= 4)
9214       PermMask = (PermMask & 0xf0) | 0x08;
9215     if (MaskHI >= 4)
9216       PermMask = (PermMask & 0x0f) | 0x80;
9217   }
9218
9219   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9220                      DAG.getConstant(PermMask, MVT::i8));
9221 }
9222
9223 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9224 /// shuffling each lane.
9225 ///
9226 /// This will only succeed when the result of fixing the 128-bit lanes results
9227 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9228 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9229 /// the lane crosses early and then use simpler shuffles within each lane.
9230 ///
9231 /// FIXME: It might be worthwhile at some point to support this without
9232 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9233 /// in x86 only floating point has interesting non-repeating shuffles, and even
9234 /// those are still *marginally* more expensive.
9235 static SDValue lowerVectorShuffleByMerging128BitLanes(
9236     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9237     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9238   assert(!isSingleInputShuffleMask(Mask) &&
9239          "This is only useful with multiple inputs.");
9240
9241   int Size = Mask.size();
9242   int LaneSize = 128 / VT.getScalarSizeInBits();
9243   int NumLanes = Size / LaneSize;
9244   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9245
9246   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9247   // check whether the in-128-bit lane shuffles share a repeating pattern.
9248   SmallVector<int, 4> Lanes;
9249   Lanes.resize(NumLanes, -1);
9250   SmallVector<int, 4> InLaneMask;
9251   InLaneMask.resize(LaneSize, -1);
9252   for (int i = 0; i < Size; ++i) {
9253     if (Mask[i] < 0)
9254       continue;
9255
9256     int j = i / LaneSize;
9257
9258     if (Lanes[j] < 0) {
9259       // First entry we've seen for this lane.
9260       Lanes[j] = Mask[i] / LaneSize;
9261     } else if (Lanes[j] != Mask[i] / LaneSize) {
9262       // This doesn't match the lane selected previously!
9263       return SDValue();
9264     }
9265
9266     // Check that within each lane we have a consistent shuffle mask.
9267     int k = i % LaneSize;
9268     if (InLaneMask[k] < 0) {
9269       InLaneMask[k] = Mask[i] % LaneSize;
9270     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9271       // This doesn't fit a repeating in-lane mask.
9272       return SDValue();
9273     }
9274   }
9275
9276   // First shuffle the lanes into place.
9277   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9278                                 VT.getSizeInBits() / 64);
9279   SmallVector<int, 8> LaneMask;
9280   LaneMask.resize(NumLanes * 2, -1);
9281   for (int i = 0; i < NumLanes; ++i)
9282     if (Lanes[i] >= 0) {
9283       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9284       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9285     }
9286
9287   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9288   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9289   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9290
9291   // Cast it back to the type we actually want.
9292   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9293
9294   // Now do a simple shuffle that isn't lane crossing.
9295   SmallVector<int, 8> NewMask;
9296   NewMask.resize(Size, -1);
9297   for (int i = 0; i < Size; ++i)
9298     if (Mask[i] >= 0)
9299       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9300   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9301          "Must not introduce lane crosses at this point!");
9302
9303   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9304 }
9305
9306 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9307 /// given mask.
9308 ///
9309 /// This returns true if the elements from a particular input are already in the
9310 /// slot required by the given mask and require no permutation.
9311 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9312   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9313   int Size = Mask.size();
9314   for (int i = 0; i < Size; ++i)
9315     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9316       return false;
9317
9318   return true;
9319 }
9320
9321 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9322 ///
9323 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9324 /// isn't available.
9325 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9326                                        const X86Subtarget *Subtarget,
9327                                        SelectionDAG &DAG) {
9328   SDLoc DL(Op);
9329   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9330   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9331   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9332   ArrayRef<int> Mask = SVOp->getMask();
9333   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9334
9335   SmallVector<int, 4> WidenedMask;
9336   if (canWidenShuffleElements(Mask, WidenedMask))
9337     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9338                                     DAG);
9339
9340   if (isSingleInputShuffleMask(Mask)) {
9341     // Check for being able to broadcast a single element.
9342     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9343                                                           Mask, Subtarget, DAG))
9344       return Broadcast;
9345
9346     // Use low duplicate instructions for masks that match their pattern.
9347     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9348       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9349
9350     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9351       // Non-half-crossing single input shuffles can be lowerid with an
9352       // interleaved permutation.
9353       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9354                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9355       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9356                          DAG.getConstant(VPERMILPMask, MVT::i8));
9357     }
9358
9359     // With AVX2 we have direct support for this permutation.
9360     if (Subtarget->hasAVX2())
9361       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9362                          getV4X86ShuffleImm8ForMask(Mask, DAG));
9363
9364     // Otherwise, fall back.
9365     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9366                                                    DAG);
9367   }
9368
9369   // X86 has dedicated unpack instructions that can handle specific blend
9370   // operations: UNPCKH and UNPCKL.
9371   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9372     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9373   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9374     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9375   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9376     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9377   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9378     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9379
9380   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9381                                                 Subtarget, DAG))
9382     return Blend;
9383
9384   // Check if the blend happens to exactly fit that of SHUFPD.
9385   if ((Mask[0] == -1 || Mask[0] < 2) &&
9386       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9387       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9388       (Mask[3] == -1 || Mask[3] >= 6)) {
9389     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9390                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9391     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9392                        DAG.getConstant(SHUFPDMask, MVT::i8));
9393   }
9394   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9395       (Mask[1] == -1 || Mask[1] < 2) &&
9396       (Mask[2] == -1 || Mask[2] >= 6) &&
9397       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9398     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9399                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9400     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9401                        DAG.getConstant(SHUFPDMask, MVT::i8));
9402   }
9403
9404   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9405   // shuffle. However, if we have AVX2 and either inputs are already in place,
9406   // we will be able to shuffle even across lanes the other input in a single
9407   // instruction so skip this pattern.
9408   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9409                                  isShuffleMaskInputInPlace(1, Mask))))
9410     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9411             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9412       return Result;
9413
9414   // If we have AVX2 then we always want to lower with a blend because an v4 we
9415   // can fully permute the elements.
9416   if (Subtarget->hasAVX2())
9417     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9418                                                       Mask, DAG);
9419
9420   // Otherwise fall back on generic lowering.
9421   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9422 }
9423
9424 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9425 ///
9426 /// This routine is only called when we have AVX2 and thus a reasonable
9427 /// instruction set for v4i64 shuffling..
9428 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9429                                        const X86Subtarget *Subtarget,
9430                                        SelectionDAG &DAG) {
9431   SDLoc DL(Op);
9432   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9433   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9434   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9435   ArrayRef<int> Mask = SVOp->getMask();
9436   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9437   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9438
9439   SmallVector<int, 4> WidenedMask;
9440   if (canWidenShuffleElements(Mask, WidenedMask))
9441     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9442                                     DAG);
9443
9444   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9445                                                 Subtarget, DAG))
9446     return Blend;
9447
9448   // Check for being able to broadcast a single element.
9449   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9450                                                         Mask, Subtarget, DAG))
9451     return Broadcast;
9452
9453   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9454   // use lower latency instructions that will operate on both 128-bit lanes.
9455   SmallVector<int, 2> RepeatedMask;
9456   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9457     if (isSingleInputShuffleMask(Mask)) {
9458       int PSHUFDMask[] = {-1, -1, -1, -1};
9459       for (int i = 0; i < 2; ++i)
9460         if (RepeatedMask[i] >= 0) {
9461           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9462           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9463         }
9464       return DAG.getNode(
9465           ISD::BITCAST, DL, MVT::v4i64,
9466           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9467                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9468                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9469     }
9470   }
9471
9472   // AVX2 provides a direct instruction for permuting a single input across
9473   // lanes.
9474   if (isSingleInputShuffleMask(Mask))
9475     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9476                        getV4X86ShuffleImm8ForMask(Mask, DAG));
9477
9478   // Try to use shift instructions.
9479   if (SDValue Shift =
9480           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9481     return Shift;
9482
9483   // Use dedicated unpack instructions for masks that match their pattern.
9484   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9485     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9486   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9487     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9488   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9489     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9490   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9491     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9492
9493   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9494   // shuffle. However, if we have AVX2 and either inputs are already in place,
9495   // we will be able to shuffle even across lanes the other input in a single
9496   // instruction so skip this pattern.
9497   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9498                                  isShuffleMaskInputInPlace(1, Mask))))
9499     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9500             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9501       return Result;
9502
9503   // Otherwise fall back on generic blend lowering.
9504   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9505                                                     Mask, DAG);
9506 }
9507
9508 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9509 ///
9510 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9511 /// isn't available.
9512 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9513                                        const X86Subtarget *Subtarget,
9514                                        SelectionDAG &DAG) {
9515   SDLoc DL(Op);
9516   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9517   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9518   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9519   ArrayRef<int> Mask = SVOp->getMask();
9520   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9521
9522   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9523                                                 Subtarget, DAG))
9524     return Blend;
9525
9526   // Check for being able to broadcast a single element.
9527   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9528                                                         Mask, Subtarget, DAG))
9529     return Broadcast;
9530
9531   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9532   // options to efficiently lower the shuffle.
9533   SmallVector<int, 4> RepeatedMask;
9534   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9535     assert(RepeatedMask.size() == 4 &&
9536            "Repeated masks must be half the mask width!");
9537
9538     // Use even/odd duplicate instructions for masks that match their pattern.
9539     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9540       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9541     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9542       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9543
9544     if (isSingleInputShuffleMask(Mask))
9545       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9546                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9547
9548     // Use dedicated unpack instructions for masks that match their pattern.
9549     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9550       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9551     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9552       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9553     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9554       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9555     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9556       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9557
9558     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9559     // have already handled any direct blends. We also need to squash the
9560     // repeated mask into a simulated v4f32 mask.
9561     for (int i = 0; i < 4; ++i)
9562       if (RepeatedMask[i] >= 8)
9563         RepeatedMask[i] -= 4;
9564     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9565   }
9566
9567   // If we have a single input shuffle with different shuffle patterns in the
9568   // two 128-bit lanes use the variable mask to VPERMILPS.
9569   if (isSingleInputShuffleMask(Mask)) {
9570     SDValue VPermMask[8];
9571     for (int i = 0; i < 8; ++i)
9572       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9573                                  : DAG.getConstant(Mask[i], MVT::i32);
9574     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9575       return DAG.getNode(
9576           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9577           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9578
9579     if (Subtarget->hasAVX2())
9580       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9581                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9582                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9583                                                  MVT::v8i32, VPermMask)),
9584                          V1);
9585
9586     // Otherwise, fall back.
9587     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9588                                                    DAG);
9589   }
9590
9591   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9592   // shuffle.
9593   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9594           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9595     return Result;
9596
9597   // If we have AVX2 then we always want to lower with a blend because at v8 we
9598   // can fully permute the elements.
9599   if (Subtarget->hasAVX2())
9600     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9601                                                       Mask, DAG);
9602
9603   // Otherwise fall back on generic lowering.
9604   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9605 }
9606
9607 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9608 ///
9609 /// This routine is only called when we have AVX2 and thus a reasonable
9610 /// instruction set for v8i32 shuffling..
9611 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9612                                        const X86Subtarget *Subtarget,
9613                                        SelectionDAG &DAG) {
9614   SDLoc DL(Op);
9615   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9616   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9617   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9618   ArrayRef<int> Mask = SVOp->getMask();
9619   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9620   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9621
9622   // Whenever we can lower this as a zext, that instruction is strictly faster
9623   // than any alternative. It also allows us to fold memory operands into the
9624   // shuffle in many cases.
9625   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9626                                                          Mask, Subtarget, DAG))
9627     return ZExt;
9628
9629   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9630                                                 Subtarget, DAG))
9631     return Blend;
9632
9633   // Check for being able to broadcast a single element.
9634   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9635                                                         Mask, Subtarget, DAG))
9636     return Broadcast;
9637
9638   // If the shuffle mask is repeated in each 128-bit lane we can use more
9639   // efficient instructions that mirror the shuffles across the two 128-bit
9640   // lanes.
9641   SmallVector<int, 4> RepeatedMask;
9642   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9643     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9644     if (isSingleInputShuffleMask(Mask))
9645       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9646                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9647
9648     // Use dedicated unpack instructions for masks that match their pattern.
9649     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9650       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9651     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9652       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9653     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9654       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9655     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9656       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9657   }
9658
9659   // Try to use shift instructions.
9660   if (SDValue Shift =
9661           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9662     return Shift;
9663
9664   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9665           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9666     return Rotate;
9667
9668   // If the shuffle patterns aren't repeated but it is a single input, directly
9669   // generate a cross-lane VPERMD instruction.
9670   if (isSingleInputShuffleMask(Mask)) {
9671     SDValue VPermMask[8];
9672     for (int i = 0; i < 8; ++i)
9673       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9674                                  : DAG.getConstant(Mask[i], MVT::i32);
9675     return DAG.getNode(
9676         X86ISD::VPERMV, DL, MVT::v8i32,
9677         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9678   }
9679
9680   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9681   // shuffle.
9682   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9683           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9684     return Result;
9685
9686   // Otherwise fall back on generic blend lowering.
9687   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9688                                                     Mask, DAG);
9689 }
9690
9691 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9692 ///
9693 /// This routine is only called when we have AVX2 and thus a reasonable
9694 /// instruction set for v16i16 shuffling..
9695 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9696                                         const X86Subtarget *Subtarget,
9697                                         SelectionDAG &DAG) {
9698   SDLoc DL(Op);
9699   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9700   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9701   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9702   ArrayRef<int> Mask = SVOp->getMask();
9703   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9704   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9705
9706   // Whenever we can lower this as a zext, that instruction is strictly faster
9707   // than any alternative. It also allows us to fold memory operands into the
9708   // shuffle in many cases.
9709   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9710                                                          Mask, Subtarget, DAG))
9711     return ZExt;
9712
9713   // Check for being able to broadcast a single element.
9714   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9715                                                         Mask, Subtarget, DAG))
9716     return Broadcast;
9717
9718   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9719                                                 Subtarget, DAG))
9720     return Blend;
9721
9722   // Use dedicated unpack instructions for masks that match their pattern.
9723   if (isShuffleEquivalent(V1, V2, Mask,
9724                           {// First 128-bit lane:
9725                            0, 16, 1, 17, 2, 18, 3, 19,
9726                            // Second 128-bit lane:
9727                            8, 24, 9, 25, 10, 26, 11, 27}))
9728     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9729   if (isShuffleEquivalent(V1, V2, Mask,
9730                           {// First 128-bit lane:
9731                            4, 20, 5, 21, 6, 22, 7, 23,
9732                            // Second 128-bit lane:
9733                            12, 28, 13, 29, 14, 30, 15, 31}))
9734     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9735
9736   // Try to use shift instructions.
9737   if (SDValue Shift =
9738           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9739     return Shift;
9740
9741   // Try to use byte rotation instructions.
9742   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9743           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9744     return Rotate;
9745
9746   if (isSingleInputShuffleMask(Mask)) {
9747     // There are no generalized cross-lane shuffle operations available on i16
9748     // element types.
9749     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9750       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9751                                                      Mask, DAG);
9752
9753     SmallVector<int, 8> RepeatedMask;
9754     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9755       // As this is a single-input shuffle, the repeated mask should be
9756       // a strictly valid v8i16 mask that we can pass through to the v8i16
9757       // lowering to handle even the v16 case.
9758       return lowerV8I16GeneralSingleInputVectorShuffle(
9759           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9760     }
9761
9762     SDValue PSHUFBMask[32];
9763     for (int i = 0; i < 16; ++i) {
9764       if (Mask[i] == -1) {
9765         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9766         continue;
9767       }
9768
9769       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9770       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9771       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
9772       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
9773     }
9774     return DAG.getNode(
9775         ISD::BITCAST, DL, MVT::v16i16,
9776         DAG.getNode(
9777             X86ISD::PSHUFB, DL, MVT::v32i8,
9778             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9779             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9780   }
9781
9782   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9783   // shuffle.
9784   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9785           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9786     return Result;
9787
9788   // Otherwise fall back on generic lowering.
9789   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9790 }
9791
9792 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9793 ///
9794 /// This routine is only called when we have AVX2 and thus a reasonable
9795 /// instruction set for v32i8 shuffling..
9796 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9797                                        const X86Subtarget *Subtarget,
9798                                        SelectionDAG &DAG) {
9799   SDLoc DL(Op);
9800   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9801   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9802   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9803   ArrayRef<int> Mask = SVOp->getMask();
9804   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9805   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9806
9807   // Whenever we can lower this as a zext, that instruction is strictly faster
9808   // than any alternative. It also allows us to fold memory operands into the
9809   // shuffle in many cases.
9810   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9811                                                          Mask, Subtarget, DAG))
9812     return ZExt;
9813
9814   // Check for being able to broadcast a single element.
9815   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9816                                                         Mask, Subtarget, DAG))
9817     return Broadcast;
9818
9819   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9820                                                 Subtarget, DAG))
9821     return Blend;
9822
9823   // Use dedicated unpack instructions for masks that match their pattern.
9824   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9825   // 256-bit lanes.
9826   if (isShuffleEquivalent(
9827           V1, V2, Mask,
9828           {// First 128-bit lane:
9829            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9830            // Second 128-bit lane:
9831            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9832     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9833   if (isShuffleEquivalent(
9834           V1, V2, Mask,
9835           {// First 128-bit lane:
9836            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9837            // Second 128-bit lane:
9838            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9839     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9840
9841   // Try to use shift instructions.
9842   if (SDValue Shift =
9843           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9844     return Shift;
9845
9846   // Try to use byte rotation instructions.
9847   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9848           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9849     return Rotate;
9850
9851   if (isSingleInputShuffleMask(Mask)) {
9852     // There are no generalized cross-lane shuffle operations available on i8
9853     // element types.
9854     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9855       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9856                                                      Mask, DAG);
9857
9858     SDValue PSHUFBMask[32];
9859     for (int i = 0; i < 32; ++i)
9860       PSHUFBMask[i] =
9861           Mask[i] < 0
9862               ? DAG.getUNDEF(MVT::i8)
9863               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
9864
9865     return DAG.getNode(
9866         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9867         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9868   }
9869
9870   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9871   // shuffle.
9872   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9873           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9874     return Result;
9875
9876   // Otherwise fall back on generic lowering.
9877   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9878 }
9879
9880 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9881 ///
9882 /// This routine either breaks down the specific type of a 256-bit x86 vector
9883 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9884 /// together based on the available instructions.
9885 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9886                                         MVT VT, const X86Subtarget *Subtarget,
9887                                         SelectionDAG &DAG) {
9888   SDLoc DL(Op);
9889   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9890   ArrayRef<int> Mask = SVOp->getMask();
9891
9892   // If we have a single input to the zero element, insert that into V1 if we
9893   // can do so cheaply.
9894   int NumElts = VT.getVectorNumElements();
9895   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9896     return M >= NumElts;
9897   });
9898
9899   if (NumV2Elements == 1 && Mask[0] >= NumElts)
9900     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9901                               DL, VT, V1, V2, Mask, Subtarget, DAG))
9902       return Insertion;
9903
9904   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9905   // check for those subtargets here and avoid much of the subtarget querying in
9906   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9907   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9908   // floating point types there eventually, just immediately cast everything to
9909   // a float and operate entirely in that domain.
9910   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9911     int ElementBits = VT.getScalarSizeInBits();
9912     if (ElementBits < 32)
9913       // No floating point type available, decompose into 128-bit vectors.
9914       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9915
9916     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9917                                 VT.getVectorNumElements());
9918     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9919     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9920     return DAG.getNode(ISD::BITCAST, DL, VT,
9921                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9922   }
9923
9924   switch (VT.SimpleTy) {
9925   case MVT::v4f64:
9926     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9927   case MVT::v4i64:
9928     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9929   case MVT::v8f32:
9930     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9931   case MVT::v8i32:
9932     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9933   case MVT::v16i16:
9934     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9935   case MVT::v32i8:
9936     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9937
9938   default:
9939     llvm_unreachable("Not a valid 256-bit x86 vector type!");
9940   }
9941 }
9942
9943 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9944 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9945                                        const X86Subtarget *Subtarget,
9946                                        SelectionDAG &DAG) {
9947   SDLoc DL(Op);
9948   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9949   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9950   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9951   ArrayRef<int> Mask = SVOp->getMask();
9952   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9953
9954   // X86 has dedicated unpack instructions that can handle specific blend
9955   // operations: UNPCKH and UNPCKL.
9956   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9957     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
9958   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9959     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
9960
9961   // FIXME: Implement direct support for this type!
9962   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
9963 }
9964
9965 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
9966 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9967                                        const X86Subtarget *Subtarget,
9968                                        SelectionDAG &DAG) {
9969   SDLoc DL(Op);
9970   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9971   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9972   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9973   ArrayRef<int> Mask = SVOp->getMask();
9974   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9975
9976   // Use dedicated unpack instructions for masks that match their pattern.
9977   if (isShuffleEquivalent(V1, V2, Mask,
9978                           {// First 128-bit lane.
9979                            0, 16, 1, 17, 4, 20, 5, 21,
9980                            // Second 128-bit lane.
9981                            8, 24, 9, 25, 12, 28, 13, 29}))
9982     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
9983   if (isShuffleEquivalent(V1, V2, Mask,
9984                           {// First 128-bit lane.
9985                            2, 18, 3, 19, 6, 22, 7, 23,
9986                            // Second 128-bit lane.
9987                            10, 26, 11, 27, 14, 30, 15, 31}))
9988     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
9989
9990   // FIXME: Implement direct support for this type!
9991   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
9992 }
9993
9994 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
9995 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9996                                        const X86Subtarget *Subtarget,
9997                                        SelectionDAG &DAG) {
9998   SDLoc DL(Op);
9999   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10000   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10001   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10002   ArrayRef<int> Mask = SVOp->getMask();
10003   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10004
10005   // X86 has dedicated unpack instructions that can handle specific blend
10006   // operations: UNPCKH and UNPCKL.
10007   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10008     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10009   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10010     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10011
10012   // FIXME: Implement direct support for this type!
10013   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10014 }
10015
10016 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10017 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10018                                        const X86Subtarget *Subtarget,
10019                                        SelectionDAG &DAG) {
10020   SDLoc DL(Op);
10021   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10022   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10023   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10024   ArrayRef<int> Mask = SVOp->getMask();
10025   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10026
10027   // Use dedicated unpack instructions for masks that match their pattern.
10028   if (isShuffleEquivalent(V1, V2, Mask,
10029                           {// First 128-bit lane.
10030                            0, 16, 1, 17, 4, 20, 5, 21,
10031                            // Second 128-bit lane.
10032                            8, 24, 9, 25, 12, 28, 13, 29}))
10033     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10034   if (isShuffleEquivalent(V1, V2, Mask,
10035                           {// First 128-bit lane.
10036                            2, 18, 3, 19, 6, 22, 7, 23,
10037                            // Second 128-bit lane.
10038                            10, 26, 11, 27, 14, 30, 15, 31}))
10039     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10040
10041   // FIXME: Implement direct support for this type!
10042   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10043 }
10044
10045 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10046 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10047                                         const X86Subtarget *Subtarget,
10048                                         SelectionDAG &DAG) {
10049   SDLoc DL(Op);
10050   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10051   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10052   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10053   ArrayRef<int> Mask = SVOp->getMask();
10054   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10055   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10056
10057   // FIXME: Implement direct support for this type!
10058   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10059 }
10060
10061 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10062 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10063                                        const X86Subtarget *Subtarget,
10064                                        SelectionDAG &DAG) {
10065   SDLoc DL(Op);
10066   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10067   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10068   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10069   ArrayRef<int> Mask = SVOp->getMask();
10070   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10071   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10072
10073   // FIXME: Implement direct support for this type!
10074   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10075 }
10076
10077 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10078 ///
10079 /// This routine either breaks down the specific type of a 512-bit x86 vector
10080 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10081 /// together based on the available instructions.
10082 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10083                                         MVT VT, const X86Subtarget *Subtarget,
10084                                         SelectionDAG &DAG) {
10085   SDLoc DL(Op);
10086   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10087   ArrayRef<int> Mask = SVOp->getMask();
10088   assert(Subtarget->hasAVX512() &&
10089          "Cannot lower 512-bit vectors w/ basic ISA!");
10090
10091   // Check for being able to broadcast a single element.
10092   if (SDValue Broadcast =
10093           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10094     return Broadcast;
10095
10096   // Dispatch to each element type for lowering. If we don't have supprot for
10097   // specific element type shuffles at 512 bits, immediately split them and
10098   // lower them. Each lowering routine of a given type is allowed to assume that
10099   // the requisite ISA extensions for that element type are available.
10100   switch (VT.SimpleTy) {
10101   case MVT::v8f64:
10102     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10103   case MVT::v16f32:
10104     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10105   case MVT::v8i64:
10106     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10107   case MVT::v16i32:
10108     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10109   case MVT::v32i16:
10110     if (Subtarget->hasBWI())
10111       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10112     break;
10113   case MVT::v64i8:
10114     if (Subtarget->hasBWI())
10115       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10116     break;
10117
10118   default:
10119     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10120   }
10121
10122   // Otherwise fall back on splitting.
10123   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10124 }
10125
10126 /// \brief Top-level lowering for x86 vector shuffles.
10127 ///
10128 /// This handles decomposition, canonicalization, and lowering of all x86
10129 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10130 /// above in helper routines. The canonicalization attempts to widen shuffles
10131 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10132 /// s.t. only one of the two inputs needs to be tested, etc.
10133 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10134                                   SelectionDAG &DAG) {
10135   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10136   ArrayRef<int> Mask = SVOp->getMask();
10137   SDValue V1 = Op.getOperand(0);
10138   SDValue V2 = Op.getOperand(1);
10139   MVT VT = Op.getSimpleValueType();
10140   int NumElements = VT.getVectorNumElements();
10141   SDLoc dl(Op);
10142
10143   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10144
10145   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10146   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10147   if (V1IsUndef && V2IsUndef)
10148     return DAG.getUNDEF(VT);
10149
10150   // When we create a shuffle node we put the UNDEF node to second operand,
10151   // but in some cases the first operand may be transformed to UNDEF.
10152   // In this case we should just commute the node.
10153   if (V1IsUndef)
10154     return DAG.getCommutedVectorShuffle(*SVOp);
10155
10156   // Check for non-undef masks pointing at an undef vector and make the masks
10157   // undef as well. This makes it easier to match the shuffle based solely on
10158   // the mask.
10159   if (V2IsUndef)
10160     for (int M : Mask)
10161       if (M >= NumElements) {
10162         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10163         for (int &M : NewMask)
10164           if (M >= NumElements)
10165             M = -1;
10166         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10167       }
10168
10169   // We actually see shuffles that are entirely re-arrangements of a set of
10170   // zero inputs. This mostly happens while decomposing complex shuffles into
10171   // simple ones. Directly lower these as a buildvector of zeros.
10172   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10173   if (Zeroable.all())
10174     return getZeroVector(VT, Subtarget, DAG, dl);
10175
10176   // Try to collapse shuffles into using a vector type with fewer elements but
10177   // wider element types. We cap this to not form integers or floating point
10178   // elements wider than 64 bits, but it might be interesting to form i128
10179   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10180   SmallVector<int, 16> WidenedMask;
10181   if (VT.getScalarSizeInBits() < 64 &&
10182       canWidenShuffleElements(Mask, WidenedMask)) {
10183     MVT NewEltVT = VT.isFloatingPoint()
10184                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10185                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10186     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10187     // Make sure that the new vector type is legal. For example, v2f64 isn't
10188     // legal on SSE1.
10189     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10190       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10191       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10192       return DAG.getNode(ISD::BITCAST, dl, VT,
10193                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10194     }
10195   }
10196
10197   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10198   for (int M : SVOp->getMask())
10199     if (M < 0)
10200       ++NumUndefElements;
10201     else if (M < NumElements)
10202       ++NumV1Elements;
10203     else
10204       ++NumV2Elements;
10205
10206   // Commute the shuffle as needed such that more elements come from V1 than
10207   // V2. This allows us to match the shuffle pattern strictly on how many
10208   // elements come from V1 without handling the symmetric cases.
10209   if (NumV2Elements > NumV1Elements)
10210     return DAG.getCommutedVectorShuffle(*SVOp);
10211
10212   // When the number of V1 and V2 elements are the same, try to minimize the
10213   // number of uses of V2 in the low half of the vector. When that is tied,
10214   // ensure that the sum of indices for V1 is equal to or lower than the sum
10215   // indices for V2. When those are equal, try to ensure that the number of odd
10216   // indices for V1 is lower than the number of odd indices for V2.
10217   if (NumV1Elements == NumV2Elements) {
10218     int LowV1Elements = 0, LowV2Elements = 0;
10219     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10220       if (M >= NumElements)
10221         ++LowV2Elements;
10222       else if (M >= 0)
10223         ++LowV1Elements;
10224     if (LowV2Elements > LowV1Elements) {
10225       return DAG.getCommutedVectorShuffle(*SVOp);
10226     } else if (LowV2Elements == LowV1Elements) {
10227       int SumV1Indices = 0, SumV2Indices = 0;
10228       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10229         if (SVOp->getMask()[i] >= NumElements)
10230           SumV2Indices += i;
10231         else if (SVOp->getMask()[i] >= 0)
10232           SumV1Indices += i;
10233       if (SumV2Indices < SumV1Indices) {
10234         return DAG.getCommutedVectorShuffle(*SVOp);
10235       } else if (SumV2Indices == SumV1Indices) {
10236         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10237         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10238           if (SVOp->getMask()[i] >= NumElements)
10239             NumV2OddIndices += i % 2;
10240           else if (SVOp->getMask()[i] >= 0)
10241             NumV1OddIndices += i % 2;
10242         if (NumV2OddIndices < NumV1OddIndices)
10243           return DAG.getCommutedVectorShuffle(*SVOp);
10244       }
10245     }
10246   }
10247
10248   // For each vector width, delegate to a specialized lowering routine.
10249   if (VT.getSizeInBits() == 128)
10250     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10251
10252   if (VT.getSizeInBits() == 256)
10253     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10254
10255   // Force AVX-512 vectors to be scalarized for now.
10256   // FIXME: Implement AVX-512 support!
10257   if (VT.getSizeInBits() == 512)
10258     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10259
10260   llvm_unreachable("Unimplemented!");
10261 }
10262
10263 // This function assumes its argument is a BUILD_VECTOR of constants or
10264 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10265 // true.
10266 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10267                                     unsigned &MaskValue) {
10268   MaskValue = 0;
10269   unsigned NumElems = BuildVector->getNumOperands();
10270   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10271   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10272   unsigned NumElemsInLane = NumElems / NumLanes;
10273
10274   // Blend for v16i16 should be symetric for the both lanes.
10275   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10276     SDValue EltCond = BuildVector->getOperand(i);
10277     SDValue SndLaneEltCond =
10278         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10279
10280     int Lane1Cond = -1, Lane2Cond = -1;
10281     if (isa<ConstantSDNode>(EltCond))
10282       Lane1Cond = !isZero(EltCond);
10283     if (isa<ConstantSDNode>(SndLaneEltCond))
10284       Lane2Cond = !isZero(SndLaneEltCond);
10285
10286     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10287       // Lane1Cond != 0, means we want the first argument.
10288       // Lane1Cond == 0, means we want the second argument.
10289       // The encoding of this argument is 0 for the first argument, 1
10290       // for the second. Therefore, invert the condition.
10291       MaskValue |= !Lane1Cond << i;
10292     else if (Lane1Cond < 0)
10293       MaskValue |= !Lane2Cond << i;
10294     else
10295       return false;
10296   }
10297   return true;
10298 }
10299
10300 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10301 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10302                                            const X86Subtarget *Subtarget,
10303                                            SelectionDAG &DAG) {
10304   SDValue Cond = Op.getOperand(0);
10305   SDValue LHS = Op.getOperand(1);
10306   SDValue RHS = Op.getOperand(2);
10307   SDLoc dl(Op);
10308   MVT VT = Op.getSimpleValueType();
10309
10310   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10311     return SDValue();
10312   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10313
10314   // Only non-legal VSELECTs reach this lowering, convert those into generic
10315   // shuffles and re-use the shuffle lowering path for blends.
10316   SmallVector<int, 32> Mask;
10317   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10318     SDValue CondElt = CondBV->getOperand(i);
10319     Mask.push_back(
10320         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10321   }
10322   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10323 }
10324
10325 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10326   // A vselect where all conditions and data are constants can be optimized into
10327   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10328   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10329       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10330       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10331     return SDValue();
10332
10333   // Try to lower this to a blend-style vector shuffle. This can handle all
10334   // constant condition cases.
10335   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10336     return BlendOp;
10337
10338   // Variable blends are only legal from SSE4.1 onward.
10339   if (!Subtarget->hasSSE41())
10340     return SDValue();
10341
10342   // Only some types will be legal on some subtargets. If we can emit a legal
10343   // VSELECT-matching blend, return Op, and but if we need to expand, return
10344   // a null value.
10345   switch (Op.getSimpleValueType().SimpleTy) {
10346   default:
10347     // Most of the vector types have blends past SSE4.1.
10348     return Op;
10349
10350   case MVT::v32i8:
10351     // The byte blends for AVX vectors were introduced only in AVX2.
10352     if (Subtarget->hasAVX2())
10353       return Op;
10354
10355     return SDValue();
10356
10357   case MVT::v8i16:
10358   case MVT::v16i16:
10359     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10360     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10361       return Op;
10362
10363     // FIXME: We should custom lower this by fixing the condition and using i8
10364     // blends.
10365     return SDValue();
10366   }
10367 }
10368
10369 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10370   MVT VT = Op.getSimpleValueType();
10371   SDLoc dl(Op);
10372
10373   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10374     return SDValue();
10375
10376   if (VT.getSizeInBits() == 8) {
10377     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10378                                   Op.getOperand(0), Op.getOperand(1));
10379     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10380                                   DAG.getValueType(VT));
10381     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10382   }
10383
10384   if (VT.getSizeInBits() == 16) {
10385     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10386     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10387     if (Idx == 0)
10388       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10389                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10390                                      DAG.getNode(ISD::BITCAST, dl,
10391                                                  MVT::v4i32,
10392                                                  Op.getOperand(0)),
10393                                      Op.getOperand(1)));
10394     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10395                                   Op.getOperand(0), Op.getOperand(1));
10396     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10397                                   DAG.getValueType(VT));
10398     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10399   }
10400
10401   if (VT == MVT::f32) {
10402     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10403     // the result back to FR32 register. It's only worth matching if the
10404     // result has a single use which is a store or a bitcast to i32.  And in
10405     // the case of a store, it's not worth it if the index is a constant 0,
10406     // because a MOVSSmr can be used instead, which is smaller and faster.
10407     if (!Op.hasOneUse())
10408       return SDValue();
10409     SDNode *User = *Op.getNode()->use_begin();
10410     if ((User->getOpcode() != ISD::STORE ||
10411          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10412           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10413         (User->getOpcode() != ISD::BITCAST ||
10414          User->getValueType(0) != MVT::i32))
10415       return SDValue();
10416     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10417                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10418                                               Op.getOperand(0)),
10419                                               Op.getOperand(1));
10420     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10421   }
10422
10423   if (VT == MVT::i32 || VT == MVT::i64) {
10424     // ExtractPS/pextrq works with constant index.
10425     if (isa<ConstantSDNode>(Op.getOperand(1)))
10426       return Op;
10427   }
10428   return SDValue();
10429 }
10430
10431 /// Extract one bit from mask vector, like v16i1 or v8i1.
10432 /// AVX-512 feature.
10433 SDValue
10434 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10435   SDValue Vec = Op.getOperand(0);
10436   SDLoc dl(Vec);
10437   MVT VecVT = Vec.getSimpleValueType();
10438   SDValue Idx = Op.getOperand(1);
10439   MVT EltVT = Op.getSimpleValueType();
10440
10441   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10442   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10443          "Unexpected vector type in ExtractBitFromMaskVector");
10444
10445   // variable index can't be handled in mask registers,
10446   // extend vector to VR512
10447   if (!isa<ConstantSDNode>(Idx)) {
10448     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10449     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10450     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10451                               ExtVT.getVectorElementType(), Ext, Idx);
10452     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10453   }
10454
10455   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10456   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10457   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10458     rc = getRegClassFor(MVT::v16i1);
10459   unsigned MaxSift = rc->getSize()*8 - 1;
10460   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10461                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10462   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10463                     DAG.getConstant(MaxSift, MVT::i8));
10464   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10465                        DAG.getIntPtrConstant(0));
10466 }
10467
10468 SDValue
10469 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10470                                            SelectionDAG &DAG) const {
10471   SDLoc dl(Op);
10472   SDValue Vec = Op.getOperand(0);
10473   MVT VecVT = Vec.getSimpleValueType();
10474   SDValue Idx = Op.getOperand(1);
10475
10476   if (Op.getSimpleValueType() == MVT::i1)
10477     return ExtractBitFromMaskVector(Op, DAG);
10478
10479   if (!isa<ConstantSDNode>(Idx)) {
10480     if (VecVT.is512BitVector() ||
10481         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10482          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10483
10484       MVT MaskEltVT =
10485         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10486       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10487                                     MaskEltVT.getSizeInBits());
10488
10489       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10490       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10491                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10492                                 Idx, DAG.getConstant(0, getPointerTy()));
10493       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10494       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10495                         Perm, DAG.getConstant(0, getPointerTy()));
10496     }
10497     return SDValue();
10498   }
10499
10500   // If this is a 256-bit vector result, first extract the 128-bit vector and
10501   // then extract the element from the 128-bit vector.
10502   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10503
10504     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10505     // Get the 128-bit vector.
10506     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10507     MVT EltVT = VecVT.getVectorElementType();
10508
10509     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10510
10511     //if (IdxVal >= NumElems/2)
10512     //  IdxVal -= NumElems/2;
10513     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10514     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10515                        DAG.getConstant(IdxVal, MVT::i32));
10516   }
10517
10518   assert(VecVT.is128BitVector() && "Unexpected vector length");
10519
10520   if (Subtarget->hasSSE41()) {
10521     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10522     if (Res.getNode())
10523       return Res;
10524   }
10525
10526   MVT VT = Op.getSimpleValueType();
10527   // TODO: handle v16i8.
10528   if (VT.getSizeInBits() == 16) {
10529     SDValue Vec = Op.getOperand(0);
10530     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10531     if (Idx == 0)
10532       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10533                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10534                                      DAG.getNode(ISD::BITCAST, dl,
10535                                                  MVT::v4i32, Vec),
10536                                      Op.getOperand(1)));
10537     // Transform it so it match pextrw which produces a 32-bit result.
10538     MVT EltVT = MVT::i32;
10539     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10540                                   Op.getOperand(0), Op.getOperand(1));
10541     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10542                                   DAG.getValueType(VT));
10543     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10544   }
10545
10546   if (VT.getSizeInBits() == 32) {
10547     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10548     if (Idx == 0)
10549       return Op;
10550
10551     // SHUFPS the element to the lowest double word, then movss.
10552     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10553     MVT VVT = Op.getOperand(0).getSimpleValueType();
10554     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10555                                        DAG.getUNDEF(VVT), Mask);
10556     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10557                        DAG.getIntPtrConstant(0));
10558   }
10559
10560   if (VT.getSizeInBits() == 64) {
10561     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10562     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10563     //        to match extract_elt for f64.
10564     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10565     if (Idx == 0)
10566       return Op;
10567
10568     // UNPCKHPD the element to the lowest double word, then movsd.
10569     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10570     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10571     int Mask[2] = { 1, -1 };
10572     MVT VVT = Op.getOperand(0).getSimpleValueType();
10573     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10574                                        DAG.getUNDEF(VVT), Mask);
10575     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10576                        DAG.getIntPtrConstant(0));
10577   }
10578
10579   return SDValue();
10580 }
10581
10582 /// Insert one bit to mask vector, like v16i1 or v8i1.
10583 /// AVX-512 feature.
10584 SDValue
10585 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10586   SDLoc dl(Op);
10587   SDValue Vec = Op.getOperand(0);
10588   SDValue Elt = Op.getOperand(1);
10589   SDValue Idx = Op.getOperand(2);
10590   MVT VecVT = Vec.getSimpleValueType();
10591
10592   if (!isa<ConstantSDNode>(Idx)) {
10593     // Non constant index. Extend source and destination,
10594     // insert element and then truncate the result.
10595     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10596     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10597     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10598       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10599       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10600     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10601   }
10602
10603   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10604   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10605   if (Vec.getOpcode() == ISD::UNDEF)
10606     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10607                        DAG.getConstant(IdxVal, MVT::i8));
10608   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10609   unsigned MaxSift = rc->getSize()*8 - 1;
10610   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10611                     DAG.getConstant(MaxSift, MVT::i8));
10612   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10613                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10614   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10615 }
10616
10617 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10618                                                   SelectionDAG &DAG) const {
10619   MVT VT = Op.getSimpleValueType();
10620   MVT EltVT = VT.getVectorElementType();
10621
10622   if (EltVT == MVT::i1)
10623     return InsertBitToMaskVector(Op, DAG);
10624
10625   SDLoc dl(Op);
10626   SDValue N0 = Op.getOperand(0);
10627   SDValue N1 = Op.getOperand(1);
10628   SDValue N2 = Op.getOperand(2);
10629   if (!isa<ConstantSDNode>(N2))
10630     return SDValue();
10631   auto *N2C = cast<ConstantSDNode>(N2);
10632   unsigned IdxVal = N2C->getZExtValue();
10633
10634   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10635   // into that, and then insert the subvector back into the result.
10636   if (VT.is256BitVector() || VT.is512BitVector()) {
10637     // With a 256-bit vector, we can insert into the zero element efficiently
10638     // using a blend if we have AVX or AVX2 and the right data type.
10639     if (VT.is256BitVector() && IdxVal == 0) {
10640       // TODO: It is worthwhile to cast integer to floating point and back
10641       // and incur a domain crossing penalty if that's what we'll end up
10642       // doing anyway after extracting to a 128-bit vector.
10643       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10644           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10645         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10646         N2 = DAG.getIntPtrConstant(1);
10647         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10648       }
10649     }
10650
10651     // Get the desired 128-bit vector chunk.
10652     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10653
10654     // Insert the element into the desired chunk.
10655     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10656     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10657
10658     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10659                     DAG.getConstant(IdxIn128, MVT::i32));
10660
10661     // Insert the changed part back into the bigger vector
10662     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10663   }
10664   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10665
10666   if (Subtarget->hasSSE41()) {
10667     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10668       unsigned Opc;
10669       if (VT == MVT::v8i16) {
10670         Opc = X86ISD::PINSRW;
10671       } else {
10672         assert(VT == MVT::v16i8);
10673         Opc = X86ISD::PINSRB;
10674       }
10675
10676       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10677       // argument.
10678       if (N1.getValueType() != MVT::i32)
10679         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10680       if (N2.getValueType() != MVT::i32)
10681         N2 = DAG.getIntPtrConstant(IdxVal);
10682       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10683     }
10684
10685     if (EltVT == MVT::f32) {
10686       // Bits [7:6] of the constant are the source select. This will always be
10687       //   zero here. The DAG Combiner may combine an extract_elt index into
10688       //   these bits. For example (insert (extract, 3), 2) could be matched by
10689       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10690       // Bits [5:4] of the constant are the destination select. This is the
10691       //   value of the incoming immediate.
10692       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10693       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10694
10695       const Function *F = DAG.getMachineFunction().getFunction();
10696       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10697       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10698         // If this is an insertion of 32-bits into the low 32-bits of
10699         // a vector, we prefer to generate a blend with immediate rather
10700         // than an insertps. Blends are simpler operations in hardware and so
10701         // will always have equal or better performance than insertps.
10702         // But if optimizing for size and there's a load folding opportunity,
10703         // generate insertps because blendps does not have a 32-bit memory
10704         // operand form.
10705         N2 = DAG.getIntPtrConstant(1);
10706         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10707         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10708       }
10709       N2 = DAG.getIntPtrConstant(IdxVal << 4);
10710       // Create this as a scalar to vector..
10711       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10712       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10713     }
10714
10715     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10716       // PINSR* works with constant index.
10717       return Op;
10718     }
10719   }
10720
10721   if (EltVT == MVT::i8)
10722     return SDValue();
10723
10724   if (EltVT.getSizeInBits() == 16) {
10725     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10726     // as its second argument.
10727     if (N1.getValueType() != MVT::i32)
10728       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10729     if (N2.getValueType() != MVT::i32)
10730       N2 = DAG.getIntPtrConstant(IdxVal);
10731     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10732   }
10733   return SDValue();
10734 }
10735
10736 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10737   SDLoc dl(Op);
10738   MVT OpVT = Op.getSimpleValueType();
10739
10740   // If this is a 256-bit vector result, first insert into a 128-bit
10741   // vector and then insert into the 256-bit vector.
10742   if (!OpVT.is128BitVector()) {
10743     // Insert into a 128-bit vector.
10744     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10745     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10746                                  OpVT.getVectorNumElements() / SizeFactor);
10747
10748     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10749
10750     // Insert the 128-bit vector.
10751     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10752   }
10753
10754   if (OpVT == MVT::v1i64 &&
10755       Op.getOperand(0).getValueType() == MVT::i64)
10756     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10757
10758   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10759   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10760   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10761                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10762 }
10763
10764 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10765 // a simple subregister reference or explicit instructions to grab
10766 // upper bits of a vector.
10767 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10768                                       SelectionDAG &DAG) {
10769   SDLoc dl(Op);
10770   SDValue In =  Op.getOperand(0);
10771   SDValue Idx = Op.getOperand(1);
10772   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10773   MVT ResVT   = Op.getSimpleValueType();
10774   MVT InVT    = In.getSimpleValueType();
10775
10776   if (Subtarget->hasFp256()) {
10777     if (ResVT.is128BitVector() &&
10778         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10779         isa<ConstantSDNode>(Idx)) {
10780       return Extract128BitVector(In, IdxVal, DAG, dl);
10781     }
10782     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10783         isa<ConstantSDNode>(Idx)) {
10784       return Extract256BitVector(In, IdxVal, DAG, dl);
10785     }
10786   }
10787   return SDValue();
10788 }
10789
10790 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10791 // simple superregister reference or explicit instructions to insert
10792 // the upper bits of a vector.
10793 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10794                                      SelectionDAG &DAG) {
10795   if (!Subtarget->hasAVX())
10796     return SDValue();
10797
10798   SDLoc dl(Op);
10799   SDValue Vec = Op.getOperand(0);
10800   SDValue SubVec = Op.getOperand(1);
10801   SDValue Idx = Op.getOperand(2);
10802
10803   if (!isa<ConstantSDNode>(Idx))
10804     return SDValue();
10805
10806   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10807   MVT OpVT = Op.getSimpleValueType();
10808   MVT SubVecVT = SubVec.getSimpleValueType();
10809
10810   // Fold two 16-byte subvector loads into one 32-byte load:
10811   // (insert_subvector (insert_subvector undef, (load addr), 0),
10812   //                   (load addr + 16), Elts/2)
10813   // --> load32 addr
10814   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10815       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10816       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10817       !Subtarget->isUnalignedMem32Slow()) {
10818     SDValue SubVec2 = Vec.getOperand(1);
10819     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10820       if (Idx2->getZExtValue() == 0) {
10821         SDValue Ops[] = { SubVec2, SubVec };
10822         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10823         if (LD.getNode())
10824           return LD;
10825       }
10826     }
10827   }
10828
10829   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10830       SubVecVT.is128BitVector())
10831     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10832
10833   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10834     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10835
10836   if (OpVT.getVectorElementType() == MVT::i1) {
10837     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10838       return Op;
10839     SDValue ZeroIdx = DAG.getIntPtrConstant(0);
10840     SDValue Undef = DAG.getUNDEF(OpVT);
10841     unsigned NumElems = OpVT.getVectorNumElements();
10842     SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
10843
10844     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10845       // Zero upper bits of the Vec
10846       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10847       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10848
10849       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10850                                  SubVec, ZeroIdx);
10851       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10852       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10853     }
10854     if (IdxVal == 0) {
10855       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10856                                  SubVec, ZeroIdx);
10857       // Zero upper bits of the Vec2
10858       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10859       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10860       // Zero lower bits of the Vec
10861       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10862       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10863       // Merge them together
10864       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10865     }
10866   }
10867   return SDValue();
10868 }
10869
10870 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10871 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10872 // one of the above mentioned nodes. It has to be wrapped because otherwise
10873 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10874 // be used to form addressing mode. These wrapped nodes will be selected
10875 // into MOV32ri.
10876 SDValue
10877 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10878   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10879
10880   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10881   // global base reg.
10882   unsigned char OpFlag = 0;
10883   unsigned WrapperKind = X86ISD::Wrapper;
10884   CodeModel::Model M = DAG.getTarget().getCodeModel();
10885
10886   if (Subtarget->isPICStyleRIPRel() &&
10887       (M == CodeModel::Small || M == CodeModel::Kernel))
10888     WrapperKind = X86ISD::WrapperRIP;
10889   else if (Subtarget->isPICStyleGOT())
10890     OpFlag = X86II::MO_GOTOFF;
10891   else if (Subtarget->isPICStyleStubPIC())
10892     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10893
10894   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10895                                              CP->getAlignment(),
10896                                              CP->getOffset(), OpFlag);
10897   SDLoc DL(CP);
10898   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10899   // With PIC, the address is actually $g + Offset.
10900   if (OpFlag) {
10901     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10902                          DAG.getNode(X86ISD::GlobalBaseReg,
10903                                      SDLoc(), getPointerTy()),
10904                          Result);
10905   }
10906
10907   return Result;
10908 }
10909
10910 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10911   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10912
10913   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10914   // global base reg.
10915   unsigned char OpFlag = 0;
10916   unsigned WrapperKind = X86ISD::Wrapper;
10917   CodeModel::Model M = DAG.getTarget().getCodeModel();
10918
10919   if (Subtarget->isPICStyleRIPRel() &&
10920       (M == CodeModel::Small || M == CodeModel::Kernel))
10921     WrapperKind = X86ISD::WrapperRIP;
10922   else if (Subtarget->isPICStyleGOT())
10923     OpFlag = X86II::MO_GOTOFF;
10924   else if (Subtarget->isPICStyleStubPIC())
10925     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10926
10927   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10928                                           OpFlag);
10929   SDLoc DL(JT);
10930   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10931
10932   // With PIC, the address is actually $g + Offset.
10933   if (OpFlag)
10934     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10935                          DAG.getNode(X86ISD::GlobalBaseReg,
10936                                      SDLoc(), getPointerTy()),
10937                          Result);
10938
10939   return Result;
10940 }
10941
10942 SDValue
10943 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10944   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10945
10946   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10947   // global base reg.
10948   unsigned char OpFlag = 0;
10949   unsigned WrapperKind = X86ISD::Wrapper;
10950   CodeModel::Model M = DAG.getTarget().getCodeModel();
10951
10952   if (Subtarget->isPICStyleRIPRel() &&
10953       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10954     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10955       OpFlag = X86II::MO_GOTPCREL;
10956     WrapperKind = X86ISD::WrapperRIP;
10957   } else if (Subtarget->isPICStyleGOT()) {
10958     OpFlag = X86II::MO_GOT;
10959   } else if (Subtarget->isPICStyleStubPIC()) {
10960     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10961   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10962     OpFlag = X86II::MO_DARWIN_NONLAZY;
10963   }
10964
10965   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10966
10967   SDLoc DL(Op);
10968   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10969
10970   // With PIC, the address is actually $g + Offset.
10971   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10972       !Subtarget->is64Bit()) {
10973     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10974                          DAG.getNode(X86ISD::GlobalBaseReg,
10975                                      SDLoc(), getPointerTy()),
10976                          Result);
10977   }
10978
10979   // For symbols that require a load from a stub to get the address, emit the
10980   // load.
10981   if (isGlobalStubReference(OpFlag))
10982     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10983                          MachinePointerInfo::getGOT(), false, false, false, 0);
10984
10985   return Result;
10986 }
10987
10988 SDValue
10989 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10990   // Create the TargetBlockAddressAddress node.
10991   unsigned char OpFlags =
10992     Subtarget->ClassifyBlockAddressReference();
10993   CodeModel::Model M = DAG.getTarget().getCodeModel();
10994   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10995   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10996   SDLoc dl(Op);
10997   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10998                                              OpFlags);
10999
11000   if (Subtarget->isPICStyleRIPRel() &&
11001       (M == CodeModel::Small || M == CodeModel::Kernel))
11002     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11003   else
11004     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11005
11006   // With PIC, the address is actually $g + Offset.
11007   if (isGlobalRelativeToPICBase(OpFlags)) {
11008     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11009                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11010                          Result);
11011   }
11012
11013   return Result;
11014 }
11015
11016 SDValue
11017 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11018                                       int64_t Offset, SelectionDAG &DAG) const {
11019   // Create the TargetGlobalAddress node, folding in the constant
11020   // offset if it is legal.
11021   unsigned char OpFlags =
11022       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11023   CodeModel::Model M = DAG.getTarget().getCodeModel();
11024   SDValue Result;
11025   if (OpFlags == X86II::MO_NO_FLAG &&
11026       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11027     // A direct static reference to a global.
11028     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11029     Offset = 0;
11030   } else {
11031     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11032   }
11033
11034   if (Subtarget->isPICStyleRIPRel() &&
11035       (M == CodeModel::Small || M == CodeModel::Kernel))
11036     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11037   else
11038     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11039
11040   // With PIC, the address is actually $g + Offset.
11041   if (isGlobalRelativeToPICBase(OpFlags)) {
11042     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11043                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11044                          Result);
11045   }
11046
11047   // For globals that require a load from a stub to get the address, emit the
11048   // load.
11049   if (isGlobalStubReference(OpFlags))
11050     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11051                          MachinePointerInfo::getGOT(), false, false, false, 0);
11052
11053   // If there was a non-zero offset that we didn't fold, create an explicit
11054   // addition for it.
11055   if (Offset != 0)
11056     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11057                          DAG.getConstant(Offset, getPointerTy()));
11058
11059   return Result;
11060 }
11061
11062 SDValue
11063 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11064   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11065   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11066   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11067 }
11068
11069 static SDValue
11070 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11071            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11072            unsigned char OperandFlags, bool LocalDynamic = false) {
11073   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11074   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11075   SDLoc dl(GA);
11076   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11077                                            GA->getValueType(0),
11078                                            GA->getOffset(),
11079                                            OperandFlags);
11080
11081   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11082                                            : X86ISD::TLSADDR;
11083
11084   if (InFlag) {
11085     SDValue Ops[] = { Chain,  TGA, *InFlag };
11086     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11087   } else {
11088     SDValue Ops[]  = { Chain, TGA };
11089     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11090   }
11091
11092   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11093   MFI->setAdjustsStack(true);
11094   MFI->setHasCalls(true);
11095
11096   SDValue Flag = Chain.getValue(1);
11097   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11098 }
11099
11100 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11101 static SDValue
11102 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11103                                 const EVT PtrVT) {
11104   SDValue InFlag;
11105   SDLoc dl(GA);  // ? function entry point might be better
11106   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11107                                    DAG.getNode(X86ISD::GlobalBaseReg,
11108                                                SDLoc(), PtrVT), InFlag);
11109   InFlag = Chain.getValue(1);
11110
11111   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11112 }
11113
11114 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11115 static SDValue
11116 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11117                                 const EVT PtrVT) {
11118   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11119                     X86::RAX, X86II::MO_TLSGD);
11120 }
11121
11122 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11123                                            SelectionDAG &DAG,
11124                                            const EVT PtrVT,
11125                                            bool is64Bit) {
11126   SDLoc dl(GA);
11127
11128   // Get the start address of the TLS block for this module.
11129   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11130       .getInfo<X86MachineFunctionInfo>();
11131   MFI->incNumLocalDynamicTLSAccesses();
11132
11133   SDValue Base;
11134   if (is64Bit) {
11135     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11136                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11137   } else {
11138     SDValue InFlag;
11139     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11140         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11141     InFlag = Chain.getValue(1);
11142     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11143                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11144   }
11145
11146   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11147   // of Base.
11148
11149   // Build x@dtpoff.
11150   unsigned char OperandFlags = X86II::MO_DTPOFF;
11151   unsigned WrapperKind = X86ISD::Wrapper;
11152   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11153                                            GA->getValueType(0),
11154                                            GA->getOffset(), OperandFlags);
11155   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11156
11157   // Add x@dtpoff with the base.
11158   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11159 }
11160
11161 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11162 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11163                                    const EVT PtrVT, TLSModel::Model model,
11164                                    bool is64Bit, bool isPIC) {
11165   SDLoc dl(GA);
11166
11167   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11168   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11169                                                          is64Bit ? 257 : 256));
11170
11171   SDValue ThreadPointer =
11172       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11173                   MachinePointerInfo(Ptr), false, false, false, 0);
11174
11175   unsigned char OperandFlags = 0;
11176   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11177   // initialexec.
11178   unsigned WrapperKind = X86ISD::Wrapper;
11179   if (model == TLSModel::LocalExec) {
11180     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11181   } else if (model == TLSModel::InitialExec) {
11182     if (is64Bit) {
11183       OperandFlags = X86II::MO_GOTTPOFF;
11184       WrapperKind = X86ISD::WrapperRIP;
11185     } else {
11186       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11187     }
11188   } else {
11189     llvm_unreachable("Unexpected model");
11190   }
11191
11192   // emit "addl x@ntpoff,%eax" (local exec)
11193   // or "addl x@indntpoff,%eax" (initial exec)
11194   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11195   SDValue TGA =
11196       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11197                                  GA->getOffset(), OperandFlags);
11198   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11199
11200   if (model == TLSModel::InitialExec) {
11201     if (isPIC && !is64Bit) {
11202       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11203                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11204                            Offset);
11205     }
11206
11207     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11208                          MachinePointerInfo::getGOT(), false, false, false, 0);
11209   }
11210
11211   // The address of the thread local variable is the add of the thread
11212   // pointer with the offset of the variable.
11213   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11214 }
11215
11216 SDValue
11217 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11218
11219   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11220   const GlobalValue *GV = GA->getGlobal();
11221
11222   if (Subtarget->isTargetELF()) {
11223     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11224
11225     switch (model) {
11226       case TLSModel::GeneralDynamic:
11227         if (Subtarget->is64Bit())
11228           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11229         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11230       case TLSModel::LocalDynamic:
11231         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11232                                            Subtarget->is64Bit());
11233       case TLSModel::InitialExec:
11234       case TLSModel::LocalExec:
11235         return LowerToTLSExecModel(
11236             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11237             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11238     }
11239     llvm_unreachable("Unknown TLS model.");
11240   }
11241
11242   if (Subtarget->isTargetDarwin()) {
11243     // Darwin only has one model of TLS.  Lower to that.
11244     unsigned char OpFlag = 0;
11245     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11246                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11247
11248     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11249     // global base reg.
11250     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11251                  !Subtarget->is64Bit();
11252     if (PIC32)
11253       OpFlag = X86II::MO_TLVP_PIC_BASE;
11254     else
11255       OpFlag = X86II::MO_TLVP;
11256     SDLoc DL(Op);
11257     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11258                                                 GA->getValueType(0),
11259                                                 GA->getOffset(), OpFlag);
11260     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11261
11262     // With PIC32, the address is actually $g + Offset.
11263     if (PIC32)
11264       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11265                            DAG.getNode(X86ISD::GlobalBaseReg,
11266                                        SDLoc(), getPointerTy()),
11267                            Offset);
11268
11269     // Lowering the machine isd will make sure everything is in the right
11270     // location.
11271     SDValue Chain = DAG.getEntryNode();
11272     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11273     SDValue Args[] = { Chain, Offset };
11274     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11275
11276     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11277     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11278     MFI->setAdjustsStack(true);
11279
11280     // And our return value (tls address) is in the standard call return value
11281     // location.
11282     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11283     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11284                               Chain.getValue(1));
11285   }
11286
11287   if (Subtarget->isTargetKnownWindowsMSVC() ||
11288       Subtarget->isTargetWindowsGNU()) {
11289     // Just use the implicit TLS architecture
11290     // Need to generate someting similar to:
11291     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11292     //                                  ; from TEB
11293     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11294     //   mov     rcx, qword [rdx+rcx*8]
11295     //   mov     eax, .tls$:tlsvar
11296     //   [rax+rcx] contains the address
11297     // Windows 64bit: gs:0x58
11298     // Windows 32bit: fs:__tls_array
11299
11300     SDLoc dl(GA);
11301     SDValue Chain = DAG.getEntryNode();
11302
11303     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11304     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11305     // use its literal value of 0x2C.
11306     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11307                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11308                                                              256)
11309                                         : Type::getInt32PtrTy(*DAG.getContext(),
11310                                                               257));
11311
11312     SDValue TlsArray =
11313         Subtarget->is64Bit()
11314             ? DAG.getIntPtrConstant(0x58)
11315             : (Subtarget->isTargetWindowsGNU()
11316                    ? DAG.getIntPtrConstant(0x2C)
11317                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11318
11319     SDValue ThreadPointer =
11320         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11321                     MachinePointerInfo(Ptr), false, false, false, 0);
11322
11323     // Load the _tls_index variable
11324     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11325     if (Subtarget->is64Bit())
11326       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11327                            IDX, MachinePointerInfo(), MVT::i32,
11328                            false, false, false, 0);
11329     else
11330       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11331                         false, false, false, 0);
11332
11333     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11334                                     getPointerTy());
11335     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11336
11337     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11338     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11339                       false, false, false, 0);
11340
11341     // Get the offset of start of .tls section
11342     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11343                                              GA->getValueType(0),
11344                                              GA->getOffset(), X86II::MO_SECREL);
11345     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11346
11347     // The address of the thread local variable is the add of the thread
11348     // pointer with the offset of the variable.
11349     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11350   }
11351
11352   llvm_unreachable("TLS not implemented for this target.");
11353 }
11354
11355 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11356 /// and take a 2 x i32 value to shift plus a shift amount.
11357 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11358   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11359   MVT VT = Op.getSimpleValueType();
11360   unsigned VTBits = VT.getSizeInBits();
11361   SDLoc dl(Op);
11362   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11363   SDValue ShOpLo = Op.getOperand(0);
11364   SDValue ShOpHi = Op.getOperand(1);
11365   SDValue ShAmt  = Op.getOperand(2);
11366   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11367   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11368   // during isel.
11369   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11370                                   DAG.getConstant(VTBits - 1, MVT::i8));
11371   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11372                                      DAG.getConstant(VTBits - 1, MVT::i8))
11373                        : DAG.getConstant(0, VT);
11374
11375   SDValue Tmp2, Tmp3;
11376   if (Op.getOpcode() == ISD::SHL_PARTS) {
11377     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11378     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11379   } else {
11380     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11381     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11382   }
11383
11384   // If the shift amount is larger or equal than the width of a part we can't
11385   // rely on the results of shld/shrd. Insert a test and select the appropriate
11386   // values for large shift amounts.
11387   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11388                                 DAG.getConstant(VTBits, MVT::i8));
11389   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11390                              AndNode, DAG.getConstant(0, MVT::i8));
11391
11392   SDValue Hi, Lo;
11393   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11394   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11395   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11396
11397   if (Op.getOpcode() == ISD::SHL_PARTS) {
11398     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11399     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11400   } else {
11401     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11402     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11403   }
11404
11405   SDValue Ops[2] = { Lo, Hi };
11406   return DAG.getMergeValues(Ops, dl);
11407 }
11408
11409 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11410                                            SelectionDAG &DAG) const {
11411   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11412   SDLoc dl(Op);
11413
11414   if (SrcVT.isVector()) {
11415     if (SrcVT.getVectorElementType() == MVT::i1) {
11416       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11417       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11418                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11419                                      Op.getOperand(0)));
11420     }
11421     return SDValue();
11422   }
11423
11424   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11425          "Unknown SINT_TO_FP to lower!");
11426
11427   // These are really Legal; return the operand so the caller accepts it as
11428   // Legal.
11429   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11430     return Op;
11431   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11432       Subtarget->is64Bit()) {
11433     return Op;
11434   }
11435
11436   unsigned Size = SrcVT.getSizeInBits()/8;
11437   MachineFunction &MF = DAG.getMachineFunction();
11438   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11439   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11440   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11441                                StackSlot,
11442                                MachinePointerInfo::getFixedStack(SSFI),
11443                                false, false, 0);
11444   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11445 }
11446
11447 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11448                                      SDValue StackSlot,
11449                                      SelectionDAG &DAG) const {
11450   // Build the FILD
11451   SDLoc DL(Op);
11452   SDVTList Tys;
11453   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11454   if (useSSE)
11455     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11456   else
11457     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11458
11459   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11460
11461   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11462   MachineMemOperand *MMO;
11463   if (FI) {
11464     int SSFI = FI->getIndex();
11465     MMO =
11466       DAG.getMachineFunction()
11467       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11468                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11469   } else {
11470     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11471     StackSlot = StackSlot.getOperand(1);
11472   }
11473   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11474   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11475                                            X86ISD::FILD, DL,
11476                                            Tys, Ops, SrcVT, MMO);
11477
11478   if (useSSE) {
11479     Chain = Result.getValue(1);
11480     SDValue InFlag = Result.getValue(2);
11481
11482     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11483     // shouldn't be necessary except that RFP cannot be live across
11484     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11485     MachineFunction &MF = DAG.getMachineFunction();
11486     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11487     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11488     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11489     Tys = DAG.getVTList(MVT::Other);
11490     SDValue Ops[] = {
11491       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11492     };
11493     MachineMemOperand *MMO =
11494       DAG.getMachineFunction()
11495       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11496                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11497
11498     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11499                                     Ops, Op.getValueType(), MMO);
11500     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11501                          MachinePointerInfo::getFixedStack(SSFI),
11502                          false, false, false, 0);
11503   }
11504
11505   return Result;
11506 }
11507
11508 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11509 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11510                                                SelectionDAG &DAG) const {
11511   // This algorithm is not obvious. Here it is what we're trying to output:
11512   /*
11513      movq       %rax,  %xmm0
11514      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11515      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11516      #ifdef __SSE3__
11517        haddpd   %xmm0, %xmm0
11518      #else
11519        pshufd   $0x4e, %xmm0, %xmm1
11520        addpd    %xmm1, %xmm0
11521      #endif
11522   */
11523
11524   SDLoc dl(Op);
11525   LLVMContext *Context = DAG.getContext();
11526
11527   // Build some magic constants.
11528   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11529   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11530   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11531
11532   SmallVector<Constant*,2> CV1;
11533   CV1.push_back(
11534     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11535                                       APInt(64, 0x4330000000000000ULL))));
11536   CV1.push_back(
11537     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11538                                       APInt(64, 0x4530000000000000ULL))));
11539   Constant *C1 = ConstantVector::get(CV1);
11540   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11541
11542   // Load the 64-bit value into an XMM register.
11543   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11544                             Op.getOperand(0));
11545   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11546                               MachinePointerInfo::getConstantPool(),
11547                               false, false, false, 16);
11548   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11549                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11550                               CLod0);
11551
11552   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11553                               MachinePointerInfo::getConstantPool(),
11554                               false, false, false, 16);
11555   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11556   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11557   SDValue Result;
11558
11559   if (Subtarget->hasSSE3()) {
11560     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11561     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11562   } else {
11563     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11564     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11565                                            S2F, 0x4E, DAG);
11566     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11567                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11568                          Sub);
11569   }
11570
11571   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11572                      DAG.getIntPtrConstant(0));
11573 }
11574
11575 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11576 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11577                                                SelectionDAG &DAG) const {
11578   SDLoc dl(Op);
11579   // FP constant to bias correct the final result.
11580   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11581                                    MVT::f64);
11582
11583   // Load the 32-bit value into an XMM register.
11584   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11585                              Op.getOperand(0));
11586
11587   // Zero out the upper parts of the register.
11588   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11589
11590   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11591                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11592                      DAG.getIntPtrConstant(0));
11593
11594   // Or the load with the bias.
11595   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11596                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11597                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11598                                                    MVT::v2f64, Load)),
11599                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11600                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11601                                                    MVT::v2f64, Bias)));
11602   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11603                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11604                    DAG.getIntPtrConstant(0));
11605
11606   // Subtract the bias.
11607   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11608
11609   // Handle final rounding.
11610   EVT DestVT = Op.getValueType();
11611
11612   if (DestVT.bitsLT(MVT::f64))
11613     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11614                        DAG.getIntPtrConstant(0));
11615   if (DestVT.bitsGT(MVT::f64))
11616     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11617
11618   // Handle final rounding.
11619   return Sub;
11620 }
11621
11622 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11623                                      const X86Subtarget &Subtarget) {
11624   // The algorithm is the following:
11625   // #ifdef __SSE4_1__
11626   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11627   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11628   //                                 (uint4) 0x53000000, 0xaa);
11629   // #else
11630   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11631   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11632   // #endif
11633   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11634   //     return (float4) lo + fhi;
11635
11636   SDLoc DL(Op);
11637   SDValue V = Op->getOperand(0);
11638   EVT VecIntVT = V.getValueType();
11639   bool Is128 = VecIntVT == MVT::v4i32;
11640   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11641   // If we convert to something else than the supported type, e.g., to v4f64,
11642   // abort early.
11643   if (VecFloatVT != Op->getValueType(0))
11644     return SDValue();
11645
11646   unsigned NumElts = VecIntVT.getVectorNumElements();
11647   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11648          "Unsupported custom type");
11649   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11650
11651   // In the #idef/#else code, we have in common:
11652   // - The vector of constants:
11653   // -- 0x4b000000
11654   // -- 0x53000000
11655   // - A shift:
11656   // -- v >> 16
11657
11658   // Create the splat vector for 0x4b000000.
11659   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
11660   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11661                            CstLow, CstLow, CstLow, CstLow};
11662   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11663                                   makeArrayRef(&CstLowArray[0], NumElts));
11664   // Create the splat vector for 0x53000000.
11665   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
11666   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11667                             CstHigh, CstHigh, CstHigh, CstHigh};
11668   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11669                                    makeArrayRef(&CstHighArray[0], NumElts));
11670
11671   // Create the right shift.
11672   SDValue CstShift = DAG.getConstant(16, MVT::i32);
11673   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11674                              CstShift, CstShift, CstShift, CstShift};
11675   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11676                                     makeArrayRef(&CstShiftArray[0], NumElts));
11677   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11678
11679   SDValue Low, High;
11680   if (Subtarget.hasSSE41()) {
11681     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11682     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11683     SDValue VecCstLowBitcast =
11684         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11685     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11686     // Low will be bitcasted right away, so do not bother bitcasting back to its
11687     // original type.
11688     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11689                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
11690     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11691     //                                 (uint4) 0x53000000, 0xaa);
11692     SDValue VecCstHighBitcast =
11693         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11694     SDValue VecShiftBitcast =
11695         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11696     // High will be bitcasted right away, so do not bother bitcasting back to
11697     // its original type.
11698     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11699                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
11700   } else {
11701     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
11702     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11703                                      CstMask, CstMask, CstMask);
11704     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11705     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11706     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11707
11708     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11709     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11710   }
11711
11712   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11713   SDValue CstFAdd = DAG.getConstantFP(
11714       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
11715   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11716                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11717   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11718                                    makeArrayRef(&CstFAddArray[0], NumElts));
11719
11720   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11721   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11722   SDValue FHigh =
11723       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11724   //     return (float4) lo + fhi;
11725   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11726   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11727 }
11728
11729 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11730                                                SelectionDAG &DAG) const {
11731   SDValue N0 = Op.getOperand(0);
11732   MVT SVT = N0.getSimpleValueType();
11733   SDLoc dl(Op);
11734
11735   switch (SVT.SimpleTy) {
11736   default:
11737     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11738   case MVT::v4i8:
11739   case MVT::v4i16:
11740   case MVT::v8i8:
11741   case MVT::v8i16: {
11742     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11743     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11744                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11745   }
11746   case MVT::v4i32:
11747   case MVT::v8i32:
11748     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11749   }
11750   llvm_unreachable(nullptr);
11751 }
11752
11753 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11754                                            SelectionDAG &DAG) const {
11755   SDValue N0 = Op.getOperand(0);
11756   SDLoc dl(Op);
11757
11758   if (Op.getValueType().isVector())
11759     return lowerUINT_TO_FP_vec(Op, DAG);
11760
11761   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11762   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11763   // the optimization here.
11764   if (DAG.SignBitIsZero(N0))
11765     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11766
11767   MVT SrcVT = N0.getSimpleValueType();
11768   MVT DstVT = Op.getSimpleValueType();
11769   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11770     return LowerUINT_TO_FP_i64(Op, DAG);
11771   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11772     return LowerUINT_TO_FP_i32(Op, DAG);
11773   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11774     return SDValue();
11775
11776   // Make a 64-bit buffer, and use it to build an FILD.
11777   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11778   if (SrcVT == MVT::i32) {
11779     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11780     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11781                                      getPointerTy(), StackSlot, WordOff);
11782     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11783                                   StackSlot, MachinePointerInfo(),
11784                                   false, false, 0);
11785     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11786                                   OffsetSlot, MachinePointerInfo(),
11787                                   false, false, 0);
11788     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11789     return Fild;
11790   }
11791
11792   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11793   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11794                                StackSlot, MachinePointerInfo(),
11795                                false, false, 0);
11796   // For i64 source, we need to add the appropriate power of 2 if the input
11797   // was negative.  This is the same as the optimization in
11798   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11799   // we must be careful to do the computation in x87 extended precision, not
11800   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11801   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11802   MachineMemOperand *MMO =
11803     DAG.getMachineFunction()
11804     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11805                           MachineMemOperand::MOLoad, 8, 8);
11806
11807   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11808   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11809   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11810                                          MVT::i64, MMO);
11811
11812   APInt FF(32, 0x5F800000ULL);
11813
11814   // Check whether the sign bit is set.
11815   SDValue SignSet = DAG.getSetCC(dl,
11816                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11817                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11818                                  ISD::SETLT);
11819
11820   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11821   SDValue FudgePtr = DAG.getConstantPool(
11822                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11823                                          getPointerTy());
11824
11825   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11826   SDValue Zero = DAG.getIntPtrConstant(0);
11827   SDValue Four = DAG.getIntPtrConstant(4);
11828   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11829                                Zero, Four);
11830   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11831
11832   // Load the value out, extending it from f32 to f80.
11833   // FIXME: Avoid the extend by constructing the right constant pool?
11834   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11835                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11836                                  MVT::f32, false, false, false, 4);
11837   // Extend everything to 80 bits to force it to be done on x87.
11838   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11839   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11840 }
11841
11842 std::pair<SDValue,SDValue>
11843 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11844                                     bool IsSigned, bool IsReplace) const {
11845   SDLoc DL(Op);
11846
11847   EVT DstTy = Op.getValueType();
11848
11849   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11850     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11851     DstTy = MVT::i64;
11852   }
11853
11854   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11855          DstTy.getSimpleVT() >= MVT::i16 &&
11856          "Unknown FP_TO_INT to lower!");
11857
11858   // These are really Legal.
11859   if (DstTy == MVT::i32 &&
11860       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11861     return std::make_pair(SDValue(), SDValue());
11862   if (Subtarget->is64Bit() &&
11863       DstTy == MVT::i64 &&
11864       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11865     return std::make_pair(SDValue(), SDValue());
11866
11867   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11868   // stack slot, or into the FTOL runtime function.
11869   MachineFunction &MF = DAG.getMachineFunction();
11870   unsigned MemSize = DstTy.getSizeInBits()/8;
11871   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11872   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11873
11874   unsigned Opc;
11875   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11876     Opc = X86ISD::WIN_FTOL;
11877   else
11878     switch (DstTy.getSimpleVT().SimpleTy) {
11879     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11880     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11881     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11882     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11883     }
11884
11885   SDValue Chain = DAG.getEntryNode();
11886   SDValue Value = Op.getOperand(0);
11887   EVT TheVT = Op.getOperand(0).getValueType();
11888   // FIXME This causes a redundant load/store if the SSE-class value is already
11889   // in memory, such as if it is on the callstack.
11890   if (isScalarFPTypeInSSEReg(TheVT)) {
11891     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11892     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11893                          MachinePointerInfo::getFixedStack(SSFI),
11894                          false, false, 0);
11895     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11896     SDValue Ops[] = {
11897       Chain, StackSlot, DAG.getValueType(TheVT)
11898     };
11899
11900     MachineMemOperand *MMO =
11901       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11902                               MachineMemOperand::MOLoad, MemSize, MemSize);
11903     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11904     Chain = Value.getValue(1);
11905     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11906     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11907   }
11908
11909   MachineMemOperand *MMO =
11910     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11911                             MachineMemOperand::MOStore, MemSize, MemSize);
11912
11913   if (Opc != X86ISD::WIN_FTOL) {
11914     // Build the FP_TO_INT*_IN_MEM
11915     SDValue Ops[] = { Chain, Value, StackSlot };
11916     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11917                                            Ops, DstTy, MMO);
11918     return std::make_pair(FIST, StackSlot);
11919   } else {
11920     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11921       DAG.getVTList(MVT::Other, MVT::Glue),
11922       Chain, Value);
11923     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11924       MVT::i32, ftol.getValue(1));
11925     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11926       MVT::i32, eax.getValue(2));
11927     SDValue Ops[] = { eax, edx };
11928     SDValue pair = IsReplace
11929       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11930       : DAG.getMergeValues(Ops, DL);
11931     return std::make_pair(pair, SDValue());
11932   }
11933 }
11934
11935 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11936                               const X86Subtarget *Subtarget) {
11937   MVT VT = Op->getSimpleValueType(0);
11938   SDValue In = Op->getOperand(0);
11939   MVT InVT = In.getSimpleValueType();
11940   SDLoc dl(Op);
11941
11942   // Optimize vectors in AVX mode:
11943   //
11944   //   v8i16 -> v8i32
11945   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11946   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11947   //   Concat upper and lower parts.
11948   //
11949   //   v4i32 -> v4i64
11950   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11951   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11952   //   Concat upper and lower parts.
11953   //
11954
11955   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11956       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11957       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11958     return SDValue();
11959
11960   if (Subtarget->hasInt256())
11961     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11962
11963   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11964   SDValue Undef = DAG.getUNDEF(InVT);
11965   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11966   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11967   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11968
11969   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11970                              VT.getVectorNumElements()/2);
11971
11972   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11973   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11974
11975   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11976 }
11977
11978 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11979                                         SelectionDAG &DAG) {
11980   MVT VT = Op->getSimpleValueType(0);
11981   SDValue In = Op->getOperand(0);
11982   MVT InVT = In.getSimpleValueType();
11983   SDLoc DL(Op);
11984   unsigned int NumElts = VT.getVectorNumElements();
11985   if (NumElts != 8 && NumElts != 16)
11986     return SDValue();
11987
11988   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11989     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11990
11991   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11992   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11993   // Now we have only mask extension
11994   assert(InVT.getVectorElementType() == MVT::i1);
11995   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11996   const Constant *C = cast<ConstantSDNode>(Cst)->getConstantIntValue();
11997   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11998   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11999   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12000                            MachinePointerInfo::getConstantPool(),
12001                            false, false, false, Alignment);
12002
12003   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
12004   if (VT.is512BitVector())
12005     return Brcst;
12006   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
12007 }
12008
12009 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12010                                SelectionDAG &DAG) {
12011   if (Subtarget->hasFp256()) {
12012     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12013     if (Res.getNode())
12014       return Res;
12015   }
12016
12017   return SDValue();
12018 }
12019
12020 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12021                                 SelectionDAG &DAG) {
12022   SDLoc DL(Op);
12023   MVT VT = Op.getSimpleValueType();
12024   SDValue In = Op.getOperand(0);
12025   MVT SVT = In.getSimpleValueType();
12026
12027   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12028     return LowerZERO_EXTEND_AVX512(Op, DAG);
12029
12030   if (Subtarget->hasFp256()) {
12031     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12032     if (Res.getNode())
12033       return Res;
12034   }
12035
12036   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12037          VT.getVectorNumElements() != SVT.getVectorNumElements());
12038   return SDValue();
12039 }
12040
12041 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12042   SDLoc DL(Op);
12043   MVT VT = Op.getSimpleValueType();
12044   SDValue In = Op.getOperand(0);
12045   MVT InVT = In.getSimpleValueType();
12046
12047   if (VT == MVT::i1) {
12048     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12049            "Invalid scalar TRUNCATE operation");
12050     if (InVT.getSizeInBits() >= 32)
12051       return SDValue();
12052     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12053     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12054   }
12055   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12056          "Invalid TRUNCATE operation");
12057
12058   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12059     if (VT.getVectorElementType().getSizeInBits() >=8)
12060       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12061
12062     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12063     unsigned NumElts = InVT.getVectorNumElements();
12064     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12065     if (InVT.getSizeInBits() < 512) {
12066       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12067       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12068       InVT = ExtVT;
12069     }
12070
12071     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
12072     const Constant *C = cast<ConstantSDNode>(Cst)->getConstantIntValue();
12073     SDValue CP = DAG.getConstantPool(C, getPointerTy());
12074     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12075     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12076                            MachinePointerInfo::getConstantPool(),
12077                            false, false, false, Alignment);
12078     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
12079     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12080     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12081   }
12082
12083   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12084     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12085     if (Subtarget->hasInt256()) {
12086       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12087       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12088       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12089                                 ShufMask);
12090       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12091                          DAG.getIntPtrConstant(0));
12092     }
12093
12094     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12095                                DAG.getIntPtrConstant(0));
12096     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12097                                DAG.getIntPtrConstant(2));
12098     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12099     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12100     static const int ShufMask[] = {0, 2, 4, 6};
12101     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12102   }
12103
12104   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12105     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12106     if (Subtarget->hasInt256()) {
12107       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12108
12109       SmallVector<SDValue,32> pshufbMask;
12110       for (unsigned i = 0; i < 2; ++i) {
12111         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
12112         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
12113         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
12114         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
12115         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
12116         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
12117         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
12118         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
12119         for (unsigned j = 0; j < 8; ++j)
12120           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
12121       }
12122       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12123       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12124       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12125
12126       static const int ShufMask[] = {0,  2,  -1,  -1};
12127       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12128                                 &ShufMask[0]);
12129       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12130                        DAG.getIntPtrConstant(0));
12131       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12132     }
12133
12134     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12135                                DAG.getIntPtrConstant(0));
12136
12137     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12138                                DAG.getIntPtrConstant(4));
12139
12140     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12141     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12142
12143     // The PSHUFB mask:
12144     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12145                                    -1, -1, -1, -1, -1, -1, -1, -1};
12146
12147     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12148     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12149     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12150
12151     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12152     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12153
12154     // The MOVLHPS Mask:
12155     static const int ShufMask2[] = {0, 1, 4, 5};
12156     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12157     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12158   }
12159
12160   // Handle truncation of V256 to V128 using shuffles.
12161   if (!VT.is128BitVector() || !InVT.is256BitVector())
12162     return SDValue();
12163
12164   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12165
12166   unsigned NumElems = VT.getVectorNumElements();
12167   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12168
12169   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12170   // Prepare truncation shuffle mask
12171   for (unsigned i = 0; i != NumElems; ++i)
12172     MaskVec[i] = i * 2;
12173   SDValue V = DAG.getVectorShuffle(NVT, DL,
12174                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12175                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12176   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12177                      DAG.getIntPtrConstant(0));
12178 }
12179
12180 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12181                                            SelectionDAG &DAG) const {
12182   assert(!Op.getSimpleValueType().isVector());
12183
12184   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12185     /*IsSigned=*/ true, /*IsReplace=*/ false);
12186   SDValue FIST = Vals.first, StackSlot = Vals.second;
12187   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12188   if (!FIST.getNode()) return Op;
12189
12190   if (StackSlot.getNode())
12191     // Load the result.
12192     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12193                        FIST, StackSlot, MachinePointerInfo(),
12194                        false, false, false, 0);
12195
12196   // The node is the result.
12197   return FIST;
12198 }
12199
12200 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12201                                            SelectionDAG &DAG) const {
12202   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12203     /*IsSigned=*/ false, /*IsReplace=*/ false);
12204   SDValue FIST = Vals.first, StackSlot = Vals.second;
12205   assert(FIST.getNode() && "Unexpected failure");
12206
12207   if (StackSlot.getNode())
12208     // Load the result.
12209     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12210                        FIST, StackSlot, MachinePointerInfo(),
12211                        false, false, false, 0);
12212
12213   // The node is the result.
12214   return FIST;
12215 }
12216
12217 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12218   SDLoc DL(Op);
12219   MVT VT = Op.getSimpleValueType();
12220   SDValue In = Op.getOperand(0);
12221   MVT SVT = In.getSimpleValueType();
12222
12223   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12224
12225   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12226                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12227                                  In, DAG.getUNDEF(SVT)));
12228 }
12229
12230 /// The only differences between FABS and FNEG are the mask and the logic op.
12231 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12232 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12233   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12234          "Wrong opcode for lowering FABS or FNEG.");
12235
12236   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12237
12238   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12239   // into an FNABS. We'll lower the FABS after that if it is still in use.
12240   if (IsFABS)
12241     for (SDNode *User : Op->uses())
12242       if (User->getOpcode() == ISD::FNEG)
12243         return Op;
12244
12245   SDValue Op0 = Op.getOperand(0);
12246   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12247
12248   SDLoc dl(Op);
12249   MVT VT = Op.getSimpleValueType();
12250   // Assume scalar op for initialization; update for vector if needed.
12251   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12252   // generate a 16-byte vector constant and logic op even for the scalar case.
12253   // Using a 16-byte mask allows folding the load of the mask with
12254   // the logic op, so it can save (~4 bytes) on code size.
12255   MVT EltVT = VT;
12256   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12257   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12258   // decide if we should generate a 16-byte constant mask when we only need 4 or
12259   // 8 bytes for the scalar case.
12260   if (VT.isVector()) {
12261     EltVT = VT.getVectorElementType();
12262     NumElts = VT.getVectorNumElements();
12263   }
12264
12265   unsigned EltBits = EltVT.getSizeInBits();
12266   LLVMContext *Context = DAG.getContext();
12267   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12268   APInt MaskElt =
12269     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12270   Constant *C = ConstantInt::get(*Context, MaskElt);
12271   C = ConstantVector::getSplat(NumElts, C);
12272   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12273   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12274   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12275   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12276                              MachinePointerInfo::getConstantPool(),
12277                              false, false, false, Alignment);
12278
12279   if (VT.isVector()) {
12280     // For a vector, cast operands to a vector type, perform the logic op,
12281     // and cast the result back to the original value type.
12282     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12283     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12284     SDValue Operand = IsFNABS ?
12285       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12286       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12287     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12288     return DAG.getNode(ISD::BITCAST, dl, VT,
12289                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12290   }
12291
12292   // If not vector, then scalar.
12293   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12294   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12295   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12296 }
12297
12298 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12299   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12300   LLVMContext *Context = DAG.getContext();
12301   SDValue Op0 = Op.getOperand(0);
12302   SDValue Op1 = Op.getOperand(1);
12303   SDLoc dl(Op);
12304   MVT VT = Op.getSimpleValueType();
12305   MVT SrcVT = Op1.getSimpleValueType();
12306
12307   // If second operand is smaller, extend it first.
12308   if (SrcVT.bitsLT(VT)) {
12309     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12310     SrcVT = VT;
12311   }
12312   // And if it is bigger, shrink it first.
12313   if (SrcVT.bitsGT(VT)) {
12314     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12315     SrcVT = VT;
12316   }
12317
12318   // At this point the operands and the result should have the same
12319   // type, and that won't be f80 since that is not custom lowered.
12320
12321   const fltSemantics &Sem =
12322       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12323   const unsigned SizeInBits = VT.getSizeInBits();
12324
12325   SmallVector<Constant *, 4> CV(
12326       VT == MVT::f64 ? 2 : 4,
12327       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12328
12329   // First, clear all bits but the sign bit from the second operand (sign).
12330   CV[0] = ConstantFP::get(*Context,
12331                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12332   Constant *C = ConstantVector::get(CV);
12333   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12334   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12335                               MachinePointerInfo::getConstantPool(),
12336                               false, false, false, 16);
12337   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12338
12339   // Next, clear the sign bit from the first operand (magnitude).
12340   // If it's a constant, we can clear it here.
12341   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12342     APFloat APF = Op0CN->getValueAPF();
12343     // If the magnitude is a positive zero, the sign bit alone is enough.
12344     if (APF.isPosZero())
12345       return SignBit;
12346     APF.clearSign();
12347     CV[0] = ConstantFP::get(*Context, APF);
12348   } else {
12349     CV[0] = ConstantFP::get(
12350         *Context,
12351         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12352   }
12353   C = ConstantVector::get(CV);
12354   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12355   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12356                             MachinePointerInfo::getConstantPool(),
12357                             false, false, false, 16);
12358   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12359   if (!isa<ConstantFPSDNode>(Op0))
12360     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12361
12362   // OR the magnitude value with the sign bit.
12363   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12364 }
12365
12366 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12367   SDValue N0 = Op.getOperand(0);
12368   SDLoc dl(Op);
12369   MVT VT = Op.getSimpleValueType();
12370
12371   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12372   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12373                                   DAG.getConstant(1, VT));
12374   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12375 }
12376
12377 // Check whether an OR'd tree is PTEST-able.
12378 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12379                                       SelectionDAG &DAG) {
12380   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12381
12382   if (!Subtarget->hasSSE41())
12383     return SDValue();
12384
12385   if (!Op->hasOneUse())
12386     return SDValue();
12387
12388   SDNode *N = Op.getNode();
12389   SDLoc DL(N);
12390
12391   SmallVector<SDValue, 8> Opnds;
12392   DenseMap<SDValue, unsigned> VecInMap;
12393   SmallVector<SDValue, 8> VecIns;
12394   EVT VT = MVT::Other;
12395
12396   // Recognize a special case where a vector is casted into wide integer to
12397   // test all 0s.
12398   Opnds.push_back(N->getOperand(0));
12399   Opnds.push_back(N->getOperand(1));
12400
12401   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12402     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12403     // BFS traverse all OR'd operands.
12404     if (I->getOpcode() == ISD::OR) {
12405       Opnds.push_back(I->getOperand(0));
12406       Opnds.push_back(I->getOperand(1));
12407       // Re-evaluate the number of nodes to be traversed.
12408       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12409       continue;
12410     }
12411
12412     // Quit if a non-EXTRACT_VECTOR_ELT
12413     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12414       return SDValue();
12415
12416     // Quit if without a constant index.
12417     SDValue Idx = I->getOperand(1);
12418     if (!isa<ConstantSDNode>(Idx))
12419       return SDValue();
12420
12421     SDValue ExtractedFromVec = I->getOperand(0);
12422     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12423     if (M == VecInMap.end()) {
12424       VT = ExtractedFromVec.getValueType();
12425       // Quit if not 128/256-bit vector.
12426       if (!VT.is128BitVector() && !VT.is256BitVector())
12427         return SDValue();
12428       // Quit if not the same type.
12429       if (VecInMap.begin() != VecInMap.end() &&
12430           VT != VecInMap.begin()->first.getValueType())
12431         return SDValue();
12432       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12433       VecIns.push_back(ExtractedFromVec);
12434     }
12435     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12436   }
12437
12438   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12439          "Not extracted from 128-/256-bit vector.");
12440
12441   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12442
12443   for (DenseMap<SDValue, unsigned>::const_iterator
12444         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12445     // Quit if not all elements are used.
12446     if (I->second != FullMask)
12447       return SDValue();
12448   }
12449
12450   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12451
12452   // Cast all vectors into TestVT for PTEST.
12453   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12454     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12455
12456   // If more than one full vectors are evaluated, OR them first before PTEST.
12457   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12458     // Each iteration will OR 2 nodes and append the result until there is only
12459     // 1 node left, i.e. the final OR'd value of all vectors.
12460     SDValue LHS = VecIns[Slot];
12461     SDValue RHS = VecIns[Slot + 1];
12462     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12463   }
12464
12465   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12466                      VecIns.back(), VecIns.back());
12467 }
12468
12469 /// \brief return true if \c Op has a use that doesn't just read flags.
12470 static bool hasNonFlagsUse(SDValue Op) {
12471   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12472        ++UI) {
12473     SDNode *User = *UI;
12474     unsigned UOpNo = UI.getOperandNo();
12475     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12476       // Look pass truncate.
12477       UOpNo = User->use_begin().getOperandNo();
12478       User = *User->use_begin();
12479     }
12480
12481     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12482         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12483       return true;
12484   }
12485   return false;
12486 }
12487
12488 /// Emit nodes that will be selected as "test Op0,Op0", or something
12489 /// equivalent.
12490 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12491                                     SelectionDAG &DAG) const {
12492   if (Op.getValueType() == MVT::i1) {
12493     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12494     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12495                        DAG.getConstant(0, MVT::i8));
12496   }
12497   // CF and OF aren't always set the way we want. Determine which
12498   // of these we need.
12499   bool NeedCF = false;
12500   bool NeedOF = false;
12501   switch (X86CC) {
12502   default: break;
12503   case X86::COND_A: case X86::COND_AE:
12504   case X86::COND_B: case X86::COND_BE:
12505     NeedCF = true;
12506     break;
12507   case X86::COND_G: case X86::COND_GE:
12508   case X86::COND_L: case X86::COND_LE:
12509   case X86::COND_O: case X86::COND_NO: {
12510     // Check if we really need to set the
12511     // Overflow flag. If NoSignedWrap is present
12512     // that is not actually needed.
12513     switch (Op->getOpcode()) {
12514     case ISD::ADD:
12515     case ISD::SUB:
12516     case ISD::MUL:
12517     case ISD::SHL: {
12518       const BinaryWithFlagsSDNode *BinNode =
12519           cast<BinaryWithFlagsSDNode>(Op.getNode());
12520       if (BinNode->hasNoSignedWrap())
12521         break;
12522     }
12523     default:
12524       NeedOF = true;
12525       break;
12526     }
12527     break;
12528   }
12529   }
12530   // See if we can use the EFLAGS value from the operand instead of
12531   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12532   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12533   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12534     // Emit a CMP with 0, which is the TEST pattern.
12535     //if (Op.getValueType() == MVT::i1)
12536     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12537     //                     DAG.getConstant(0, MVT::i1));
12538     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12539                        DAG.getConstant(0, Op.getValueType()));
12540   }
12541   unsigned Opcode = 0;
12542   unsigned NumOperands = 0;
12543
12544   // Truncate operations may prevent the merge of the SETCC instruction
12545   // and the arithmetic instruction before it. Attempt to truncate the operands
12546   // of the arithmetic instruction and use a reduced bit-width instruction.
12547   bool NeedTruncation = false;
12548   SDValue ArithOp = Op;
12549   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12550     SDValue Arith = Op->getOperand(0);
12551     // Both the trunc and the arithmetic op need to have one user each.
12552     if (Arith->hasOneUse())
12553       switch (Arith.getOpcode()) {
12554         default: break;
12555         case ISD::ADD:
12556         case ISD::SUB:
12557         case ISD::AND:
12558         case ISD::OR:
12559         case ISD::XOR: {
12560           NeedTruncation = true;
12561           ArithOp = Arith;
12562         }
12563       }
12564   }
12565
12566   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12567   // which may be the result of a CAST.  We use the variable 'Op', which is the
12568   // non-casted variable when we check for possible users.
12569   switch (ArithOp.getOpcode()) {
12570   case ISD::ADD:
12571     // Due to an isel shortcoming, be conservative if this add is likely to be
12572     // selected as part of a load-modify-store instruction. When the root node
12573     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12574     // uses of other nodes in the match, such as the ADD in this case. This
12575     // leads to the ADD being left around and reselected, with the result being
12576     // two adds in the output.  Alas, even if none our users are stores, that
12577     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12578     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12579     // climbing the DAG back to the root, and it doesn't seem to be worth the
12580     // effort.
12581     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12582          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12583       if (UI->getOpcode() != ISD::CopyToReg &&
12584           UI->getOpcode() != ISD::SETCC &&
12585           UI->getOpcode() != ISD::STORE)
12586         goto default_case;
12587
12588     if (ConstantSDNode *C =
12589         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12590       // An add of one will be selected as an INC.
12591       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12592         Opcode = X86ISD::INC;
12593         NumOperands = 1;
12594         break;
12595       }
12596
12597       // An add of negative one (subtract of one) will be selected as a DEC.
12598       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12599         Opcode = X86ISD::DEC;
12600         NumOperands = 1;
12601         break;
12602       }
12603     }
12604
12605     // Otherwise use a regular EFLAGS-setting add.
12606     Opcode = X86ISD::ADD;
12607     NumOperands = 2;
12608     break;
12609   case ISD::SHL:
12610   case ISD::SRL:
12611     // If we have a constant logical shift that's only used in a comparison
12612     // against zero turn it into an equivalent AND. This allows turning it into
12613     // a TEST instruction later.
12614     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12615         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12616       EVT VT = Op.getValueType();
12617       unsigned BitWidth = VT.getSizeInBits();
12618       unsigned ShAmt = Op->getConstantOperandVal(1);
12619       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12620         break;
12621       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12622                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12623                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12624       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12625         break;
12626       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12627                                 DAG.getConstant(Mask, VT));
12628       DAG.ReplaceAllUsesWith(Op, New);
12629       Op = New;
12630     }
12631     break;
12632
12633   case ISD::AND:
12634     // If the primary and result isn't used, don't bother using X86ISD::AND,
12635     // because a TEST instruction will be better.
12636     if (!hasNonFlagsUse(Op))
12637       break;
12638     // FALL THROUGH
12639   case ISD::SUB:
12640   case ISD::OR:
12641   case ISD::XOR:
12642     // Due to the ISEL shortcoming noted above, be conservative if this op is
12643     // likely to be selected as part of a load-modify-store instruction.
12644     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12645            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12646       if (UI->getOpcode() == ISD::STORE)
12647         goto default_case;
12648
12649     // Otherwise use a regular EFLAGS-setting instruction.
12650     switch (ArithOp.getOpcode()) {
12651     default: llvm_unreachable("unexpected operator!");
12652     case ISD::SUB: Opcode = X86ISD::SUB; break;
12653     case ISD::XOR: Opcode = X86ISD::XOR; break;
12654     case ISD::AND: Opcode = X86ISD::AND; break;
12655     case ISD::OR: {
12656       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12657         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12658         if (EFLAGS.getNode())
12659           return EFLAGS;
12660       }
12661       Opcode = X86ISD::OR;
12662       break;
12663     }
12664     }
12665
12666     NumOperands = 2;
12667     break;
12668   case X86ISD::ADD:
12669   case X86ISD::SUB:
12670   case X86ISD::INC:
12671   case X86ISD::DEC:
12672   case X86ISD::OR:
12673   case X86ISD::XOR:
12674   case X86ISD::AND:
12675     return SDValue(Op.getNode(), 1);
12676   default:
12677   default_case:
12678     break;
12679   }
12680
12681   // If we found that truncation is beneficial, perform the truncation and
12682   // update 'Op'.
12683   if (NeedTruncation) {
12684     EVT VT = Op.getValueType();
12685     SDValue WideVal = Op->getOperand(0);
12686     EVT WideVT = WideVal.getValueType();
12687     unsigned ConvertedOp = 0;
12688     // Use a target machine opcode to prevent further DAGCombine
12689     // optimizations that may separate the arithmetic operations
12690     // from the setcc node.
12691     switch (WideVal.getOpcode()) {
12692       default: break;
12693       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12694       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12695       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12696       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12697       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12698     }
12699
12700     if (ConvertedOp) {
12701       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12702       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12703         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12704         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12705         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12706       }
12707     }
12708   }
12709
12710   if (Opcode == 0)
12711     // Emit a CMP with 0, which is the TEST pattern.
12712     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12713                        DAG.getConstant(0, Op.getValueType()));
12714
12715   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12716   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12717
12718   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12719   DAG.ReplaceAllUsesWith(Op, New);
12720   return SDValue(New.getNode(), 1);
12721 }
12722
12723 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12724 /// equivalent.
12725 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12726                                    SDLoc dl, SelectionDAG &DAG) const {
12727   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12728     if (C->getAPIntValue() == 0)
12729       return EmitTest(Op0, X86CC, dl, DAG);
12730
12731      if (Op0.getValueType() == MVT::i1)
12732        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12733   }
12734
12735   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12736        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12737     // Do the comparison at i32 if it's smaller, besides the Atom case.
12738     // This avoids subregister aliasing issues. Keep the smaller reference
12739     // if we're optimizing for size, however, as that'll allow better folding
12740     // of memory operations.
12741     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12742         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12743             Attribute::MinSize) &&
12744         !Subtarget->isAtom()) {
12745       unsigned ExtendOp =
12746           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12747       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12748       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12749     }
12750     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12751     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12752     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12753                               Op0, Op1);
12754     return SDValue(Sub.getNode(), 1);
12755   }
12756   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12757 }
12758
12759 /// Convert a comparison if required by the subtarget.
12760 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12761                                                  SelectionDAG &DAG) const {
12762   // If the subtarget does not support the FUCOMI instruction, floating-point
12763   // comparisons have to be converted.
12764   if (Subtarget->hasCMov() ||
12765       Cmp.getOpcode() != X86ISD::CMP ||
12766       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12767       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12768     return Cmp;
12769
12770   // The instruction selector will select an FUCOM instruction instead of
12771   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12772   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12773   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12774   SDLoc dl(Cmp);
12775   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12776   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12777   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12778                             DAG.getConstant(8, MVT::i8));
12779   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12780   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12781 }
12782
12783 /// The minimum architected relative accuracy is 2^-12. We need one
12784 /// Newton-Raphson step to have a good float result (24 bits of precision).
12785 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12786                                             DAGCombinerInfo &DCI,
12787                                             unsigned &RefinementSteps,
12788                                             bool &UseOneConstNR) const {
12789   // FIXME: We should use instruction latency models to calculate the cost of
12790   // each potential sequence, but this is very hard to do reliably because
12791   // at least Intel's Core* chips have variable timing based on the number of
12792   // significant digits in the divisor and/or sqrt operand.
12793   if (!Subtarget->useSqrtEst())
12794     return SDValue();
12795
12796   EVT VT = Op.getValueType();
12797
12798   // SSE1 has rsqrtss and rsqrtps.
12799   // TODO: Add support for AVX512 (v16f32).
12800   // It is likely not profitable to do this for f64 because a double-precision
12801   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12802   // instructions: convert to single, rsqrtss, convert back to double, refine
12803   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12804   // along with FMA, this could be a throughput win.
12805   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12806       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12807     RefinementSteps = 1;
12808     UseOneConstNR = false;
12809     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12810   }
12811   return SDValue();
12812 }
12813
12814 /// The minimum architected relative accuracy is 2^-12. We need one
12815 /// Newton-Raphson step to have a good float result (24 bits of precision).
12816 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12817                                             DAGCombinerInfo &DCI,
12818                                             unsigned &RefinementSteps) const {
12819   // FIXME: We should use instruction latency models to calculate the cost of
12820   // each potential sequence, but this is very hard to do reliably because
12821   // at least Intel's Core* chips have variable timing based on the number of
12822   // significant digits in the divisor.
12823   if (!Subtarget->useReciprocalEst())
12824     return SDValue();
12825
12826   EVT VT = Op.getValueType();
12827
12828   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12829   // TODO: Add support for AVX512 (v16f32).
12830   // It is likely not profitable to do this for f64 because a double-precision
12831   // reciprocal estimate with refinement on x86 prior to FMA requires
12832   // 15 instructions: convert to single, rcpss, convert back to double, refine
12833   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12834   // along with FMA, this could be a throughput win.
12835   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12836       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12837     RefinementSteps = ReciprocalEstimateRefinementSteps;
12838     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12839   }
12840   return SDValue();
12841 }
12842
12843 /// If we have at least two divisions that use the same divisor, convert to
12844 /// multplication by a reciprocal. This may need to be adjusted for a given
12845 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12846 /// This is because we still need one division to calculate the reciprocal and
12847 /// then we need two multiplies by that reciprocal as replacements for the
12848 /// original divisions.
12849 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12850   return NumUsers > 1;
12851 }
12852
12853 static bool isAllOnes(SDValue V) {
12854   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12855   return C && C->isAllOnesValue();
12856 }
12857
12858 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12859 /// if it's possible.
12860 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12861                                      SDLoc dl, SelectionDAG &DAG) const {
12862   SDValue Op0 = And.getOperand(0);
12863   SDValue Op1 = And.getOperand(1);
12864   if (Op0.getOpcode() == ISD::TRUNCATE)
12865     Op0 = Op0.getOperand(0);
12866   if (Op1.getOpcode() == ISD::TRUNCATE)
12867     Op1 = Op1.getOperand(0);
12868
12869   SDValue LHS, RHS;
12870   if (Op1.getOpcode() == ISD::SHL)
12871     std::swap(Op0, Op1);
12872   if (Op0.getOpcode() == ISD::SHL) {
12873     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12874       if (And00C->getZExtValue() == 1) {
12875         // If we looked past a truncate, check that it's only truncating away
12876         // known zeros.
12877         unsigned BitWidth = Op0.getValueSizeInBits();
12878         unsigned AndBitWidth = And.getValueSizeInBits();
12879         if (BitWidth > AndBitWidth) {
12880           APInt Zeros, Ones;
12881           DAG.computeKnownBits(Op0, Zeros, Ones);
12882           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12883             return SDValue();
12884         }
12885         LHS = Op1;
12886         RHS = Op0.getOperand(1);
12887       }
12888   } else if (Op1.getOpcode() == ISD::Constant) {
12889     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12890     uint64_t AndRHSVal = AndRHS->getZExtValue();
12891     SDValue AndLHS = Op0;
12892
12893     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12894       LHS = AndLHS.getOperand(0);
12895       RHS = AndLHS.getOperand(1);
12896     }
12897
12898     // Use BT if the immediate can't be encoded in a TEST instruction.
12899     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12900       LHS = AndLHS;
12901       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12902     }
12903   }
12904
12905   if (LHS.getNode()) {
12906     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12907     // instruction.  Since the shift amount is in-range-or-undefined, we know
12908     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12909     // the encoding for the i16 version is larger than the i32 version.
12910     // Also promote i16 to i32 for performance / code size reason.
12911     if (LHS.getValueType() == MVT::i8 ||
12912         LHS.getValueType() == MVT::i16)
12913       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12914
12915     // If the operand types disagree, extend the shift amount to match.  Since
12916     // BT ignores high bits (like shifts) we can use anyextend.
12917     if (LHS.getValueType() != RHS.getValueType())
12918       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12919
12920     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12921     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12922     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12923                        DAG.getConstant(Cond, MVT::i8), BT);
12924   }
12925
12926   return SDValue();
12927 }
12928
12929 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12930 /// mask CMPs.
12931 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12932                               SDValue &Op1) {
12933   unsigned SSECC;
12934   bool Swap = false;
12935
12936   // SSE Condition code mapping:
12937   //  0 - EQ
12938   //  1 - LT
12939   //  2 - LE
12940   //  3 - UNORD
12941   //  4 - NEQ
12942   //  5 - NLT
12943   //  6 - NLE
12944   //  7 - ORD
12945   switch (SetCCOpcode) {
12946   default: llvm_unreachable("Unexpected SETCC condition");
12947   case ISD::SETOEQ:
12948   case ISD::SETEQ:  SSECC = 0; break;
12949   case ISD::SETOGT:
12950   case ISD::SETGT:  Swap = true; // Fallthrough
12951   case ISD::SETLT:
12952   case ISD::SETOLT: SSECC = 1; break;
12953   case ISD::SETOGE:
12954   case ISD::SETGE:  Swap = true; // Fallthrough
12955   case ISD::SETLE:
12956   case ISD::SETOLE: SSECC = 2; break;
12957   case ISD::SETUO:  SSECC = 3; break;
12958   case ISD::SETUNE:
12959   case ISD::SETNE:  SSECC = 4; break;
12960   case ISD::SETULE: Swap = true; // Fallthrough
12961   case ISD::SETUGE: SSECC = 5; break;
12962   case ISD::SETULT: Swap = true; // Fallthrough
12963   case ISD::SETUGT: SSECC = 6; break;
12964   case ISD::SETO:   SSECC = 7; break;
12965   case ISD::SETUEQ:
12966   case ISD::SETONE: SSECC = 8; break;
12967   }
12968   if (Swap)
12969     std::swap(Op0, Op1);
12970
12971   return SSECC;
12972 }
12973
12974 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12975 // ones, and then concatenate the result back.
12976 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12977   MVT VT = Op.getSimpleValueType();
12978
12979   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12980          "Unsupported value type for operation");
12981
12982   unsigned NumElems = VT.getVectorNumElements();
12983   SDLoc dl(Op);
12984   SDValue CC = Op.getOperand(2);
12985
12986   // Extract the LHS vectors
12987   SDValue LHS = Op.getOperand(0);
12988   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12989   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12990
12991   // Extract the RHS vectors
12992   SDValue RHS = Op.getOperand(1);
12993   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12994   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12995
12996   // Issue the operation on the smaller types and concatenate the result back
12997   MVT EltVT = VT.getVectorElementType();
12998   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12999   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13000                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13001                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13002 }
13003
13004 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13005                                      const X86Subtarget *Subtarget) {
13006   SDValue Op0 = Op.getOperand(0);
13007   SDValue Op1 = Op.getOperand(1);
13008   SDValue CC = Op.getOperand(2);
13009   MVT VT = Op.getSimpleValueType();
13010   SDLoc dl(Op);
13011
13012   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13013          Op.getValueType().getScalarType() == MVT::i1 &&
13014          "Cannot set masked compare for this operation");
13015
13016   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13017   unsigned  Opc = 0;
13018   bool Unsigned = false;
13019   bool Swap = false;
13020   unsigned SSECC;
13021   switch (SetCCOpcode) {
13022   default: llvm_unreachable("Unexpected SETCC condition");
13023   case ISD::SETNE:  SSECC = 4; break;
13024   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13025   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13026   case ISD::SETLT:  Swap = true; //fall-through
13027   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13028   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13029   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13030   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13031   case ISD::SETULE: Unsigned = true; //fall-through
13032   case ISD::SETLE:  SSECC = 2; break;
13033   }
13034
13035   if (Swap)
13036     std::swap(Op0, Op1);
13037   if (Opc)
13038     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13039   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13040   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13041                      DAG.getConstant(SSECC, MVT::i8));
13042 }
13043
13044 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13045 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13046 /// return an empty value.
13047 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13048 {
13049   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13050   if (!BV)
13051     return SDValue();
13052
13053   MVT VT = Op1.getSimpleValueType();
13054   MVT EVT = VT.getVectorElementType();
13055   unsigned n = VT.getVectorNumElements();
13056   SmallVector<SDValue, 8> ULTOp1;
13057
13058   for (unsigned i = 0; i < n; ++i) {
13059     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13060     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13061       return SDValue();
13062
13063     // Avoid underflow.
13064     APInt Val = Elt->getAPIntValue();
13065     if (Val == 0)
13066       return SDValue();
13067
13068     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
13069   }
13070
13071   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13072 }
13073
13074 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13075                            SelectionDAG &DAG) {
13076   SDValue Op0 = Op.getOperand(0);
13077   SDValue Op1 = Op.getOperand(1);
13078   SDValue CC = Op.getOperand(2);
13079   MVT VT = Op.getSimpleValueType();
13080   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13081   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13082   SDLoc dl(Op);
13083
13084   if (isFP) {
13085 #ifndef NDEBUG
13086     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13087     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13088 #endif
13089
13090     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13091     unsigned Opc = X86ISD::CMPP;
13092     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13093       assert(VT.getVectorNumElements() <= 16);
13094       Opc = X86ISD::CMPM;
13095     }
13096     // In the two special cases we can't handle, emit two comparisons.
13097     if (SSECC == 8) {
13098       unsigned CC0, CC1;
13099       unsigned CombineOpc;
13100       if (SetCCOpcode == ISD::SETUEQ) {
13101         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13102       } else {
13103         assert(SetCCOpcode == ISD::SETONE);
13104         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13105       }
13106
13107       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13108                                  DAG.getConstant(CC0, MVT::i8));
13109       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13110                                  DAG.getConstant(CC1, MVT::i8));
13111       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13112     }
13113     // Handle all other FP comparisons here.
13114     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13115                        DAG.getConstant(SSECC, MVT::i8));
13116   }
13117
13118   // Break 256-bit integer vector compare into smaller ones.
13119   if (VT.is256BitVector() && !Subtarget->hasInt256())
13120     return Lower256IntVSETCC(Op, DAG);
13121
13122   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13123   EVT OpVT = Op1.getValueType();
13124   if (Subtarget->hasAVX512()) {
13125     if (Op1.getValueType().is512BitVector() ||
13126         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13127         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13128       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13129
13130     // In AVX-512 architecture setcc returns mask with i1 elements,
13131     // But there is no compare instruction for i8 and i16 elements in KNL.
13132     // We are not talking about 512-bit operands in this case, these
13133     // types are illegal.
13134     if (MaskResult &&
13135         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13136          OpVT.getVectorElementType().getSizeInBits() >= 8))
13137       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13138                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13139   }
13140
13141   // We are handling one of the integer comparisons here.  Since SSE only has
13142   // GT and EQ comparisons for integer, swapping operands and multiple
13143   // operations may be required for some comparisons.
13144   unsigned Opc;
13145   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13146   bool Subus = false;
13147
13148   switch (SetCCOpcode) {
13149   default: llvm_unreachable("Unexpected SETCC condition");
13150   case ISD::SETNE:  Invert = true;
13151   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13152   case ISD::SETLT:  Swap = true;
13153   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13154   case ISD::SETGE:  Swap = true;
13155   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13156                     Invert = true; break;
13157   case ISD::SETULT: Swap = true;
13158   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13159                     FlipSigns = true; break;
13160   case ISD::SETUGE: Swap = true;
13161   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13162                     FlipSigns = true; Invert = true; break;
13163   }
13164
13165   // Special case: Use min/max operations for SETULE/SETUGE
13166   MVT VET = VT.getVectorElementType();
13167   bool hasMinMax =
13168        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13169     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13170
13171   if (hasMinMax) {
13172     switch (SetCCOpcode) {
13173     default: break;
13174     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13175     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13176     }
13177
13178     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13179   }
13180
13181   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13182   if (!MinMax && hasSubus) {
13183     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13184     // Op0 u<= Op1:
13185     //   t = psubus Op0, Op1
13186     //   pcmpeq t, <0..0>
13187     switch (SetCCOpcode) {
13188     default: break;
13189     case ISD::SETULT: {
13190       // If the comparison is against a constant we can turn this into a
13191       // setule.  With psubus, setule does not require a swap.  This is
13192       // beneficial because the constant in the register is no longer
13193       // destructed as the destination so it can be hoisted out of a loop.
13194       // Only do this pre-AVX since vpcmp* is no longer destructive.
13195       if (Subtarget->hasAVX())
13196         break;
13197       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13198       if (ULEOp1.getNode()) {
13199         Op1 = ULEOp1;
13200         Subus = true; Invert = false; Swap = false;
13201       }
13202       break;
13203     }
13204     // Psubus is better than flip-sign because it requires no inversion.
13205     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13206     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13207     }
13208
13209     if (Subus) {
13210       Opc = X86ISD::SUBUS;
13211       FlipSigns = false;
13212     }
13213   }
13214
13215   if (Swap)
13216     std::swap(Op0, Op1);
13217
13218   // Check that the operation in question is available (most are plain SSE2,
13219   // but PCMPGTQ and PCMPEQQ have different requirements).
13220   if (VT == MVT::v2i64) {
13221     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13222       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13223
13224       // First cast everything to the right type.
13225       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13226       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13227
13228       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13229       // bits of the inputs before performing those operations. The lower
13230       // compare is always unsigned.
13231       SDValue SB;
13232       if (FlipSigns) {
13233         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13234       } else {
13235         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13236         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13237         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13238                          Sign, Zero, Sign, Zero);
13239       }
13240       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13241       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13242
13243       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13244       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13245       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13246
13247       // Create masks for only the low parts/high parts of the 64 bit integers.
13248       static const int MaskHi[] = { 1, 1, 3, 3 };
13249       static const int MaskLo[] = { 0, 0, 2, 2 };
13250       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13251       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13252       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13253
13254       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13255       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13256
13257       if (Invert)
13258         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13259
13260       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13261     }
13262
13263     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13264       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13265       // pcmpeqd + pshufd + pand.
13266       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13267
13268       // First cast everything to the right type.
13269       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13270       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13271
13272       // Do the compare.
13273       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13274
13275       // Make sure the lower and upper halves are both all-ones.
13276       static const int Mask[] = { 1, 0, 3, 2 };
13277       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13278       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13279
13280       if (Invert)
13281         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13282
13283       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13284     }
13285   }
13286
13287   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13288   // bits of the inputs before performing those operations.
13289   if (FlipSigns) {
13290     EVT EltVT = VT.getVectorElementType();
13291     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13292     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13293     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13294   }
13295
13296   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13297
13298   // If the logical-not of the result is required, perform that now.
13299   if (Invert)
13300     Result = DAG.getNOT(dl, Result, VT);
13301
13302   if (MinMax)
13303     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13304
13305   if (Subus)
13306     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13307                          getZeroVector(VT, Subtarget, DAG, dl));
13308
13309   return Result;
13310 }
13311
13312 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13313
13314   MVT VT = Op.getSimpleValueType();
13315
13316   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13317
13318   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13319          && "SetCC type must be 8-bit or 1-bit integer");
13320   SDValue Op0 = Op.getOperand(0);
13321   SDValue Op1 = Op.getOperand(1);
13322   SDLoc dl(Op);
13323   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13324
13325   // Optimize to BT if possible.
13326   // Lower (X & (1 << N)) == 0 to BT(X, N).
13327   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13328   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13329   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13330       Op1.getOpcode() == ISD::Constant &&
13331       cast<ConstantSDNode>(Op1)->isNullValue() &&
13332       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13333     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13334     if (NewSetCC.getNode()) {
13335       if (VT == MVT::i1)
13336         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13337       return NewSetCC;
13338     }
13339   }
13340
13341   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13342   // these.
13343   if (Op1.getOpcode() == ISD::Constant &&
13344       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13345        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13346       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13347
13348     // If the input is a setcc, then reuse the input setcc or use a new one with
13349     // the inverted condition.
13350     if (Op0.getOpcode() == X86ISD::SETCC) {
13351       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13352       bool Invert = (CC == ISD::SETNE) ^
13353         cast<ConstantSDNode>(Op1)->isNullValue();
13354       if (!Invert)
13355         return Op0;
13356
13357       CCode = X86::GetOppositeBranchCondition(CCode);
13358       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13359                                   DAG.getConstant(CCode, MVT::i8),
13360                                   Op0.getOperand(1));
13361       if (VT == MVT::i1)
13362         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13363       return SetCC;
13364     }
13365   }
13366   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13367       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13368       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13369
13370     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13371     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13372   }
13373
13374   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13375   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13376   if (X86CC == X86::COND_INVALID)
13377     return SDValue();
13378
13379   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13380   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13381   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13382                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13383   if (VT == MVT::i1)
13384     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13385   return SetCC;
13386 }
13387
13388 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13389 static bool isX86LogicalCmp(SDValue Op) {
13390   unsigned Opc = Op.getNode()->getOpcode();
13391   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13392       Opc == X86ISD::SAHF)
13393     return true;
13394   if (Op.getResNo() == 1 &&
13395       (Opc == X86ISD::ADD ||
13396        Opc == X86ISD::SUB ||
13397        Opc == X86ISD::ADC ||
13398        Opc == X86ISD::SBB ||
13399        Opc == X86ISD::SMUL ||
13400        Opc == X86ISD::UMUL ||
13401        Opc == X86ISD::INC ||
13402        Opc == X86ISD::DEC ||
13403        Opc == X86ISD::OR ||
13404        Opc == X86ISD::XOR ||
13405        Opc == X86ISD::AND))
13406     return true;
13407
13408   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13409     return true;
13410
13411   return false;
13412 }
13413
13414 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13415   if (V.getOpcode() != ISD::TRUNCATE)
13416     return false;
13417
13418   SDValue VOp0 = V.getOperand(0);
13419   unsigned InBits = VOp0.getValueSizeInBits();
13420   unsigned Bits = V.getValueSizeInBits();
13421   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13422 }
13423
13424 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13425   bool addTest = true;
13426   SDValue Cond  = Op.getOperand(0);
13427   SDValue Op1 = Op.getOperand(1);
13428   SDValue Op2 = Op.getOperand(2);
13429   SDLoc DL(Op);
13430   EVT VT = Op1.getValueType();
13431   SDValue CC;
13432
13433   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13434   // are available or VBLENDV if AVX is available.
13435   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13436   if (Cond.getOpcode() == ISD::SETCC &&
13437       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13438        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13439       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13440     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13441     int SSECC = translateX86FSETCC(
13442         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13443
13444     if (SSECC != 8) {
13445       if (Subtarget->hasAVX512()) {
13446         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13447                                   DAG.getConstant(SSECC, MVT::i8));
13448         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13449       }
13450
13451       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13452                                 DAG.getConstant(SSECC, MVT::i8));
13453
13454       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13455       // of 3 logic instructions for size savings and potentially speed.
13456       // Unfortunately, there is no scalar form of VBLENDV.
13457
13458       // If either operand is a constant, don't try this. We can expect to
13459       // optimize away at least one of the logic instructions later in that
13460       // case, so that sequence would be faster than a variable blend.
13461
13462       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13463       // uses XMM0 as the selection register. That may need just as many
13464       // instructions as the AND/ANDN/OR sequence due to register moves, so
13465       // don't bother.
13466
13467       if (Subtarget->hasAVX() &&
13468           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13469
13470         // Convert to vectors, do a VSELECT, and convert back to scalar.
13471         // All of the conversions should be optimized away.
13472
13473         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13474         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13475         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13476         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13477
13478         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13479         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13480
13481         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13482
13483         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13484                            VSel, DAG.getIntPtrConstant(0));
13485       }
13486       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13487       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13488       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13489     }
13490   }
13491
13492   if (Cond.getOpcode() == ISD::SETCC) {
13493     SDValue NewCond = LowerSETCC(Cond, DAG);
13494     if (NewCond.getNode())
13495       Cond = NewCond;
13496   }
13497
13498   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13499   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13500   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13501   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13502   if (Cond.getOpcode() == X86ISD::SETCC &&
13503       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13504       isZero(Cond.getOperand(1).getOperand(1))) {
13505     SDValue Cmp = Cond.getOperand(1);
13506
13507     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13508
13509     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13510         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13511       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13512
13513       SDValue CmpOp0 = Cmp.getOperand(0);
13514       // Apply further optimizations for special cases
13515       // (select (x != 0), -1, 0) -> neg & sbb
13516       // (select (x == 0), 0, -1) -> neg & sbb
13517       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13518         if (YC->isNullValue() &&
13519             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13520           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13521           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13522                                     DAG.getConstant(0, CmpOp0.getValueType()),
13523                                     CmpOp0);
13524           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13525                                     DAG.getConstant(X86::COND_B, MVT::i8),
13526                                     SDValue(Neg.getNode(), 1));
13527           return Res;
13528         }
13529
13530       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13531                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13532       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13533
13534       SDValue Res =   // Res = 0 or -1.
13535         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13536                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13537
13538       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13539         Res = DAG.getNOT(DL, Res, Res.getValueType());
13540
13541       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13542       if (!N2C || !N2C->isNullValue())
13543         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13544       return Res;
13545     }
13546   }
13547
13548   // Look past (and (setcc_carry (cmp ...)), 1).
13549   if (Cond.getOpcode() == ISD::AND &&
13550       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13551     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13552     if (C && C->getAPIntValue() == 1)
13553       Cond = Cond.getOperand(0);
13554   }
13555
13556   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13557   // setting operand in place of the X86ISD::SETCC.
13558   unsigned CondOpcode = Cond.getOpcode();
13559   if (CondOpcode == X86ISD::SETCC ||
13560       CondOpcode == X86ISD::SETCC_CARRY) {
13561     CC = Cond.getOperand(0);
13562
13563     SDValue Cmp = Cond.getOperand(1);
13564     unsigned Opc = Cmp.getOpcode();
13565     MVT VT = Op.getSimpleValueType();
13566
13567     bool IllegalFPCMov = false;
13568     if (VT.isFloatingPoint() && !VT.isVector() &&
13569         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13570       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13571
13572     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13573         Opc == X86ISD::BT) { // FIXME
13574       Cond = Cmp;
13575       addTest = false;
13576     }
13577   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13578              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13579              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13580               Cond.getOperand(0).getValueType() != MVT::i8)) {
13581     SDValue LHS = Cond.getOperand(0);
13582     SDValue RHS = Cond.getOperand(1);
13583     unsigned X86Opcode;
13584     unsigned X86Cond;
13585     SDVTList VTs;
13586     switch (CondOpcode) {
13587     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13588     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13589     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13590     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13591     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13592     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13593     default: llvm_unreachable("unexpected overflowing operator");
13594     }
13595     if (CondOpcode == ISD::UMULO)
13596       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13597                           MVT::i32);
13598     else
13599       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13600
13601     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13602
13603     if (CondOpcode == ISD::UMULO)
13604       Cond = X86Op.getValue(2);
13605     else
13606       Cond = X86Op.getValue(1);
13607
13608     CC = DAG.getConstant(X86Cond, MVT::i8);
13609     addTest = false;
13610   }
13611
13612   if (addTest) {
13613     // Look pass the truncate if the high bits are known zero.
13614     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13615         Cond = Cond.getOperand(0);
13616
13617     // We know the result of AND is compared against zero. Try to match
13618     // it to BT.
13619     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13620       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13621       if (NewSetCC.getNode()) {
13622         CC = NewSetCC.getOperand(0);
13623         Cond = NewSetCC.getOperand(1);
13624         addTest = false;
13625       }
13626     }
13627   }
13628
13629   if (addTest) {
13630     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13631     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13632   }
13633
13634   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13635   // a <  b ?  0 : -1 -> RES = setcc_carry
13636   // a >= b ? -1 :  0 -> RES = setcc_carry
13637   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13638   if (Cond.getOpcode() == X86ISD::SUB) {
13639     Cond = ConvertCmpIfNecessary(Cond, DAG);
13640     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13641
13642     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13643         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13644       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13645                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13646       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13647         return DAG.getNOT(DL, Res, Res.getValueType());
13648       return Res;
13649     }
13650   }
13651
13652   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13653   // widen the cmov and push the truncate through. This avoids introducing a new
13654   // branch during isel and doesn't add any extensions.
13655   if (Op.getValueType() == MVT::i8 &&
13656       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13657     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13658     if (T1.getValueType() == T2.getValueType() &&
13659         // Blacklist CopyFromReg to avoid partial register stalls.
13660         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13661       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13662       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13663       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13664     }
13665   }
13666
13667   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13668   // condition is true.
13669   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13670   SDValue Ops[] = { Op2, Op1, CC, Cond };
13671   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13672 }
13673
13674 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13675                                        SelectionDAG &DAG) {
13676   MVT VT = Op->getSimpleValueType(0);
13677   SDValue In = Op->getOperand(0);
13678   MVT InVT = In.getSimpleValueType();
13679   MVT VTElt = VT.getVectorElementType();
13680   MVT InVTElt = InVT.getVectorElementType();
13681   SDLoc dl(Op);
13682
13683   // SKX processor
13684   if ((InVTElt == MVT::i1) &&
13685       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13686         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13687
13688        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13689         VTElt.getSizeInBits() <= 16)) ||
13690
13691        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13692         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13693
13694        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13695         VTElt.getSizeInBits() >= 32))))
13696     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13697
13698   unsigned int NumElts = VT.getVectorNumElements();
13699
13700   if (NumElts != 8 && NumElts != 16)
13701     return SDValue();
13702
13703   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13704     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13705       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13706     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13707   }
13708
13709   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13710   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13711
13712   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13713   Constant *C = ConstantInt::get(*DAG.getContext(),
13714     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13715
13716   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13717   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13718   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13719                           MachinePointerInfo::getConstantPool(),
13720                           false, false, false, Alignment);
13721   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13722   if (VT.is512BitVector())
13723     return Brcst;
13724   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13725 }
13726
13727 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13728                                 SelectionDAG &DAG) {
13729   MVT VT = Op->getSimpleValueType(0);
13730   SDValue In = Op->getOperand(0);
13731   MVT InVT = In.getSimpleValueType();
13732   SDLoc dl(Op);
13733
13734   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13735     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13736
13737   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13738       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13739       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13740     return SDValue();
13741
13742   if (Subtarget->hasInt256())
13743     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13744
13745   // Optimize vectors in AVX mode
13746   // Sign extend  v8i16 to v8i32 and
13747   //              v4i32 to v4i64
13748   //
13749   // Divide input vector into two parts
13750   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13751   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13752   // concat the vectors to original VT
13753
13754   unsigned NumElems = InVT.getVectorNumElements();
13755   SDValue Undef = DAG.getUNDEF(InVT);
13756
13757   SmallVector<int,8> ShufMask1(NumElems, -1);
13758   for (unsigned i = 0; i != NumElems/2; ++i)
13759     ShufMask1[i] = i;
13760
13761   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13762
13763   SmallVector<int,8> ShufMask2(NumElems, -1);
13764   for (unsigned i = 0; i != NumElems/2; ++i)
13765     ShufMask2[i] = i + NumElems/2;
13766
13767   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13768
13769   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13770                                 VT.getVectorNumElements()/2);
13771
13772   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13773   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13774
13775   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13776 }
13777
13778 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13779 // may emit an illegal shuffle but the expansion is still better than scalar
13780 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13781 // we'll emit a shuffle and a arithmetic shift.
13782 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13783 // TODO: It is possible to support ZExt by zeroing the undef values during
13784 // the shuffle phase or after the shuffle.
13785 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13786                                  SelectionDAG &DAG) {
13787   MVT RegVT = Op.getSimpleValueType();
13788   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13789   assert(RegVT.isInteger() &&
13790          "We only custom lower integer vector sext loads.");
13791
13792   // Nothing useful we can do without SSE2 shuffles.
13793   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13794
13795   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13796   SDLoc dl(Ld);
13797   EVT MemVT = Ld->getMemoryVT();
13798   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13799   unsigned RegSz = RegVT.getSizeInBits();
13800
13801   ISD::LoadExtType Ext = Ld->getExtensionType();
13802
13803   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13804          && "Only anyext and sext are currently implemented.");
13805   assert(MemVT != RegVT && "Cannot extend to the same type");
13806   assert(MemVT.isVector() && "Must load a vector from memory");
13807
13808   unsigned NumElems = RegVT.getVectorNumElements();
13809   unsigned MemSz = MemVT.getSizeInBits();
13810   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13811
13812   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13813     // The only way in which we have a legal 256-bit vector result but not the
13814     // integer 256-bit operations needed to directly lower a sextload is if we
13815     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13816     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13817     // correctly legalized. We do this late to allow the canonical form of
13818     // sextload to persist throughout the rest of the DAG combiner -- it wants
13819     // to fold together any extensions it can, and so will fuse a sign_extend
13820     // of an sextload into a sextload targeting a wider value.
13821     SDValue Load;
13822     if (MemSz == 128) {
13823       // Just switch this to a normal load.
13824       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13825                                        "it must be a legal 128-bit vector "
13826                                        "type!");
13827       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13828                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13829                   Ld->isInvariant(), Ld->getAlignment());
13830     } else {
13831       assert(MemSz < 128 &&
13832              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13833       // Do an sext load to a 128-bit vector type. We want to use the same
13834       // number of elements, but elements half as wide. This will end up being
13835       // recursively lowered by this routine, but will succeed as we definitely
13836       // have all the necessary features if we're using AVX1.
13837       EVT HalfEltVT =
13838           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13839       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13840       Load =
13841           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13842                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13843                          Ld->isNonTemporal(), Ld->isInvariant(),
13844                          Ld->getAlignment());
13845     }
13846
13847     // Replace chain users with the new chain.
13848     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13849     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13850
13851     // Finally, do a normal sign-extend to the desired register.
13852     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13853   }
13854
13855   // All sizes must be a power of two.
13856   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13857          "Non-power-of-two elements are not custom lowered!");
13858
13859   // Attempt to load the original value using scalar loads.
13860   // Find the largest scalar type that divides the total loaded size.
13861   MVT SclrLoadTy = MVT::i8;
13862   for (MVT Tp : MVT::integer_valuetypes()) {
13863     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13864       SclrLoadTy = Tp;
13865     }
13866   }
13867
13868   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13869   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13870       (64 <= MemSz))
13871     SclrLoadTy = MVT::f64;
13872
13873   // Calculate the number of scalar loads that we need to perform
13874   // in order to load our vector from memory.
13875   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13876
13877   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13878          "Can only lower sext loads with a single scalar load!");
13879
13880   unsigned loadRegZize = RegSz;
13881   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13882     loadRegZize /= 2;
13883
13884   // Represent our vector as a sequence of elements which are the
13885   // largest scalar that we can load.
13886   EVT LoadUnitVecVT = EVT::getVectorVT(
13887       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13888
13889   // Represent the data using the same element type that is stored in
13890   // memory. In practice, we ''widen'' MemVT.
13891   EVT WideVecVT =
13892       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13893                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13894
13895   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13896          "Invalid vector type");
13897
13898   // We can't shuffle using an illegal type.
13899   assert(TLI.isTypeLegal(WideVecVT) &&
13900          "We only lower types that form legal widened vector types");
13901
13902   SmallVector<SDValue, 8> Chains;
13903   SDValue Ptr = Ld->getBasePtr();
13904   SDValue Increment =
13905       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13906   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13907
13908   for (unsigned i = 0; i < NumLoads; ++i) {
13909     // Perform a single load.
13910     SDValue ScalarLoad =
13911         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13912                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13913                     Ld->getAlignment());
13914     Chains.push_back(ScalarLoad.getValue(1));
13915     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13916     // another round of DAGCombining.
13917     if (i == 0)
13918       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13919     else
13920       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13921                         ScalarLoad, DAG.getIntPtrConstant(i));
13922
13923     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13924   }
13925
13926   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13927
13928   // Bitcast the loaded value to a vector of the original element type, in
13929   // the size of the target vector type.
13930   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13931   unsigned SizeRatio = RegSz / MemSz;
13932
13933   if (Ext == ISD::SEXTLOAD) {
13934     // If we have SSE4.1, we can directly emit a VSEXT node.
13935     if (Subtarget->hasSSE41()) {
13936       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13937       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13938       return Sext;
13939     }
13940
13941     // Otherwise we'll shuffle the small elements in the high bits of the
13942     // larger type and perform an arithmetic shift. If the shift is not legal
13943     // it's better to scalarize.
13944     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13945            "We can't implement a sext load without an arithmetic right shift!");
13946
13947     // Redistribute the loaded elements into the different locations.
13948     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13949     for (unsigned i = 0; i != NumElems; ++i)
13950       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13951
13952     SDValue Shuff = DAG.getVectorShuffle(
13953         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13954
13955     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13956
13957     // Build the arithmetic shift.
13958     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13959                    MemVT.getVectorElementType().getSizeInBits();
13960     Shuff =
13961         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13962
13963     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13964     return Shuff;
13965   }
13966
13967   // Redistribute the loaded elements into the different locations.
13968   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13969   for (unsigned i = 0; i != NumElems; ++i)
13970     ShuffleVec[i * SizeRatio] = i;
13971
13972   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13973                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13974
13975   // Bitcast to the requested type.
13976   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13977   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13978   return Shuff;
13979 }
13980
13981 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13982 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13983 // from the AND / OR.
13984 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13985   Opc = Op.getOpcode();
13986   if (Opc != ISD::OR && Opc != ISD::AND)
13987     return false;
13988   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13989           Op.getOperand(0).hasOneUse() &&
13990           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13991           Op.getOperand(1).hasOneUse());
13992 }
13993
13994 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13995 // 1 and that the SETCC node has a single use.
13996 static bool isXor1OfSetCC(SDValue Op) {
13997   if (Op.getOpcode() != ISD::XOR)
13998     return false;
13999   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14000   if (N1C && N1C->getAPIntValue() == 1) {
14001     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14002       Op.getOperand(0).hasOneUse();
14003   }
14004   return false;
14005 }
14006
14007 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14008   bool addTest = true;
14009   SDValue Chain = Op.getOperand(0);
14010   SDValue Cond  = Op.getOperand(1);
14011   SDValue Dest  = Op.getOperand(2);
14012   SDLoc dl(Op);
14013   SDValue CC;
14014   bool Inverted = false;
14015
14016   if (Cond.getOpcode() == ISD::SETCC) {
14017     // Check for setcc([su]{add,sub,mul}o == 0).
14018     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14019         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14020         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14021         Cond.getOperand(0).getResNo() == 1 &&
14022         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14023          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14024          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14025          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14026          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14027          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14028       Inverted = true;
14029       Cond = Cond.getOperand(0);
14030     } else {
14031       SDValue NewCond = LowerSETCC(Cond, DAG);
14032       if (NewCond.getNode())
14033         Cond = NewCond;
14034     }
14035   }
14036 #if 0
14037   // FIXME: LowerXALUO doesn't handle these!!
14038   else if (Cond.getOpcode() == X86ISD::ADD  ||
14039            Cond.getOpcode() == X86ISD::SUB  ||
14040            Cond.getOpcode() == X86ISD::SMUL ||
14041            Cond.getOpcode() == X86ISD::UMUL)
14042     Cond = LowerXALUO(Cond, DAG);
14043 #endif
14044
14045   // Look pass (and (setcc_carry (cmp ...)), 1).
14046   if (Cond.getOpcode() == ISD::AND &&
14047       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14048     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14049     if (C && C->getAPIntValue() == 1)
14050       Cond = Cond.getOperand(0);
14051   }
14052
14053   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14054   // setting operand in place of the X86ISD::SETCC.
14055   unsigned CondOpcode = Cond.getOpcode();
14056   if (CondOpcode == X86ISD::SETCC ||
14057       CondOpcode == X86ISD::SETCC_CARRY) {
14058     CC = Cond.getOperand(0);
14059
14060     SDValue Cmp = Cond.getOperand(1);
14061     unsigned Opc = Cmp.getOpcode();
14062     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14063     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14064       Cond = Cmp;
14065       addTest = false;
14066     } else {
14067       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14068       default: break;
14069       case X86::COND_O:
14070       case X86::COND_B:
14071         // These can only come from an arithmetic instruction with overflow,
14072         // e.g. SADDO, UADDO.
14073         Cond = Cond.getNode()->getOperand(1);
14074         addTest = false;
14075         break;
14076       }
14077     }
14078   }
14079   CondOpcode = Cond.getOpcode();
14080   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14081       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14082       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14083        Cond.getOperand(0).getValueType() != MVT::i8)) {
14084     SDValue LHS = Cond.getOperand(0);
14085     SDValue RHS = Cond.getOperand(1);
14086     unsigned X86Opcode;
14087     unsigned X86Cond;
14088     SDVTList VTs;
14089     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14090     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14091     // X86ISD::INC).
14092     switch (CondOpcode) {
14093     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14094     case ISD::SADDO:
14095       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14096         if (C->isOne()) {
14097           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14098           break;
14099         }
14100       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14101     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14102     case ISD::SSUBO:
14103       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14104         if (C->isOne()) {
14105           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14106           break;
14107         }
14108       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14109     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14110     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14111     default: llvm_unreachable("unexpected overflowing operator");
14112     }
14113     if (Inverted)
14114       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14115     if (CondOpcode == ISD::UMULO)
14116       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14117                           MVT::i32);
14118     else
14119       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14120
14121     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14122
14123     if (CondOpcode == ISD::UMULO)
14124       Cond = X86Op.getValue(2);
14125     else
14126       Cond = X86Op.getValue(1);
14127
14128     CC = DAG.getConstant(X86Cond, MVT::i8);
14129     addTest = false;
14130   } else {
14131     unsigned CondOpc;
14132     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14133       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14134       if (CondOpc == ISD::OR) {
14135         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14136         // two branches instead of an explicit OR instruction with a
14137         // separate test.
14138         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14139             isX86LogicalCmp(Cmp)) {
14140           CC = Cond.getOperand(0).getOperand(0);
14141           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14142                               Chain, Dest, CC, Cmp);
14143           CC = Cond.getOperand(1).getOperand(0);
14144           Cond = Cmp;
14145           addTest = false;
14146         }
14147       } else { // ISD::AND
14148         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14149         // two branches instead of an explicit AND instruction with a
14150         // separate test. However, we only do this if this block doesn't
14151         // have a fall-through edge, because this requires an explicit
14152         // jmp when the condition is false.
14153         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14154             isX86LogicalCmp(Cmp) &&
14155             Op.getNode()->hasOneUse()) {
14156           X86::CondCode CCode =
14157             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14158           CCode = X86::GetOppositeBranchCondition(CCode);
14159           CC = DAG.getConstant(CCode, MVT::i8);
14160           SDNode *User = *Op.getNode()->use_begin();
14161           // Look for an unconditional branch following this conditional branch.
14162           // We need this because we need to reverse the successors in order
14163           // to implement FCMP_OEQ.
14164           if (User->getOpcode() == ISD::BR) {
14165             SDValue FalseBB = User->getOperand(1);
14166             SDNode *NewBR =
14167               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14168             assert(NewBR == User);
14169             (void)NewBR;
14170             Dest = FalseBB;
14171
14172             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14173                                 Chain, Dest, CC, Cmp);
14174             X86::CondCode CCode =
14175               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14176             CCode = X86::GetOppositeBranchCondition(CCode);
14177             CC = DAG.getConstant(CCode, MVT::i8);
14178             Cond = Cmp;
14179             addTest = false;
14180           }
14181         }
14182       }
14183     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14184       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14185       // It should be transformed during dag combiner except when the condition
14186       // is set by a arithmetics with overflow node.
14187       X86::CondCode CCode =
14188         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14189       CCode = X86::GetOppositeBranchCondition(CCode);
14190       CC = DAG.getConstant(CCode, MVT::i8);
14191       Cond = Cond.getOperand(0).getOperand(1);
14192       addTest = false;
14193     } else if (Cond.getOpcode() == ISD::SETCC &&
14194                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14195       // For FCMP_OEQ, we can emit
14196       // two branches instead of an explicit AND instruction with a
14197       // separate test. However, we only do this if this block doesn't
14198       // have a fall-through edge, because this requires an explicit
14199       // jmp when the condition is false.
14200       if (Op.getNode()->hasOneUse()) {
14201         SDNode *User = *Op.getNode()->use_begin();
14202         // Look for an unconditional branch following this conditional branch.
14203         // We need this because we need to reverse the successors in order
14204         // to implement FCMP_OEQ.
14205         if (User->getOpcode() == ISD::BR) {
14206           SDValue FalseBB = User->getOperand(1);
14207           SDNode *NewBR =
14208             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14209           assert(NewBR == User);
14210           (void)NewBR;
14211           Dest = FalseBB;
14212
14213           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14214                                     Cond.getOperand(0), Cond.getOperand(1));
14215           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14216           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14217           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14218                               Chain, Dest, CC, Cmp);
14219           CC = DAG.getConstant(X86::COND_P, MVT::i8);
14220           Cond = Cmp;
14221           addTest = false;
14222         }
14223       }
14224     } else if (Cond.getOpcode() == ISD::SETCC &&
14225                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14226       // For FCMP_UNE, we can emit
14227       // two branches instead of an explicit AND instruction with a
14228       // separate test. However, we only do this if this block doesn't
14229       // have a fall-through edge, because this requires an explicit
14230       // jmp when the condition is false.
14231       if (Op.getNode()->hasOneUse()) {
14232         SDNode *User = *Op.getNode()->use_begin();
14233         // Look for an unconditional branch following this conditional branch.
14234         // We need this because we need to reverse the successors in order
14235         // to implement FCMP_UNE.
14236         if (User->getOpcode() == ISD::BR) {
14237           SDValue FalseBB = User->getOperand(1);
14238           SDNode *NewBR =
14239             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14240           assert(NewBR == User);
14241           (void)NewBR;
14242
14243           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14244                                     Cond.getOperand(0), Cond.getOperand(1));
14245           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14246           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14247           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14248                               Chain, Dest, CC, Cmp);
14249           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14250           Cond = Cmp;
14251           addTest = false;
14252           Dest = FalseBB;
14253         }
14254       }
14255     }
14256   }
14257
14258   if (addTest) {
14259     // Look pass the truncate if the high bits are known zero.
14260     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14261         Cond = Cond.getOperand(0);
14262
14263     // We know the result of AND is compared against zero. Try to match
14264     // it to BT.
14265     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14266       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14267       if (NewSetCC.getNode()) {
14268         CC = NewSetCC.getOperand(0);
14269         Cond = NewSetCC.getOperand(1);
14270         addTest = false;
14271       }
14272     }
14273   }
14274
14275   if (addTest) {
14276     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14277     CC = DAG.getConstant(X86Cond, MVT::i8);
14278     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14279   }
14280   Cond = ConvertCmpIfNecessary(Cond, DAG);
14281   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14282                      Chain, Dest, CC, Cond);
14283 }
14284
14285 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14286 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14287 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14288 // that the guard pages used by the OS virtual memory manager are allocated in
14289 // correct sequence.
14290 SDValue
14291 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14292                                            SelectionDAG &DAG) const {
14293   MachineFunction &MF = DAG.getMachineFunction();
14294   bool SplitStack = MF.shouldSplitStack();
14295   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14296                SplitStack;
14297   SDLoc dl(Op);
14298
14299   if (!Lower) {
14300     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14301     SDNode* Node = Op.getNode();
14302
14303     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14304     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14305         " not tell us which reg is the stack pointer!");
14306     EVT VT = Node->getValueType(0);
14307     SDValue Tmp1 = SDValue(Node, 0);
14308     SDValue Tmp2 = SDValue(Node, 1);
14309     SDValue Tmp3 = Node->getOperand(2);
14310     SDValue Chain = Tmp1.getOperand(0);
14311
14312     // Chain the dynamic stack allocation so that it doesn't modify the stack
14313     // pointer when other instructions are using the stack.
14314     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14315         SDLoc(Node));
14316
14317     SDValue Size = Tmp2.getOperand(1);
14318     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14319     Chain = SP.getValue(1);
14320     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14321     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14322     unsigned StackAlign = TFI.getStackAlignment();
14323     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14324     if (Align > StackAlign)
14325       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14326           DAG.getConstant(-(uint64_t)Align, VT));
14327     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14328
14329     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14330         DAG.getIntPtrConstant(0, true), SDValue(),
14331         SDLoc(Node));
14332
14333     SDValue Ops[2] = { Tmp1, Tmp2 };
14334     return DAG.getMergeValues(Ops, dl);
14335   }
14336
14337   // Get the inputs.
14338   SDValue Chain = Op.getOperand(0);
14339   SDValue Size  = Op.getOperand(1);
14340   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14341   EVT VT = Op.getNode()->getValueType(0);
14342
14343   bool Is64Bit = Subtarget->is64Bit();
14344   EVT SPTy = getPointerTy();
14345
14346   if (SplitStack) {
14347     MachineRegisterInfo &MRI = MF.getRegInfo();
14348
14349     if (Is64Bit) {
14350       // The 64 bit implementation of segmented stacks needs to clobber both r10
14351       // r11. This makes it impossible to use it along with nested parameters.
14352       const Function *F = MF.getFunction();
14353
14354       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14355            I != E; ++I)
14356         if (I->hasNestAttr())
14357           report_fatal_error("Cannot use segmented stacks with functions that "
14358                              "have nested arguments.");
14359     }
14360
14361     const TargetRegisterClass *AddrRegClass =
14362       getRegClassFor(getPointerTy());
14363     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14364     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14365     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14366                                 DAG.getRegister(Vreg, SPTy));
14367     SDValue Ops1[2] = { Value, Chain };
14368     return DAG.getMergeValues(Ops1, dl);
14369   } else {
14370     SDValue Flag;
14371     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14372
14373     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14374     Flag = Chain.getValue(1);
14375     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14376
14377     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14378
14379     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14380     unsigned SPReg = RegInfo->getStackRegister();
14381     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14382     Chain = SP.getValue(1);
14383
14384     if (Align) {
14385       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14386                        DAG.getConstant(-(uint64_t)Align, VT));
14387       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14388     }
14389
14390     SDValue Ops1[2] = { SP, Chain };
14391     return DAG.getMergeValues(Ops1, dl);
14392   }
14393 }
14394
14395 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14396   MachineFunction &MF = DAG.getMachineFunction();
14397   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14398
14399   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14400   SDLoc DL(Op);
14401
14402   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14403     // vastart just stores the address of the VarArgsFrameIndex slot into the
14404     // memory location argument.
14405     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14406                                    getPointerTy());
14407     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14408                         MachinePointerInfo(SV), false, false, 0);
14409   }
14410
14411   // __va_list_tag:
14412   //   gp_offset         (0 - 6 * 8)
14413   //   fp_offset         (48 - 48 + 8 * 16)
14414   //   overflow_arg_area (point to parameters coming in memory).
14415   //   reg_save_area
14416   SmallVector<SDValue, 8> MemOps;
14417   SDValue FIN = Op.getOperand(1);
14418   // Store gp_offset
14419   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14420                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14421                                                MVT::i32),
14422                                FIN, MachinePointerInfo(SV), false, false, 0);
14423   MemOps.push_back(Store);
14424
14425   // Store fp_offset
14426   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14427                     FIN, DAG.getIntPtrConstant(4));
14428   Store = DAG.getStore(Op.getOperand(0), DL,
14429                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14430                                        MVT::i32),
14431                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14432   MemOps.push_back(Store);
14433
14434   // Store ptr to overflow_arg_area
14435   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14436                     FIN, DAG.getIntPtrConstant(4));
14437   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14438                                     getPointerTy());
14439   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14440                        MachinePointerInfo(SV, 8),
14441                        false, false, 0);
14442   MemOps.push_back(Store);
14443
14444   // Store ptr to reg_save_area.
14445   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14446                     FIN, DAG.getIntPtrConstant(8));
14447   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14448                                     getPointerTy());
14449   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14450                        MachinePointerInfo(SV, 16), false, false, 0);
14451   MemOps.push_back(Store);
14452   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14453 }
14454
14455 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14456   assert(Subtarget->is64Bit() &&
14457          "LowerVAARG only handles 64-bit va_arg!");
14458   assert((Subtarget->isTargetLinux() ||
14459           Subtarget->isTargetDarwin()) &&
14460           "Unhandled target in LowerVAARG");
14461   assert(Op.getNode()->getNumOperands() == 4);
14462   SDValue Chain = Op.getOperand(0);
14463   SDValue SrcPtr = Op.getOperand(1);
14464   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14465   unsigned Align = Op.getConstantOperandVal(3);
14466   SDLoc dl(Op);
14467
14468   EVT ArgVT = Op.getNode()->getValueType(0);
14469   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14470   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14471   uint8_t ArgMode;
14472
14473   // Decide which area this value should be read from.
14474   // TODO: Implement the AMD64 ABI in its entirety. This simple
14475   // selection mechanism works only for the basic types.
14476   if (ArgVT == MVT::f80) {
14477     llvm_unreachable("va_arg for f80 not yet implemented");
14478   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14479     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14480   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14481     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14482   } else {
14483     llvm_unreachable("Unhandled argument type in LowerVAARG");
14484   }
14485
14486   if (ArgMode == 2) {
14487     // Sanity Check: Make sure using fp_offset makes sense.
14488     assert(!DAG.getTarget().Options.UseSoftFloat &&
14489            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14490                Attribute::NoImplicitFloat)) &&
14491            Subtarget->hasSSE1());
14492   }
14493
14494   // Insert VAARG_64 node into the DAG
14495   // VAARG_64 returns two values: Variable Argument Address, Chain
14496   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, MVT::i32),
14497                        DAG.getConstant(ArgMode, MVT::i8),
14498                        DAG.getConstant(Align, MVT::i32)};
14499   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14500   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14501                                           VTs, InstOps, MVT::i64,
14502                                           MachinePointerInfo(SV),
14503                                           /*Align=*/0,
14504                                           /*Volatile=*/false,
14505                                           /*ReadMem=*/true,
14506                                           /*WriteMem=*/true);
14507   Chain = VAARG.getValue(1);
14508
14509   // Load the next argument and return it
14510   return DAG.getLoad(ArgVT, dl,
14511                      Chain,
14512                      VAARG,
14513                      MachinePointerInfo(),
14514                      false, false, false, 0);
14515 }
14516
14517 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14518                            SelectionDAG &DAG) {
14519   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14520   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14521   SDValue Chain = Op.getOperand(0);
14522   SDValue DstPtr = Op.getOperand(1);
14523   SDValue SrcPtr = Op.getOperand(2);
14524   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14525   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14526   SDLoc DL(Op);
14527
14528   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14529                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14530                        false, false,
14531                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14532 }
14533
14534 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14535 // amount is a constant. Takes immediate version of shift as input.
14536 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14537                                           SDValue SrcOp, uint64_t ShiftAmt,
14538                                           SelectionDAG &DAG) {
14539   MVT ElementType = VT.getVectorElementType();
14540
14541   // Fold this packed shift into its first operand if ShiftAmt is 0.
14542   if (ShiftAmt == 0)
14543     return SrcOp;
14544
14545   // Check for ShiftAmt >= element width
14546   if (ShiftAmt >= ElementType.getSizeInBits()) {
14547     if (Opc == X86ISD::VSRAI)
14548       ShiftAmt = ElementType.getSizeInBits() - 1;
14549     else
14550       return DAG.getConstant(0, VT);
14551   }
14552
14553   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14554          && "Unknown target vector shift-by-constant node");
14555
14556   // Fold this packed vector shift into a build vector if SrcOp is a
14557   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14558   if (VT == SrcOp.getSimpleValueType() &&
14559       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14560     SmallVector<SDValue, 8> Elts;
14561     unsigned NumElts = SrcOp->getNumOperands();
14562     ConstantSDNode *ND;
14563
14564     switch(Opc) {
14565     default: llvm_unreachable(nullptr);
14566     case X86ISD::VSHLI:
14567       for (unsigned i=0; i!=NumElts; ++i) {
14568         SDValue CurrentOp = SrcOp->getOperand(i);
14569         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14570           Elts.push_back(CurrentOp);
14571           continue;
14572         }
14573         ND = cast<ConstantSDNode>(CurrentOp);
14574         const APInt &C = ND->getAPIntValue();
14575         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14576       }
14577       break;
14578     case X86ISD::VSRLI:
14579       for (unsigned i=0; i!=NumElts; ++i) {
14580         SDValue CurrentOp = SrcOp->getOperand(i);
14581         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14582           Elts.push_back(CurrentOp);
14583           continue;
14584         }
14585         ND = cast<ConstantSDNode>(CurrentOp);
14586         const APInt &C = ND->getAPIntValue();
14587         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14588       }
14589       break;
14590     case X86ISD::VSRAI:
14591       for (unsigned i=0; i!=NumElts; ++i) {
14592         SDValue CurrentOp = SrcOp->getOperand(i);
14593         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14594           Elts.push_back(CurrentOp);
14595           continue;
14596         }
14597         ND = cast<ConstantSDNode>(CurrentOp);
14598         const APInt &C = ND->getAPIntValue();
14599         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14600       }
14601       break;
14602     }
14603
14604     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14605   }
14606
14607   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14608 }
14609
14610 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14611 // may or may not be a constant. Takes immediate version of shift as input.
14612 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14613                                    SDValue SrcOp, SDValue ShAmt,
14614                                    SelectionDAG &DAG) {
14615   MVT SVT = ShAmt.getSimpleValueType();
14616   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14617
14618   // Catch shift-by-constant.
14619   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14620     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14621                                       CShAmt->getZExtValue(), DAG);
14622
14623   // Change opcode to non-immediate version
14624   switch (Opc) {
14625     default: llvm_unreachable("Unknown target vector shift node");
14626     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14627     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14628     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14629   }
14630
14631   const X86Subtarget &Subtarget =
14632       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14633   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14634       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14635     // Let the shuffle legalizer expand this shift amount node.
14636     SDValue Op0 = ShAmt.getOperand(0);
14637     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14638     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14639   } else {
14640     // Need to build a vector containing shift amount.
14641     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14642     SmallVector<SDValue, 4> ShOps;
14643     ShOps.push_back(ShAmt);
14644     if (SVT == MVT::i32) {
14645       ShOps.push_back(DAG.getConstant(0, SVT));
14646       ShOps.push_back(DAG.getUNDEF(SVT));
14647     }
14648     ShOps.push_back(DAG.getUNDEF(SVT));
14649
14650     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14651     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14652   }
14653
14654   // The return type has to be a 128-bit type with the same element
14655   // type as the input type.
14656   MVT EltVT = VT.getVectorElementType();
14657   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14658
14659   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14660   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14661 }
14662
14663 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14664 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14665 /// necessary casting for \p Mask when lowering masking intrinsics.
14666 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14667                                     SDValue PreservedSrc,
14668                                     const X86Subtarget *Subtarget,
14669                                     SelectionDAG &DAG) {
14670     EVT VT = Op.getValueType();
14671     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14672                                   MVT::i1, VT.getVectorNumElements());
14673     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14674                                      Mask.getValueType().getSizeInBits());
14675     SDLoc dl(Op);
14676
14677     assert(MaskVT.isSimple() && "invalid mask type");
14678
14679     if (isAllOnes(Mask))
14680       return Op;
14681
14682     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14683     // are extracted by EXTRACT_SUBVECTOR.
14684     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14685                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14686                               DAG.getIntPtrConstant(0));
14687
14688     switch (Op.getOpcode()) {
14689       default: break;
14690       case X86ISD::PCMPEQM:
14691       case X86ISD::PCMPGTM:
14692       case X86ISD::CMPM:
14693       case X86ISD::CMPMU:
14694         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14695     }
14696     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14697       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14698     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14699 }
14700
14701 /// \brief Creates an SDNode for a predicated scalar operation.
14702 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14703 /// The mask is comming as MVT::i8 and it should be truncated
14704 /// to MVT::i1 while lowering masking intrinsics.
14705 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14706 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14707 /// a scalar instruction.
14708 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14709                                     SDValue PreservedSrc,
14710                                     const X86Subtarget *Subtarget,
14711                                     SelectionDAG &DAG) {
14712     if (isAllOnes(Mask))
14713       return Op;
14714
14715     EVT VT = Op.getValueType();
14716     SDLoc dl(Op);
14717     // The mask should be of type MVT::i1
14718     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14719
14720     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14721       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14722     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14723 }
14724
14725 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14726                                        SelectionDAG &DAG) {
14727   SDLoc dl(Op);
14728   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14729   EVT VT = Op.getValueType();
14730   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14731   if (IntrData) {
14732     switch(IntrData->Type) {
14733     case INTR_TYPE_1OP:
14734       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14735     case INTR_TYPE_2OP:
14736       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14737         Op.getOperand(2));
14738     case INTR_TYPE_3OP:
14739       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14740         Op.getOperand(2), Op.getOperand(3));
14741     case INTR_TYPE_1OP_MASK_RM: {
14742       SDValue Src = Op.getOperand(1);
14743       SDValue Src0 = Op.getOperand(2);
14744       SDValue Mask = Op.getOperand(3);
14745       SDValue RoundingMode = Op.getOperand(4);
14746       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14747                                               RoundingMode),
14748                                   Mask, Src0, Subtarget, DAG);
14749     }
14750     case INTR_TYPE_SCALAR_MASK_RM: {
14751       SDValue Src1 = Op.getOperand(1);
14752       SDValue Src2 = Op.getOperand(2);
14753       SDValue Src0 = Op.getOperand(3);
14754       SDValue Mask = Op.getOperand(4);
14755       // There are 2 kinds of intrinsics in this group:
14756       // (1) With supress-all-exceptions (sae) - 6 operands
14757       // (2) With rounding mode and sae - 7 operands.
14758       if (Op.getNumOperands() == 6) {
14759         SDValue Sae  = Op.getOperand(5);
14760         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14761                                                 Sae),
14762                                     Mask, Src0, Subtarget, DAG);
14763       }
14764       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14765       SDValue RoundingMode  = Op.getOperand(5);
14766       SDValue Sae  = Op.getOperand(6);
14767       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14768                                               RoundingMode, Sae),
14769                                   Mask, Src0, Subtarget, DAG);
14770     }
14771     case INTR_TYPE_2OP_MASK: {
14772       SDValue Src1 = Op.getOperand(1);
14773       SDValue Src2 = Op.getOperand(2);
14774       SDValue PassThru = Op.getOperand(3);
14775       SDValue Mask = Op.getOperand(4);
14776       // We specify 2 possible opcodes for intrinsics with rounding modes.
14777       // First, we check if the intrinsic may have non-default rounding mode,
14778       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14779       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14780       if (IntrWithRoundingModeOpcode != 0) {
14781         SDValue Rnd = Op.getOperand(5);
14782         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14783         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14784           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14785                                       dl, Op.getValueType(),
14786                                       Src1, Src2, Rnd),
14787                                       Mask, PassThru, Subtarget, DAG);
14788         }
14789       }
14790       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14791                                               Src1,Src2),
14792                                   Mask, PassThru, Subtarget, DAG);
14793     }
14794     case FMA_OP_MASK: {
14795       SDValue Src1 = Op.getOperand(1);
14796       SDValue Src2 = Op.getOperand(2);
14797       SDValue Src3 = Op.getOperand(3);
14798       SDValue Mask = Op.getOperand(4);
14799       // We specify 2 possible opcodes for intrinsics with rounding modes.
14800       // First, we check if the intrinsic may have non-default rounding mode,
14801       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14802       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14803       if (IntrWithRoundingModeOpcode != 0) {
14804         SDValue Rnd = Op.getOperand(5);
14805         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14806             X86::STATIC_ROUNDING::CUR_DIRECTION)
14807           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14808                                                   dl, Op.getValueType(),
14809                                                   Src1, Src2, Src3, Rnd),
14810                                       Mask, Src1, Subtarget, DAG);
14811       }
14812       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14813                                               dl, Op.getValueType(),
14814                                               Src1, Src2, Src3),
14815                                   Mask, Src1, Subtarget, DAG);
14816     }
14817     case CMP_MASK:
14818     case CMP_MASK_CC: {
14819       // Comparison intrinsics with masks.
14820       // Example of transformation:
14821       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14822       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14823       // (i8 (bitcast
14824       //   (v8i1 (insert_subvector undef,
14825       //           (v2i1 (and (PCMPEQM %a, %b),
14826       //                      (extract_subvector
14827       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14828       EVT VT = Op.getOperand(1).getValueType();
14829       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14830                                     VT.getVectorNumElements());
14831       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14832       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14833                                        Mask.getValueType().getSizeInBits());
14834       SDValue Cmp;
14835       if (IntrData->Type == CMP_MASK_CC) {
14836         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14837                     Op.getOperand(2), Op.getOperand(3));
14838       } else {
14839         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14840         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14841                     Op.getOperand(2));
14842       }
14843       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14844                                              DAG.getTargetConstant(0, MaskVT),
14845                                              Subtarget, DAG);
14846       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14847                                 DAG.getUNDEF(BitcastVT), CmpMask,
14848                                 DAG.getIntPtrConstant(0));
14849       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14850     }
14851     case COMI: { // Comparison intrinsics
14852       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14853       SDValue LHS = Op.getOperand(1);
14854       SDValue RHS = Op.getOperand(2);
14855       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14856       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14857       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14858       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14859                                   DAG.getConstant(X86CC, MVT::i8), Cond);
14860       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14861     }
14862     case VSHIFT:
14863       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14864                                  Op.getOperand(1), Op.getOperand(2), DAG);
14865     case VSHIFT_MASK:
14866       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14867                                                       Op.getSimpleValueType(),
14868                                                       Op.getOperand(1),
14869                                                       Op.getOperand(2), DAG),
14870                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
14871                                   DAG);
14872     case COMPRESS_EXPAND_IN_REG: {
14873       SDValue Mask = Op.getOperand(3);
14874       SDValue DataToCompress = Op.getOperand(1);
14875       SDValue PassThru = Op.getOperand(2);
14876       if (isAllOnes(Mask)) // return data as is
14877         return Op.getOperand(1);
14878       EVT VT = Op.getValueType();
14879       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14880                                     VT.getVectorNumElements());
14881       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14882                                        Mask.getValueType().getSizeInBits());
14883       SDLoc dl(Op);
14884       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14885                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14886                                   DAG.getIntPtrConstant(0));
14887
14888       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
14889                          PassThru);
14890     }
14891     case BLEND: {
14892       SDValue Mask = Op.getOperand(3);
14893       EVT VT = Op.getValueType();
14894       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14895                                     VT.getVectorNumElements());
14896       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14897                                        Mask.getValueType().getSizeInBits());
14898       SDLoc dl(Op);
14899       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14900                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14901                                   DAG.getIntPtrConstant(0));
14902       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
14903                          Op.getOperand(2));
14904     }
14905     default:
14906       break;
14907     }
14908   }
14909
14910   switch (IntNo) {
14911   default: return SDValue();    // Don't custom lower most intrinsics.
14912
14913   case Intrinsic::x86_avx2_permd:
14914   case Intrinsic::x86_avx2_permps:
14915     // Operands intentionally swapped. Mask is last operand to intrinsic,
14916     // but second operand for node/instruction.
14917     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14918                        Op.getOperand(2), Op.getOperand(1));
14919
14920   case Intrinsic::x86_avx512_mask_valign_q_512:
14921   case Intrinsic::x86_avx512_mask_valign_d_512:
14922     // Vector source operands are swapped.
14923     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14924                                             Op.getValueType(), Op.getOperand(2),
14925                                             Op.getOperand(1),
14926                                             Op.getOperand(3)),
14927                                 Op.getOperand(5), Op.getOperand(4),
14928                                 Subtarget, DAG);
14929
14930   // ptest and testp intrinsics. The intrinsic these come from are designed to
14931   // return an integer value, not just an instruction so lower it to the ptest
14932   // or testp pattern and a setcc for the result.
14933   case Intrinsic::x86_sse41_ptestz:
14934   case Intrinsic::x86_sse41_ptestc:
14935   case Intrinsic::x86_sse41_ptestnzc:
14936   case Intrinsic::x86_avx_ptestz_256:
14937   case Intrinsic::x86_avx_ptestc_256:
14938   case Intrinsic::x86_avx_ptestnzc_256:
14939   case Intrinsic::x86_avx_vtestz_ps:
14940   case Intrinsic::x86_avx_vtestc_ps:
14941   case Intrinsic::x86_avx_vtestnzc_ps:
14942   case Intrinsic::x86_avx_vtestz_pd:
14943   case Intrinsic::x86_avx_vtestc_pd:
14944   case Intrinsic::x86_avx_vtestnzc_pd:
14945   case Intrinsic::x86_avx_vtestz_ps_256:
14946   case Intrinsic::x86_avx_vtestc_ps_256:
14947   case Intrinsic::x86_avx_vtestnzc_ps_256:
14948   case Intrinsic::x86_avx_vtestz_pd_256:
14949   case Intrinsic::x86_avx_vtestc_pd_256:
14950   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14951     bool IsTestPacked = false;
14952     unsigned X86CC;
14953     switch (IntNo) {
14954     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14955     case Intrinsic::x86_avx_vtestz_ps:
14956     case Intrinsic::x86_avx_vtestz_pd:
14957     case Intrinsic::x86_avx_vtestz_ps_256:
14958     case Intrinsic::x86_avx_vtestz_pd_256:
14959       IsTestPacked = true; // Fallthrough
14960     case Intrinsic::x86_sse41_ptestz:
14961     case Intrinsic::x86_avx_ptestz_256:
14962       // ZF = 1
14963       X86CC = X86::COND_E;
14964       break;
14965     case Intrinsic::x86_avx_vtestc_ps:
14966     case Intrinsic::x86_avx_vtestc_pd:
14967     case Intrinsic::x86_avx_vtestc_ps_256:
14968     case Intrinsic::x86_avx_vtestc_pd_256:
14969       IsTestPacked = true; // Fallthrough
14970     case Intrinsic::x86_sse41_ptestc:
14971     case Intrinsic::x86_avx_ptestc_256:
14972       // CF = 1
14973       X86CC = X86::COND_B;
14974       break;
14975     case Intrinsic::x86_avx_vtestnzc_ps:
14976     case Intrinsic::x86_avx_vtestnzc_pd:
14977     case Intrinsic::x86_avx_vtestnzc_ps_256:
14978     case Intrinsic::x86_avx_vtestnzc_pd_256:
14979       IsTestPacked = true; // Fallthrough
14980     case Intrinsic::x86_sse41_ptestnzc:
14981     case Intrinsic::x86_avx_ptestnzc_256:
14982       // ZF and CF = 0
14983       X86CC = X86::COND_A;
14984       break;
14985     }
14986
14987     SDValue LHS = Op.getOperand(1);
14988     SDValue RHS = Op.getOperand(2);
14989     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14990     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14991     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14992     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14993     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14994   }
14995   case Intrinsic::x86_avx512_kortestz_w:
14996   case Intrinsic::x86_avx512_kortestc_w: {
14997     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14998     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14999     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15000     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
15001     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15002     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15003     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15004   }
15005
15006   case Intrinsic::x86_sse42_pcmpistria128:
15007   case Intrinsic::x86_sse42_pcmpestria128:
15008   case Intrinsic::x86_sse42_pcmpistric128:
15009   case Intrinsic::x86_sse42_pcmpestric128:
15010   case Intrinsic::x86_sse42_pcmpistrio128:
15011   case Intrinsic::x86_sse42_pcmpestrio128:
15012   case Intrinsic::x86_sse42_pcmpistris128:
15013   case Intrinsic::x86_sse42_pcmpestris128:
15014   case Intrinsic::x86_sse42_pcmpistriz128:
15015   case Intrinsic::x86_sse42_pcmpestriz128: {
15016     unsigned Opcode;
15017     unsigned X86CC;
15018     switch (IntNo) {
15019     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15020     case Intrinsic::x86_sse42_pcmpistria128:
15021       Opcode = X86ISD::PCMPISTRI;
15022       X86CC = X86::COND_A;
15023       break;
15024     case Intrinsic::x86_sse42_pcmpestria128:
15025       Opcode = X86ISD::PCMPESTRI;
15026       X86CC = X86::COND_A;
15027       break;
15028     case Intrinsic::x86_sse42_pcmpistric128:
15029       Opcode = X86ISD::PCMPISTRI;
15030       X86CC = X86::COND_B;
15031       break;
15032     case Intrinsic::x86_sse42_pcmpestric128:
15033       Opcode = X86ISD::PCMPESTRI;
15034       X86CC = X86::COND_B;
15035       break;
15036     case Intrinsic::x86_sse42_pcmpistrio128:
15037       Opcode = X86ISD::PCMPISTRI;
15038       X86CC = X86::COND_O;
15039       break;
15040     case Intrinsic::x86_sse42_pcmpestrio128:
15041       Opcode = X86ISD::PCMPESTRI;
15042       X86CC = X86::COND_O;
15043       break;
15044     case Intrinsic::x86_sse42_pcmpistris128:
15045       Opcode = X86ISD::PCMPISTRI;
15046       X86CC = X86::COND_S;
15047       break;
15048     case Intrinsic::x86_sse42_pcmpestris128:
15049       Opcode = X86ISD::PCMPESTRI;
15050       X86CC = X86::COND_S;
15051       break;
15052     case Intrinsic::x86_sse42_pcmpistriz128:
15053       Opcode = X86ISD::PCMPISTRI;
15054       X86CC = X86::COND_E;
15055       break;
15056     case Intrinsic::x86_sse42_pcmpestriz128:
15057       Opcode = X86ISD::PCMPESTRI;
15058       X86CC = X86::COND_E;
15059       break;
15060     }
15061     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15062     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15063     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15064     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15065                                 DAG.getConstant(X86CC, MVT::i8),
15066                                 SDValue(PCMP.getNode(), 1));
15067     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15068   }
15069
15070   case Intrinsic::x86_sse42_pcmpistri128:
15071   case Intrinsic::x86_sse42_pcmpestri128: {
15072     unsigned Opcode;
15073     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15074       Opcode = X86ISD::PCMPISTRI;
15075     else
15076       Opcode = X86ISD::PCMPESTRI;
15077
15078     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15079     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15080     return DAG.getNode(Opcode, dl, VTs, NewOps);
15081   }
15082   }
15083 }
15084
15085 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15086                               SDValue Src, SDValue Mask, SDValue Base,
15087                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15088                               const X86Subtarget * Subtarget) {
15089   SDLoc dl(Op);
15090   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15091   assert(C && "Invalid scale type");
15092   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15093   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15094                              Index.getSimpleValueType().getVectorNumElements());
15095   SDValue MaskInReg;
15096   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15097   if (MaskC)
15098     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15099   else
15100     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15101   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15102   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15103   SDValue Segment = DAG.getRegister(0, MVT::i32);
15104   if (Src.getOpcode() == ISD::UNDEF)
15105     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15106   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15107   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15108   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15109   return DAG.getMergeValues(RetOps, dl);
15110 }
15111
15112 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15113                                SDValue Src, SDValue Mask, SDValue Base,
15114                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15115   SDLoc dl(Op);
15116   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15117   assert(C && "Invalid scale type");
15118   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15119   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15120   SDValue Segment = DAG.getRegister(0, MVT::i32);
15121   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15122                              Index.getSimpleValueType().getVectorNumElements());
15123   SDValue MaskInReg;
15124   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15125   if (MaskC)
15126     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15127   else
15128     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15129   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15130   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15131   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15132   return SDValue(Res, 1);
15133 }
15134
15135 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15136                                SDValue Mask, SDValue Base, SDValue Index,
15137                                SDValue ScaleOp, SDValue Chain) {
15138   SDLoc dl(Op);
15139   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15140   assert(C && "Invalid scale type");
15141   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15142   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15143   SDValue Segment = DAG.getRegister(0, MVT::i32);
15144   EVT MaskVT =
15145     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15146   SDValue MaskInReg;
15147   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15148   if (MaskC)
15149     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15150   else
15151     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15152   //SDVTList VTs = DAG.getVTList(MVT::Other);
15153   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15154   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15155   return SDValue(Res, 0);
15156 }
15157
15158 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15159 // read performance monitor counters (x86_rdpmc).
15160 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15161                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15162                               SmallVectorImpl<SDValue> &Results) {
15163   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15164   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15165   SDValue LO, HI;
15166
15167   // The ECX register is used to select the index of the performance counter
15168   // to read.
15169   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15170                                    N->getOperand(2));
15171   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15172
15173   // Reads the content of a 64-bit performance counter and returns it in the
15174   // registers EDX:EAX.
15175   if (Subtarget->is64Bit()) {
15176     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15177     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15178                             LO.getValue(2));
15179   } else {
15180     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15181     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15182                             LO.getValue(2));
15183   }
15184   Chain = HI.getValue(1);
15185
15186   if (Subtarget->is64Bit()) {
15187     // The EAX register is loaded with the low-order 32 bits. The EDX register
15188     // is loaded with the supported high-order bits of the counter.
15189     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15190                               DAG.getConstant(32, MVT::i8));
15191     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15192     Results.push_back(Chain);
15193     return;
15194   }
15195
15196   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15197   SDValue Ops[] = { LO, HI };
15198   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15199   Results.push_back(Pair);
15200   Results.push_back(Chain);
15201 }
15202
15203 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15204 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15205 // also used to custom lower READCYCLECOUNTER nodes.
15206 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15207                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15208                               SmallVectorImpl<SDValue> &Results) {
15209   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15210   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15211   SDValue LO, HI;
15212
15213   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15214   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15215   // and the EAX register is loaded with the low-order 32 bits.
15216   if (Subtarget->is64Bit()) {
15217     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15218     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15219                             LO.getValue(2));
15220   } else {
15221     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15222     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15223                             LO.getValue(2));
15224   }
15225   SDValue Chain = HI.getValue(1);
15226
15227   if (Opcode == X86ISD::RDTSCP_DAG) {
15228     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15229
15230     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15231     // the ECX register. Add 'ecx' explicitly to the chain.
15232     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15233                                      HI.getValue(2));
15234     // Explicitly store the content of ECX at the location passed in input
15235     // to the 'rdtscp' intrinsic.
15236     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15237                          MachinePointerInfo(), false, false, 0);
15238   }
15239
15240   if (Subtarget->is64Bit()) {
15241     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15242     // the EAX register is loaded with the low-order 32 bits.
15243     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15244                               DAG.getConstant(32, MVT::i8));
15245     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15246     Results.push_back(Chain);
15247     return;
15248   }
15249
15250   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15251   SDValue Ops[] = { LO, HI };
15252   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15253   Results.push_back(Pair);
15254   Results.push_back(Chain);
15255 }
15256
15257 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15258                                      SelectionDAG &DAG) {
15259   SmallVector<SDValue, 2> Results;
15260   SDLoc DL(Op);
15261   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15262                           Results);
15263   return DAG.getMergeValues(Results, DL);
15264 }
15265
15266
15267 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15268                                       SelectionDAG &DAG) {
15269   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15270
15271   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15272   if (!IntrData)
15273     return SDValue();
15274
15275   SDLoc dl(Op);
15276   switch(IntrData->Type) {
15277   default:
15278     llvm_unreachable("Unknown Intrinsic Type");
15279     break;
15280   case RDSEED:
15281   case RDRAND: {
15282     // Emit the node with the right value type.
15283     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15284     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15285
15286     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15287     // Otherwise return the value from Rand, which is always 0, casted to i32.
15288     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15289                       DAG.getConstant(1, Op->getValueType(1)),
15290                       DAG.getConstant(X86::COND_B, MVT::i32),
15291                       SDValue(Result.getNode(), 1) };
15292     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15293                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15294                                   Ops);
15295
15296     // Return { result, isValid, chain }.
15297     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15298                        SDValue(Result.getNode(), 2));
15299   }
15300   case GATHER: {
15301   //gather(v1, mask, index, base, scale);
15302     SDValue Chain = Op.getOperand(0);
15303     SDValue Src   = Op.getOperand(2);
15304     SDValue Base  = Op.getOperand(3);
15305     SDValue Index = Op.getOperand(4);
15306     SDValue Mask  = Op.getOperand(5);
15307     SDValue Scale = Op.getOperand(6);
15308     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15309                           Subtarget);
15310   }
15311   case SCATTER: {
15312   //scatter(base, mask, index, v1, scale);
15313     SDValue Chain = Op.getOperand(0);
15314     SDValue Base  = Op.getOperand(2);
15315     SDValue Mask  = Op.getOperand(3);
15316     SDValue Index = Op.getOperand(4);
15317     SDValue Src   = Op.getOperand(5);
15318     SDValue Scale = Op.getOperand(6);
15319     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15320   }
15321   case PREFETCH: {
15322     SDValue Hint = Op.getOperand(6);
15323     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15324     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15325     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15326     SDValue Chain = Op.getOperand(0);
15327     SDValue Mask  = Op.getOperand(2);
15328     SDValue Index = Op.getOperand(3);
15329     SDValue Base  = Op.getOperand(4);
15330     SDValue Scale = Op.getOperand(5);
15331     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15332   }
15333   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15334   case RDTSC: {
15335     SmallVector<SDValue, 2> Results;
15336     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15337     return DAG.getMergeValues(Results, dl);
15338   }
15339   // Read Performance Monitoring Counters.
15340   case RDPMC: {
15341     SmallVector<SDValue, 2> Results;
15342     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15343     return DAG.getMergeValues(Results, dl);
15344   }
15345   // XTEST intrinsics.
15346   case XTEST: {
15347     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15348     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15349     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15350                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15351                                 InTrans);
15352     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15353     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15354                        Ret, SDValue(InTrans.getNode(), 1));
15355   }
15356   // ADC/ADCX/SBB
15357   case ADX: {
15358     SmallVector<SDValue, 2> Results;
15359     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15360     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15361     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15362                                 DAG.getConstant(-1, MVT::i8));
15363     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15364                               Op.getOperand(4), GenCF.getValue(1));
15365     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15366                                  Op.getOperand(5), MachinePointerInfo(),
15367                                  false, false, 0);
15368     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15369                                 DAG.getConstant(X86::COND_B, MVT::i8),
15370                                 Res.getValue(1));
15371     Results.push_back(SetCC);
15372     Results.push_back(Store);
15373     return DAG.getMergeValues(Results, dl);
15374   }
15375   case COMPRESS_TO_MEM: {
15376     SDLoc dl(Op);
15377     SDValue Mask = Op.getOperand(4);
15378     SDValue DataToCompress = Op.getOperand(3);
15379     SDValue Addr = Op.getOperand(2);
15380     SDValue Chain = Op.getOperand(0);
15381
15382     if (isAllOnes(Mask)) // return just a store
15383       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15384                           MachinePointerInfo(), false, false, 0);
15385
15386     EVT VT = DataToCompress.getValueType();
15387     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15388                                   VT.getVectorNumElements());
15389     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15390                                      Mask.getValueType().getSizeInBits());
15391     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15392                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15393                                 DAG.getIntPtrConstant(0));
15394
15395     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15396                                       DataToCompress, DAG.getUNDEF(VT));
15397     return DAG.getStore(Chain, dl, Compressed, Addr,
15398                         MachinePointerInfo(), false, false, 0);
15399   }
15400   case EXPAND_FROM_MEM: {
15401     SDLoc dl(Op);
15402     SDValue Mask = Op.getOperand(4);
15403     SDValue PathThru = Op.getOperand(3);
15404     SDValue Addr = Op.getOperand(2);
15405     SDValue Chain = Op.getOperand(0);
15406     EVT VT = Op.getValueType();
15407
15408     if (isAllOnes(Mask)) // return just a load
15409       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15410                          false, 0);
15411     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15412                                   VT.getVectorNumElements());
15413     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15414                                      Mask.getValueType().getSizeInBits());
15415     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15416                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15417                                 DAG.getIntPtrConstant(0));
15418
15419     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15420                                    false, false, false, 0);
15421
15422     SDValue Results[] = {
15423         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15424         Chain};
15425     return DAG.getMergeValues(Results, dl);
15426   }
15427   }
15428 }
15429
15430 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15431                                            SelectionDAG &DAG) const {
15432   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15433   MFI->setReturnAddressIsTaken(true);
15434
15435   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15436     return SDValue();
15437
15438   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15439   SDLoc dl(Op);
15440   EVT PtrVT = getPointerTy();
15441
15442   if (Depth > 0) {
15443     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15444     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15445     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15446     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15447                        DAG.getNode(ISD::ADD, dl, PtrVT,
15448                                    FrameAddr, Offset),
15449                        MachinePointerInfo(), false, false, false, 0);
15450   }
15451
15452   // Just load the return address.
15453   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15454   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15455                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15456 }
15457
15458 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15459   MachineFunction &MF = DAG.getMachineFunction();
15460   MachineFrameInfo *MFI = MF.getFrameInfo();
15461   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15462   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15463   EVT VT = Op.getValueType();
15464
15465   MFI->setFrameAddressIsTaken(true);
15466
15467   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15468     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15469     // is not possible to crawl up the stack without looking at the unwind codes
15470     // simultaneously.
15471     int FrameAddrIndex = FuncInfo->getFAIndex();
15472     if (!FrameAddrIndex) {
15473       // Set up a frame object for the return address.
15474       unsigned SlotSize = RegInfo->getSlotSize();
15475       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15476           SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15477       FuncInfo->setFAIndex(FrameAddrIndex);
15478     }
15479     return DAG.getFrameIndex(FrameAddrIndex, VT);
15480   }
15481
15482   unsigned FrameReg =
15483       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15484   SDLoc dl(Op);  // FIXME probably not meaningful
15485   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15486   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15487           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15488          "Invalid Frame Register!");
15489   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15490   while (Depth--)
15491     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15492                             MachinePointerInfo(),
15493                             false, false, false, 0);
15494   return FrameAddr;
15495 }
15496
15497 // FIXME? Maybe this could be a TableGen attribute on some registers and
15498 // this table could be generated automatically from RegInfo.
15499 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15500                                               EVT VT) const {
15501   unsigned Reg = StringSwitch<unsigned>(RegName)
15502                        .Case("esp", X86::ESP)
15503                        .Case("rsp", X86::RSP)
15504                        .Default(0);
15505   if (Reg)
15506     return Reg;
15507   report_fatal_error("Invalid register name global variable");
15508 }
15509
15510 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15511                                                      SelectionDAG &DAG) const {
15512   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15513   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15514 }
15515
15516 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15517   SDValue Chain     = Op.getOperand(0);
15518   SDValue Offset    = Op.getOperand(1);
15519   SDValue Handler   = Op.getOperand(2);
15520   SDLoc dl      (Op);
15521
15522   EVT PtrVT = getPointerTy();
15523   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15524   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15525   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15526           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15527          "Invalid Frame Register!");
15528   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15529   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15530
15531   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15532                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15533   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15534   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15535                        false, false, 0);
15536   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15537
15538   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15539                      DAG.getRegister(StoreAddrReg, PtrVT));
15540 }
15541
15542 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15543                                                SelectionDAG &DAG) const {
15544   SDLoc DL(Op);
15545   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15546                      DAG.getVTList(MVT::i32, MVT::Other),
15547                      Op.getOperand(0), Op.getOperand(1));
15548 }
15549
15550 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15551                                                 SelectionDAG &DAG) const {
15552   SDLoc DL(Op);
15553   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15554                      Op.getOperand(0), Op.getOperand(1));
15555 }
15556
15557 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15558   return Op.getOperand(0);
15559 }
15560
15561 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15562                                                 SelectionDAG &DAG) const {
15563   SDValue Root = Op.getOperand(0);
15564   SDValue Trmp = Op.getOperand(1); // trampoline
15565   SDValue FPtr = Op.getOperand(2); // nested function
15566   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15567   SDLoc dl (Op);
15568
15569   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15570   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15571
15572   if (Subtarget->is64Bit()) {
15573     SDValue OutChains[6];
15574
15575     // Large code-model.
15576     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15577     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15578
15579     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15580     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15581
15582     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15583
15584     // Load the pointer to the nested function into R11.
15585     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15586     SDValue Addr = Trmp;
15587     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15588                                 Addr, MachinePointerInfo(TrmpAddr),
15589                                 false, false, 0);
15590
15591     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15592                        DAG.getConstant(2, MVT::i64));
15593     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15594                                 MachinePointerInfo(TrmpAddr, 2),
15595                                 false, false, 2);
15596
15597     // Load the 'nest' parameter value into R10.
15598     // R10 is specified in X86CallingConv.td
15599     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15600     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15601                        DAG.getConstant(10, MVT::i64));
15602     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15603                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15604                                 false, false, 0);
15605
15606     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15607                        DAG.getConstant(12, MVT::i64));
15608     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15609                                 MachinePointerInfo(TrmpAddr, 12),
15610                                 false, false, 2);
15611
15612     // Jump to the nested function.
15613     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15614     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15615                        DAG.getConstant(20, MVT::i64));
15616     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15617                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15618                                 false, false, 0);
15619
15620     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15621     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15622                        DAG.getConstant(22, MVT::i64));
15623     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15624                                 MachinePointerInfo(TrmpAddr, 22),
15625                                 false, false, 0);
15626
15627     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15628   } else {
15629     const Function *Func =
15630       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15631     CallingConv::ID CC = Func->getCallingConv();
15632     unsigned NestReg;
15633
15634     switch (CC) {
15635     default:
15636       llvm_unreachable("Unsupported calling convention");
15637     case CallingConv::C:
15638     case CallingConv::X86_StdCall: {
15639       // Pass 'nest' parameter in ECX.
15640       // Must be kept in sync with X86CallingConv.td
15641       NestReg = X86::ECX;
15642
15643       // Check that ECX wasn't needed by an 'inreg' parameter.
15644       FunctionType *FTy = Func->getFunctionType();
15645       const AttributeSet &Attrs = Func->getAttributes();
15646
15647       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15648         unsigned InRegCount = 0;
15649         unsigned Idx = 1;
15650
15651         for (FunctionType::param_iterator I = FTy->param_begin(),
15652              E = FTy->param_end(); I != E; ++I, ++Idx)
15653           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15654             // FIXME: should only count parameters that are lowered to integers.
15655             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15656
15657         if (InRegCount > 2) {
15658           report_fatal_error("Nest register in use - reduce number of inreg"
15659                              " parameters!");
15660         }
15661       }
15662       break;
15663     }
15664     case CallingConv::X86_FastCall:
15665     case CallingConv::X86_ThisCall:
15666     case CallingConv::Fast:
15667       // Pass 'nest' parameter in EAX.
15668       // Must be kept in sync with X86CallingConv.td
15669       NestReg = X86::EAX;
15670       break;
15671     }
15672
15673     SDValue OutChains[4];
15674     SDValue Addr, Disp;
15675
15676     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15677                        DAG.getConstant(10, MVT::i32));
15678     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15679
15680     // This is storing the opcode for MOV32ri.
15681     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15682     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15683     OutChains[0] = DAG.getStore(Root, dl,
15684                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15685                                 Trmp, MachinePointerInfo(TrmpAddr),
15686                                 false, false, 0);
15687
15688     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15689                        DAG.getConstant(1, MVT::i32));
15690     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15691                                 MachinePointerInfo(TrmpAddr, 1),
15692                                 false, false, 1);
15693
15694     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15695     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15696                        DAG.getConstant(5, MVT::i32));
15697     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15698                                 MachinePointerInfo(TrmpAddr, 5),
15699                                 false, false, 1);
15700
15701     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15702                        DAG.getConstant(6, MVT::i32));
15703     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15704                                 MachinePointerInfo(TrmpAddr, 6),
15705                                 false, false, 1);
15706
15707     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15708   }
15709 }
15710
15711 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15712                                             SelectionDAG &DAG) const {
15713   /*
15714    The rounding mode is in bits 11:10 of FPSR, and has the following
15715    settings:
15716      00 Round to nearest
15717      01 Round to -inf
15718      10 Round to +inf
15719      11 Round to 0
15720
15721   FLT_ROUNDS, on the other hand, expects the following:
15722     -1 Undefined
15723      0 Round to 0
15724      1 Round to nearest
15725      2 Round to +inf
15726      3 Round to -inf
15727
15728   To perform the conversion, we do:
15729     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15730   */
15731
15732   MachineFunction &MF = DAG.getMachineFunction();
15733   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15734   unsigned StackAlignment = TFI.getStackAlignment();
15735   MVT VT = Op.getSimpleValueType();
15736   SDLoc DL(Op);
15737
15738   // Save FP Control Word to stack slot
15739   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15740   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15741
15742   MachineMemOperand *MMO =
15743    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15744                            MachineMemOperand::MOStore, 2, 2);
15745
15746   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15747   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15748                                           DAG.getVTList(MVT::Other),
15749                                           Ops, MVT::i16, MMO);
15750
15751   // Load FP Control Word from stack slot
15752   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15753                             MachinePointerInfo(), false, false, false, 0);
15754
15755   // Transform as necessary
15756   SDValue CWD1 =
15757     DAG.getNode(ISD::SRL, DL, MVT::i16,
15758                 DAG.getNode(ISD::AND, DL, MVT::i16,
15759                             CWD, DAG.getConstant(0x800, MVT::i16)),
15760                 DAG.getConstant(11, MVT::i8));
15761   SDValue CWD2 =
15762     DAG.getNode(ISD::SRL, DL, MVT::i16,
15763                 DAG.getNode(ISD::AND, DL, MVT::i16,
15764                             CWD, DAG.getConstant(0x400, MVT::i16)),
15765                 DAG.getConstant(9, MVT::i8));
15766
15767   SDValue RetVal =
15768     DAG.getNode(ISD::AND, DL, MVT::i16,
15769                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15770                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15771                             DAG.getConstant(1, MVT::i16)),
15772                 DAG.getConstant(3, MVT::i16));
15773
15774   return DAG.getNode((VT.getSizeInBits() < 16 ?
15775                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15776 }
15777
15778 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15779   MVT VT = Op.getSimpleValueType();
15780   EVT OpVT = VT;
15781   unsigned NumBits = VT.getSizeInBits();
15782   SDLoc dl(Op);
15783
15784   Op = Op.getOperand(0);
15785   if (VT == MVT::i8) {
15786     // Zero extend to i32 since there is not an i8 bsr.
15787     OpVT = MVT::i32;
15788     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15789   }
15790
15791   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15792   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15793   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15794
15795   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15796   SDValue Ops[] = {
15797     Op,
15798     DAG.getConstant(NumBits+NumBits-1, OpVT),
15799     DAG.getConstant(X86::COND_E, MVT::i8),
15800     Op.getValue(1)
15801   };
15802   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15803
15804   // Finally xor with NumBits-1.
15805   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15806
15807   if (VT == MVT::i8)
15808     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15809   return Op;
15810 }
15811
15812 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15813   MVT VT = Op.getSimpleValueType();
15814   EVT OpVT = VT;
15815   unsigned NumBits = VT.getSizeInBits();
15816   SDLoc dl(Op);
15817
15818   Op = Op.getOperand(0);
15819   if (VT == MVT::i8) {
15820     // Zero extend to i32 since there is not an i8 bsr.
15821     OpVT = MVT::i32;
15822     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15823   }
15824
15825   // Issue a bsr (scan bits in reverse).
15826   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15827   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15828
15829   // And xor with NumBits-1.
15830   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15831
15832   if (VT == MVT::i8)
15833     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15834   return Op;
15835 }
15836
15837 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15838   MVT VT = Op.getSimpleValueType();
15839   unsigned NumBits = VT.getSizeInBits();
15840   SDLoc dl(Op);
15841   Op = Op.getOperand(0);
15842
15843   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15844   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15845   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15846
15847   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15848   SDValue Ops[] = {
15849     Op,
15850     DAG.getConstant(NumBits, VT),
15851     DAG.getConstant(X86::COND_E, MVT::i8),
15852     Op.getValue(1)
15853   };
15854   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15855 }
15856
15857 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15858 // ones, and then concatenate the result back.
15859 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15860   MVT VT = Op.getSimpleValueType();
15861
15862   assert(VT.is256BitVector() && VT.isInteger() &&
15863          "Unsupported value type for operation");
15864
15865   unsigned NumElems = VT.getVectorNumElements();
15866   SDLoc dl(Op);
15867
15868   // Extract the LHS vectors
15869   SDValue LHS = Op.getOperand(0);
15870   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15871   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15872
15873   // Extract the RHS vectors
15874   SDValue RHS = Op.getOperand(1);
15875   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15876   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15877
15878   MVT EltVT = VT.getVectorElementType();
15879   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15880
15881   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15882                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15883                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15884 }
15885
15886 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15887   assert(Op.getSimpleValueType().is256BitVector() &&
15888          Op.getSimpleValueType().isInteger() &&
15889          "Only handle AVX 256-bit vector integer operation");
15890   return Lower256IntArith(Op, DAG);
15891 }
15892
15893 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15894   assert(Op.getSimpleValueType().is256BitVector() &&
15895          Op.getSimpleValueType().isInteger() &&
15896          "Only handle AVX 256-bit vector integer operation");
15897   return Lower256IntArith(Op, DAG);
15898 }
15899
15900 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15901                         SelectionDAG &DAG) {
15902   SDLoc dl(Op);
15903   MVT VT = Op.getSimpleValueType();
15904
15905   // Decompose 256-bit ops into smaller 128-bit ops.
15906   if (VT.is256BitVector() && !Subtarget->hasInt256())
15907     return Lower256IntArith(Op, DAG);
15908
15909   SDValue A = Op.getOperand(0);
15910   SDValue B = Op.getOperand(1);
15911
15912   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
15913   // pairs, multiply and truncate.
15914   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
15915     if (Subtarget->hasInt256()) {
15916       if (VT == MVT::v32i8) {
15917         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
15918         SDValue Lo = DAG.getIntPtrConstant(0);
15919         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2);
15920         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
15921         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
15922         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
15923         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
15924         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15925                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
15926                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
15927       }
15928
15929       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
15930       return DAG.getNode(
15931           ISD::TRUNCATE, dl, VT,
15932           DAG.getNode(ISD::MUL, dl, ExVT,
15933                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
15934                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
15935     }
15936
15937     assert(VT == MVT::v16i8 &&
15938            "Pre-AVX2 support only supports v16i8 multiplication");
15939     MVT ExVT = MVT::v8i16;
15940
15941     // Extract the lo parts and sign extend to i16
15942     SDValue ALo, BLo;
15943     if (Subtarget->hasSSE41()) {
15944       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
15945       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
15946     } else {
15947       const int ShufMask[] = {0, -1, 1, -1, 2, -1, 3, -1,
15948                               4, -1, 5, -1, 6, -1, 7, -1};
15949       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
15950       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
15951       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
15952       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
15953       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, ExVT));
15954       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, ExVT));
15955     }
15956
15957     // Extract the hi parts and sign extend to i16
15958     SDValue AHi, BHi;
15959     if (Subtarget->hasSSE41()) {
15960       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
15961                               -1, -1, -1, -1, -1, -1, -1, -1};
15962       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
15963       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
15964       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
15965       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
15966     } else {
15967       const int ShufMask[] = {8,  -1, 9,  -1, 10, -1, 11, -1,
15968                               12, -1, 13, -1, 14, -1, 15, -1};
15969       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
15970       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
15971       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
15972       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
15973       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, ExVT));
15974       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, ExVT));
15975     }
15976
15977     // Multiply, mask the lower 8bits of the lo/hi results and pack
15978     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
15979     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
15980     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, ExVT));
15981     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, ExVT));
15982     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
15983   }
15984
15985   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15986   if (VT == MVT::v4i32) {
15987     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15988            "Should not custom lower when pmuldq is available!");
15989
15990     // Extract the odd parts.
15991     static const int UnpackMask[] = { 1, -1, 3, -1 };
15992     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15993     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15994
15995     // Multiply the even parts.
15996     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15997     // Now multiply odd parts.
15998     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15999
16000     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16001     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16002
16003     // Merge the two vectors back together with a shuffle. This expands into 2
16004     // shuffles.
16005     static const int ShufMask[] = { 0, 4, 2, 6 };
16006     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16007   }
16008
16009   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16010          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16011
16012   //  Ahi = psrlqi(a, 32);
16013   //  Bhi = psrlqi(b, 32);
16014   //
16015   //  AloBlo = pmuludq(a, b);
16016   //  AloBhi = pmuludq(a, Bhi);
16017   //  AhiBlo = pmuludq(Ahi, b);
16018
16019   //  AloBhi = psllqi(AloBhi, 32);
16020   //  AhiBlo = psllqi(AhiBlo, 32);
16021   //  return AloBlo + AloBhi + AhiBlo;
16022
16023   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16024   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16025
16026   // Bit cast to 32-bit vectors for MULUDQ
16027   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16028                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16029   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16030   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16031   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16032   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16033
16034   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16035   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16036   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16037
16038   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16039   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16040
16041   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16042   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16043 }
16044
16045 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16046   assert(Subtarget->isTargetWin64() && "Unexpected target");
16047   EVT VT = Op.getValueType();
16048   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16049          "Unexpected return type for lowering");
16050
16051   RTLIB::Libcall LC;
16052   bool isSigned;
16053   switch (Op->getOpcode()) {
16054   default: llvm_unreachable("Unexpected request for libcall!");
16055   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16056   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16057   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16058   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16059   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16060   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16061   }
16062
16063   SDLoc dl(Op);
16064   SDValue InChain = DAG.getEntryNode();
16065
16066   TargetLowering::ArgListTy Args;
16067   TargetLowering::ArgListEntry Entry;
16068   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16069     EVT ArgVT = Op->getOperand(i).getValueType();
16070     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16071            "Unexpected argument type for lowering");
16072     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16073     Entry.Node = StackPtr;
16074     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16075                            false, false, 16);
16076     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16077     Entry.Ty = PointerType::get(ArgTy,0);
16078     Entry.isSExt = false;
16079     Entry.isZExt = false;
16080     Args.push_back(Entry);
16081   }
16082
16083   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16084                                          getPointerTy());
16085
16086   TargetLowering::CallLoweringInfo CLI(DAG);
16087   CLI.setDebugLoc(dl).setChain(InChain)
16088     .setCallee(getLibcallCallingConv(LC),
16089                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16090                Callee, std::move(Args), 0)
16091     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16092
16093   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16094   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16095 }
16096
16097 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16098                              SelectionDAG &DAG) {
16099   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16100   EVT VT = Op0.getValueType();
16101   SDLoc dl(Op);
16102
16103   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16104          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16105
16106   // PMULxD operations multiply each even value (starting at 0) of LHS with
16107   // the related value of RHS and produce a widen result.
16108   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16109   // => <2 x i64> <ae|cg>
16110   //
16111   // In other word, to have all the results, we need to perform two PMULxD:
16112   // 1. one with the even values.
16113   // 2. one with the odd values.
16114   // To achieve #2, with need to place the odd values at an even position.
16115   //
16116   // Place the odd value at an even position (basically, shift all values 1
16117   // step to the left):
16118   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16119   // <a|b|c|d> => <b|undef|d|undef>
16120   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16121   // <e|f|g|h> => <f|undef|h|undef>
16122   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16123
16124   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16125   // ints.
16126   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16127   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16128   unsigned Opcode =
16129       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16130   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16131   // => <2 x i64> <ae|cg>
16132   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16133                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16134   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16135   // => <2 x i64> <bf|dh>
16136   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16137                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16138
16139   // Shuffle it back into the right order.
16140   SDValue Highs, Lows;
16141   if (VT == MVT::v8i32) {
16142     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16143     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16144     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16145     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16146   } else {
16147     const int HighMask[] = {1, 5, 3, 7};
16148     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16149     const int LowMask[] = {0, 4, 2, 6};
16150     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16151   }
16152
16153   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16154   // unsigned multiply.
16155   if (IsSigned && !Subtarget->hasSSE41()) {
16156     SDValue ShAmt =
16157         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16158     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16159                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16160     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16161                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16162
16163     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16164     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16165   }
16166
16167   // The first result of MUL_LOHI is actually the low value, followed by the
16168   // high value.
16169   SDValue Ops[] = {Lows, Highs};
16170   return DAG.getMergeValues(Ops, dl);
16171 }
16172
16173 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16174                                          const X86Subtarget *Subtarget) {
16175   MVT VT = Op.getSimpleValueType();
16176   SDLoc dl(Op);
16177   SDValue R = Op.getOperand(0);
16178   SDValue Amt = Op.getOperand(1);
16179
16180   // Optimize shl/srl/sra with constant shift amount.
16181   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16182     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16183       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16184
16185       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16186           (Subtarget->hasInt256() &&
16187            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16188           (Subtarget->hasAVX512() &&
16189            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16190         if (Op.getOpcode() == ISD::SHL)
16191           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16192                                             DAG);
16193         if (Op.getOpcode() == ISD::SRL)
16194           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16195                                             DAG);
16196         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16197           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16198                                             DAG);
16199       }
16200
16201       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16202         unsigned NumElts = VT.getVectorNumElements();
16203         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16204
16205         if (Op.getOpcode() == ISD::SHL) {
16206           // Make a large shift.
16207           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16208                                                    R, ShiftAmt, DAG);
16209           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16210           // Zero out the rightmost bits.
16211           SmallVector<SDValue, 32> V(
16212               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), MVT::i8));
16213           return DAG.getNode(ISD::AND, dl, VT, SHL,
16214                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16215         }
16216         if (Op.getOpcode() == ISD::SRL) {
16217           // Make a large shift.
16218           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16219                                                    R, ShiftAmt, DAG);
16220           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16221           // Zero out the leftmost bits.
16222           SmallVector<SDValue, 32> V(
16223               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, MVT::i8));
16224           return DAG.getNode(ISD::AND, dl, VT, SRL,
16225                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16226         }
16227         if (Op.getOpcode() == ISD::SRA) {
16228           if (ShiftAmt == 7) {
16229             // R s>> 7  ===  R s< 0
16230             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16231             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16232           }
16233
16234           // R s>> a === ((R u>> a) ^ m) - m
16235           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16236           SmallVector<SDValue, 32> V(NumElts,
16237                                      DAG.getConstant(128 >> ShiftAmt, MVT::i8));
16238           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16239           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16240           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16241           return Res;
16242         }
16243         llvm_unreachable("Unknown shift opcode.");
16244       }
16245     }
16246   }
16247
16248   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16249   if (!Subtarget->is64Bit() &&
16250       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16251       Amt.getOpcode() == ISD::BITCAST &&
16252       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16253     Amt = Amt.getOperand(0);
16254     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16255                      VT.getVectorNumElements();
16256     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16257     uint64_t ShiftAmt = 0;
16258     for (unsigned i = 0; i != Ratio; ++i) {
16259       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16260       if (!C)
16261         return SDValue();
16262       // 6 == Log2(64)
16263       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16264     }
16265     // Check remaining shift amounts.
16266     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16267       uint64_t ShAmt = 0;
16268       for (unsigned j = 0; j != Ratio; ++j) {
16269         ConstantSDNode *C =
16270           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16271         if (!C)
16272           return SDValue();
16273         // 6 == Log2(64)
16274         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16275       }
16276       if (ShAmt != ShiftAmt)
16277         return SDValue();
16278     }
16279     switch (Op.getOpcode()) {
16280     default:
16281       llvm_unreachable("Unknown shift opcode!");
16282     case ISD::SHL:
16283       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16284                                         DAG);
16285     case ISD::SRL:
16286       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16287                                         DAG);
16288     case ISD::SRA:
16289       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16290                                         DAG);
16291     }
16292   }
16293
16294   return SDValue();
16295 }
16296
16297 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16298                                         const X86Subtarget* Subtarget) {
16299   MVT VT = Op.getSimpleValueType();
16300   SDLoc dl(Op);
16301   SDValue R = Op.getOperand(0);
16302   SDValue Amt = Op.getOperand(1);
16303
16304   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16305       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16306       (Subtarget->hasInt256() &&
16307        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16308         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16309        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16310     SDValue BaseShAmt;
16311     EVT EltVT = VT.getVectorElementType();
16312
16313     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16314       // Check if this build_vector node is doing a splat.
16315       // If so, then set BaseShAmt equal to the splat value.
16316       BaseShAmt = BV->getSplatValue();
16317       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16318         BaseShAmt = SDValue();
16319     } else {
16320       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16321         Amt = Amt.getOperand(0);
16322
16323       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16324       if (SVN && SVN->isSplat()) {
16325         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16326         SDValue InVec = Amt.getOperand(0);
16327         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16328           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16329                  "Unexpected shuffle index found!");
16330           BaseShAmt = InVec.getOperand(SplatIdx);
16331         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16332            if (ConstantSDNode *C =
16333                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16334              if (C->getZExtValue() == SplatIdx)
16335                BaseShAmt = InVec.getOperand(1);
16336            }
16337         }
16338
16339         if (!BaseShAmt)
16340           // Avoid introducing an extract element from a shuffle.
16341           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16342                                     DAG.getIntPtrConstant(SplatIdx));
16343       }
16344     }
16345
16346     if (BaseShAmt.getNode()) {
16347       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16348       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16349         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16350       else if (EltVT.bitsLT(MVT::i32))
16351         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16352
16353       switch (Op.getOpcode()) {
16354       default:
16355         llvm_unreachable("Unknown shift opcode!");
16356       case ISD::SHL:
16357         switch (VT.SimpleTy) {
16358         default: return SDValue();
16359         case MVT::v2i64:
16360         case MVT::v4i32:
16361         case MVT::v8i16:
16362         case MVT::v4i64:
16363         case MVT::v8i32:
16364         case MVT::v16i16:
16365         case MVT::v16i32:
16366         case MVT::v8i64:
16367           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16368         }
16369       case ISD::SRA:
16370         switch (VT.SimpleTy) {
16371         default: return SDValue();
16372         case MVT::v4i32:
16373         case MVT::v8i16:
16374         case MVT::v8i32:
16375         case MVT::v16i16:
16376         case MVT::v16i32:
16377         case MVT::v8i64:
16378           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16379         }
16380       case ISD::SRL:
16381         switch (VT.SimpleTy) {
16382         default: return SDValue();
16383         case MVT::v2i64:
16384         case MVT::v4i32:
16385         case MVT::v8i16:
16386         case MVT::v4i64:
16387         case MVT::v8i32:
16388         case MVT::v16i16:
16389         case MVT::v16i32:
16390         case MVT::v8i64:
16391           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16392         }
16393       }
16394     }
16395   }
16396
16397   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16398   if (!Subtarget->is64Bit() &&
16399       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16400       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16401       Amt.getOpcode() == ISD::BITCAST &&
16402       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16403     Amt = Amt.getOperand(0);
16404     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16405                      VT.getVectorNumElements();
16406     std::vector<SDValue> Vals(Ratio);
16407     for (unsigned i = 0; i != Ratio; ++i)
16408       Vals[i] = Amt.getOperand(i);
16409     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16410       for (unsigned j = 0; j != Ratio; ++j)
16411         if (Vals[j] != Amt.getOperand(i + j))
16412           return SDValue();
16413     }
16414     switch (Op.getOpcode()) {
16415     default:
16416       llvm_unreachable("Unknown shift opcode!");
16417     case ISD::SHL:
16418       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16419     case ISD::SRL:
16420       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16421     case ISD::SRA:
16422       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16423     }
16424   }
16425
16426   return SDValue();
16427 }
16428
16429 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16430                           SelectionDAG &DAG) {
16431   MVT VT = Op.getSimpleValueType();
16432   SDLoc dl(Op);
16433   SDValue R = Op.getOperand(0);
16434   SDValue Amt = Op.getOperand(1);
16435
16436   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16437   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16438
16439   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16440     return V;
16441
16442   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16443       return V;
16444
16445   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16446     return Op;
16447
16448   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16449   if (Subtarget->hasInt256()) {
16450     if (Op.getOpcode() == ISD::SRL &&
16451         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16452          VT == MVT::v4i64 || VT == MVT::v8i32))
16453       return Op;
16454     if (Op.getOpcode() == ISD::SHL &&
16455         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16456          VT == MVT::v4i64 || VT == MVT::v8i32))
16457       return Op;
16458     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16459       return Op;
16460   }
16461
16462   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16463   // shifts per-lane and then shuffle the partial results back together.
16464   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16465     // Splat the shift amounts so the scalar shifts above will catch it.
16466     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16467     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16468     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16469     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16470     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16471   }
16472
16473   // If possible, lower this packed shift into a vector multiply instead of
16474   // expanding it into a sequence of scalar shifts.
16475   // Do this only if the vector shift count is a constant build_vector.
16476   if (Op.getOpcode() == ISD::SHL &&
16477       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16478        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16479       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16480     SmallVector<SDValue, 8> Elts;
16481     EVT SVT = VT.getScalarType();
16482     unsigned SVTBits = SVT.getSizeInBits();
16483     const APInt &One = APInt(SVTBits, 1);
16484     unsigned NumElems = VT.getVectorNumElements();
16485
16486     for (unsigned i=0; i !=NumElems; ++i) {
16487       SDValue Op = Amt->getOperand(i);
16488       if (Op->getOpcode() == ISD::UNDEF) {
16489         Elts.push_back(Op);
16490         continue;
16491       }
16492
16493       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16494       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16495       uint64_t ShAmt = C.getZExtValue();
16496       if (ShAmt >= SVTBits) {
16497         Elts.push_back(DAG.getUNDEF(SVT));
16498         continue;
16499       }
16500       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16501     }
16502     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16503     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16504   }
16505
16506   // Lower SHL with variable shift amount.
16507   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16508     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16509
16510     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16511     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16512     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16513     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16514   }
16515
16516   // If possible, lower this shift as a sequence of two shifts by
16517   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16518   // Example:
16519   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16520   //
16521   // Could be rewritten as:
16522   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16523   //
16524   // The advantage is that the two shifts from the example would be
16525   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16526   // the vector shift into four scalar shifts plus four pairs of vector
16527   // insert/extract.
16528   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16529       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16530     unsigned TargetOpcode = X86ISD::MOVSS;
16531     bool CanBeSimplified;
16532     // The splat value for the first packed shift (the 'X' from the example).
16533     SDValue Amt1 = Amt->getOperand(0);
16534     // The splat value for the second packed shift (the 'Y' from the example).
16535     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16536                                         Amt->getOperand(2);
16537
16538     // See if it is possible to replace this node with a sequence of
16539     // two shifts followed by a MOVSS/MOVSD
16540     if (VT == MVT::v4i32) {
16541       // Check if it is legal to use a MOVSS.
16542       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16543                         Amt2 == Amt->getOperand(3);
16544       if (!CanBeSimplified) {
16545         // Otherwise, check if we can still simplify this node using a MOVSD.
16546         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16547                           Amt->getOperand(2) == Amt->getOperand(3);
16548         TargetOpcode = X86ISD::MOVSD;
16549         Amt2 = Amt->getOperand(2);
16550       }
16551     } else {
16552       // Do similar checks for the case where the machine value type
16553       // is MVT::v8i16.
16554       CanBeSimplified = Amt1 == Amt->getOperand(1);
16555       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16556         CanBeSimplified = Amt2 == Amt->getOperand(i);
16557
16558       if (!CanBeSimplified) {
16559         TargetOpcode = X86ISD::MOVSD;
16560         CanBeSimplified = true;
16561         Amt2 = Amt->getOperand(4);
16562         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16563           CanBeSimplified = Amt1 == Amt->getOperand(i);
16564         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16565           CanBeSimplified = Amt2 == Amt->getOperand(j);
16566       }
16567     }
16568
16569     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16570         isa<ConstantSDNode>(Amt2)) {
16571       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16572       EVT CastVT = MVT::v4i32;
16573       SDValue Splat1 =
16574         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16575       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16576       SDValue Splat2 =
16577         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16578       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16579       if (TargetOpcode == X86ISD::MOVSD)
16580         CastVT = MVT::v2i64;
16581       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16582       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16583       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16584                                             BitCast1, DAG);
16585       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16586     }
16587   }
16588
16589   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16590     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16591
16592     // a = a << 5;
16593     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16594     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16595
16596     // Turn 'a' into a mask suitable for VSELECT
16597     SDValue VSelM = DAG.getConstant(0x80, VT);
16598     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16599     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16600
16601     SDValue CM1 = DAG.getConstant(0x0f, VT);
16602     SDValue CM2 = DAG.getConstant(0x3f, VT);
16603
16604     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16605     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16606     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16607     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16608     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16609
16610     // a += a
16611     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16612     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16613     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16614
16615     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16616     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16617     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16618     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16619     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16620
16621     // a += a
16622     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16623     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16624     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16625
16626     // return VSELECT(r, r+r, a);
16627     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16628                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16629     return R;
16630   }
16631
16632   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16633   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16634   // solution better.
16635   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16636     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16637     unsigned ExtOpc =
16638         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16639     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16640     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16641     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16642                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16643   }
16644
16645   // Decompose 256-bit shifts into smaller 128-bit shifts.
16646   if (VT.is256BitVector()) {
16647     unsigned NumElems = VT.getVectorNumElements();
16648     MVT EltVT = VT.getVectorElementType();
16649     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16650
16651     // Extract the two vectors
16652     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16653     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16654
16655     // Recreate the shift amount vectors
16656     SDValue Amt1, Amt2;
16657     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16658       // Constant shift amount
16659       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16660       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16661       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16662
16663       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16664       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16665     } else {
16666       // Variable shift amount
16667       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16668       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16669     }
16670
16671     // Issue new vector shifts for the smaller types
16672     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16673     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16674
16675     // Concatenate the result back
16676     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16677   }
16678
16679   return SDValue();
16680 }
16681
16682 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16683   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16684   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16685   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16686   // has only one use.
16687   SDNode *N = Op.getNode();
16688   SDValue LHS = N->getOperand(0);
16689   SDValue RHS = N->getOperand(1);
16690   unsigned BaseOp = 0;
16691   unsigned Cond = 0;
16692   SDLoc DL(Op);
16693   switch (Op.getOpcode()) {
16694   default: llvm_unreachable("Unknown ovf instruction!");
16695   case ISD::SADDO:
16696     // A subtract of one will be selected as a INC. Note that INC doesn't
16697     // set CF, so we can't do this for UADDO.
16698     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16699       if (C->isOne()) {
16700         BaseOp = X86ISD::INC;
16701         Cond = X86::COND_O;
16702         break;
16703       }
16704     BaseOp = X86ISD::ADD;
16705     Cond = X86::COND_O;
16706     break;
16707   case ISD::UADDO:
16708     BaseOp = X86ISD::ADD;
16709     Cond = X86::COND_B;
16710     break;
16711   case ISD::SSUBO:
16712     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16713     // set CF, so we can't do this for USUBO.
16714     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16715       if (C->isOne()) {
16716         BaseOp = X86ISD::DEC;
16717         Cond = X86::COND_O;
16718         break;
16719       }
16720     BaseOp = X86ISD::SUB;
16721     Cond = X86::COND_O;
16722     break;
16723   case ISD::USUBO:
16724     BaseOp = X86ISD::SUB;
16725     Cond = X86::COND_B;
16726     break;
16727   case ISD::SMULO:
16728     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16729     Cond = X86::COND_O;
16730     break;
16731   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16732     if (N->getValueType(0) == MVT::i8) {
16733       BaseOp = X86ISD::UMUL8;
16734       Cond = X86::COND_O;
16735       break;
16736     }
16737     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16738                                  MVT::i32);
16739     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16740
16741     SDValue SetCC =
16742       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16743                   DAG.getConstant(X86::COND_O, MVT::i32),
16744                   SDValue(Sum.getNode(), 2));
16745
16746     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16747   }
16748   }
16749
16750   // Also sets EFLAGS.
16751   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16752   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16753
16754   SDValue SetCC =
16755     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16756                 DAG.getConstant(Cond, MVT::i32),
16757                 SDValue(Sum.getNode(), 1));
16758
16759   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16760 }
16761
16762 /// Returns true if the operand type is exactly twice the native width, and
16763 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16764 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16765 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16766 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16767   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16768
16769   if (OpWidth == 64)
16770     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16771   else if (OpWidth == 128)
16772     return Subtarget->hasCmpxchg16b();
16773   else
16774     return false;
16775 }
16776
16777 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16778   return needsCmpXchgNb(SI->getValueOperand()->getType());
16779 }
16780
16781 // Note: this turns large loads into lock cmpxchg8b/16b.
16782 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16783 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16784   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16785   return needsCmpXchgNb(PTy->getElementType());
16786 }
16787
16788 TargetLoweringBase::AtomicRMWExpansionKind
16789 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16790   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16791   const Type *MemType = AI->getType();
16792
16793   // If the operand is too big, we must see if cmpxchg8/16b is available
16794   // and default to library calls otherwise.
16795   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16796     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16797                                    : AtomicRMWExpansionKind::None;
16798   }
16799
16800   AtomicRMWInst::BinOp Op = AI->getOperation();
16801   switch (Op) {
16802   default:
16803     llvm_unreachable("Unknown atomic operation");
16804   case AtomicRMWInst::Xchg:
16805   case AtomicRMWInst::Add:
16806   case AtomicRMWInst::Sub:
16807     // It's better to use xadd, xsub or xchg for these in all cases.
16808     return AtomicRMWExpansionKind::None;
16809   case AtomicRMWInst::Or:
16810   case AtomicRMWInst::And:
16811   case AtomicRMWInst::Xor:
16812     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16813     // prefix to a normal instruction for these operations.
16814     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16815                             : AtomicRMWExpansionKind::None;
16816   case AtomicRMWInst::Nand:
16817   case AtomicRMWInst::Max:
16818   case AtomicRMWInst::Min:
16819   case AtomicRMWInst::UMax:
16820   case AtomicRMWInst::UMin:
16821     // These always require a non-trivial set of data operations on x86. We must
16822     // use a cmpxchg loop.
16823     return AtomicRMWExpansionKind::CmpXChg;
16824   }
16825 }
16826
16827 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16828   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16829   // no-sse2). There isn't any reason to disable it if the target processor
16830   // supports it.
16831   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16832 }
16833
16834 LoadInst *
16835 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16836   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16837   const Type *MemType = AI->getType();
16838   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16839   // there is no benefit in turning such RMWs into loads, and it is actually
16840   // harmful as it introduces a mfence.
16841   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16842     return nullptr;
16843
16844   auto Builder = IRBuilder<>(AI);
16845   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16846   auto SynchScope = AI->getSynchScope();
16847   // We must restrict the ordering to avoid generating loads with Release or
16848   // ReleaseAcquire orderings.
16849   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16850   auto Ptr = AI->getPointerOperand();
16851
16852   // Before the load we need a fence. Here is an example lifted from
16853   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16854   // is required:
16855   // Thread 0:
16856   //   x.store(1, relaxed);
16857   //   r1 = y.fetch_add(0, release);
16858   // Thread 1:
16859   //   y.fetch_add(42, acquire);
16860   //   r2 = x.load(relaxed);
16861   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16862   // lowered to just a load without a fence. A mfence flushes the store buffer,
16863   // making the optimization clearly correct.
16864   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16865   // otherwise, we might be able to be more agressive on relaxed idempotent
16866   // rmw. In practice, they do not look useful, so we don't try to be
16867   // especially clever.
16868   if (SynchScope == SingleThread) {
16869     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16870     // the IR level, so we must wrap it in an intrinsic.
16871     return nullptr;
16872   } else if (hasMFENCE(*Subtarget)) {
16873     Function *MFence = llvm::Intrinsic::getDeclaration(M,
16874             Intrinsic::x86_sse2_mfence);
16875     Builder.CreateCall(MFence);
16876   } else {
16877     // FIXME: it might make sense to use a locked operation here but on a
16878     // different cache-line to prevent cache-line bouncing. In practice it
16879     // is probably a small win, and x86 processors without mfence are rare
16880     // enough that we do not bother.
16881     return nullptr;
16882   }
16883
16884   // Finally we can emit the atomic load.
16885   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16886           AI->getType()->getPrimitiveSizeInBits());
16887   Loaded->setAtomic(Order, SynchScope);
16888   AI->replaceAllUsesWith(Loaded);
16889   AI->eraseFromParent();
16890   return Loaded;
16891 }
16892
16893 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16894                                  SelectionDAG &DAG) {
16895   SDLoc dl(Op);
16896   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16897     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16898   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16899     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16900
16901   // The only fence that needs an instruction is a sequentially-consistent
16902   // cross-thread fence.
16903   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16904     if (hasMFENCE(*Subtarget))
16905       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16906
16907     SDValue Chain = Op.getOperand(0);
16908     SDValue Zero = DAG.getConstant(0, MVT::i32);
16909     SDValue Ops[] = {
16910       DAG.getRegister(X86::ESP, MVT::i32), // Base
16911       DAG.getTargetConstant(1, MVT::i8),   // Scale
16912       DAG.getRegister(0, MVT::i32),        // Index
16913       DAG.getTargetConstant(0, MVT::i32),  // Disp
16914       DAG.getRegister(0, MVT::i32),        // Segment.
16915       Zero,
16916       Chain
16917     };
16918     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16919     return SDValue(Res, 0);
16920   }
16921
16922   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16923   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16924 }
16925
16926 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16927                              SelectionDAG &DAG) {
16928   MVT T = Op.getSimpleValueType();
16929   SDLoc DL(Op);
16930   unsigned Reg = 0;
16931   unsigned size = 0;
16932   switch(T.SimpleTy) {
16933   default: llvm_unreachable("Invalid value type!");
16934   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16935   case MVT::i16: Reg = X86::AX;  size = 2; break;
16936   case MVT::i32: Reg = X86::EAX; size = 4; break;
16937   case MVT::i64:
16938     assert(Subtarget->is64Bit() && "Node not type legal!");
16939     Reg = X86::RAX; size = 8;
16940     break;
16941   }
16942   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16943                                   Op.getOperand(2), SDValue());
16944   SDValue Ops[] = { cpIn.getValue(0),
16945                     Op.getOperand(1),
16946                     Op.getOperand(3),
16947                     DAG.getTargetConstant(size, MVT::i8),
16948                     cpIn.getValue(1) };
16949   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16950   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16951   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16952                                            Ops, T, MMO);
16953
16954   SDValue cpOut =
16955     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16956   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16957                                       MVT::i32, cpOut.getValue(2));
16958   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16959                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16960
16961   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16962   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16963   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16964   return SDValue();
16965 }
16966
16967 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16968                             SelectionDAG &DAG) {
16969   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16970   MVT DstVT = Op.getSimpleValueType();
16971
16972   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16973     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16974     if (DstVT != MVT::f64)
16975       // This conversion needs to be expanded.
16976       return SDValue();
16977
16978     SDValue InVec = Op->getOperand(0);
16979     SDLoc dl(Op);
16980     unsigned NumElts = SrcVT.getVectorNumElements();
16981     EVT SVT = SrcVT.getVectorElementType();
16982
16983     // Widen the vector in input in the case of MVT::v2i32.
16984     // Example: from MVT::v2i32 to MVT::v4i32.
16985     SmallVector<SDValue, 16> Elts;
16986     for (unsigned i = 0, e = NumElts; i != e; ++i)
16987       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16988                                  DAG.getIntPtrConstant(i)));
16989
16990     // Explicitly mark the extra elements as Undef.
16991     Elts.append(NumElts, DAG.getUNDEF(SVT));
16992
16993     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16994     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16995     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16996     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16997                        DAG.getIntPtrConstant(0));
16998   }
16999
17000   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17001          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17002   assert((DstVT == MVT::i64 ||
17003           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17004          "Unexpected custom BITCAST");
17005   // i64 <=> MMX conversions are Legal.
17006   if (SrcVT==MVT::i64 && DstVT.isVector())
17007     return Op;
17008   if (DstVT==MVT::i64 && SrcVT.isVector())
17009     return Op;
17010   // MMX <=> MMX conversions are Legal.
17011   if (SrcVT.isVector() && DstVT.isVector())
17012     return Op;
17013   // All other conversions need to be expanded.
17014   return SDValue();
17015 }
17016
17017 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17018                           SelectionDAG &DAG) {
17019   SDNode *Node = Op.getNode();
17020   SDLoc dl(Node);
17021
17022   Op = Op.getOperand(0);
17023   EVT VT = Op.getValueType();
17024   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17025          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17026
17027   unsigned NumElts = VT.getVectorNumElements();
17028   EVT EltVT = VT.getVectorElementType();
17029   unsigned Len = EltVT.getSizeInBits();
17030
17031   // This is the vectorized version of the "best" algorithm from
17032   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17033   // with a minor tweak to use a series of adds + shifts instead of vector
17034   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17035   //
17036   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17037   //  v8i32 => Always profitable
17038   //
17039   // FIXME: There a couple of possible improvements:
17040   //
17041   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17042   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17043   //
17044   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17045          "CTPOP not implemented for this vector element type.");
17046
17047   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17048   // extra legalization.
17049   bool NeedsBitcast = EltVT == MVT::i32;
17050   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17051
17052   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
17053   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
17054   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
17055
17056   // v = v - ((v >> 1) & 0x55555555...)
17057   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
17058   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17059   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17060   if (NeedsBitcast)
17061     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17062
17063   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17064   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17065   if (NeedsBitcast)
17066     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17067
17068   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17069   if (VT != And.getValueType())
17070     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17071   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17072
17073   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17074   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17075   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17076   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
17077   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17078
17079   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17080   if (NeedsBitcast) {
17081     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17082     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17083     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17084   }
17085
17086   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17087   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17088   if (VT != AndRHS.getValueType()) {
17089     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17090     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17091   }
17092   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17093
17094   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17095   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
17096   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17097   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17098   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17099
17100   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17101   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17102   if (NeedsBitcast) {
17103     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17104     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17105   }
17106   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17107   if (VT != And.getValueType())
17108     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17109
17110   // The algorithm mentioned above uses:
17111   //    v = (v * 0x01010101...) >> (Len - 8)
17112   //
17113   // Change it to use vector adds + vector shifts which yield faster results on
17114   // Haswell than using vector integer multiplication.
17115   //
17116   // For i32 elements:
17117   //    v = v + (v >> 8)
17118   //    v = v + (v >> 16)
17119   //
17120   // For i64 elements:
17121   //    v = v + (v >> 8)
17122   //    v = v + (v >> 16)
17123   //    v = v + (v >> 32)
17124   //
17125   Add = And;
17126   SmallVector<SDValue, 8> Csts;
17127   for (unsigned i = 8; i <= Len/2; i *= 2) {
17128     Csts.assign(NumElts, DAG.getConstant(i, EltVT));
17129     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17130     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17131     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17132     Csts.clear();
17133   }
17134
17135   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17136   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
17137   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17138   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17139   if (NeedsBitcast) {
17140     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17141     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17142   }
17143   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17144   if (VT != And.getValueType())
17145     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17146
17147   return And;
17148 }
17149
17150 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17151   SDNode *Node = Op.getNode();
17152   SDLoc dl(Node);
17153   EVT T = Node->getValueType(0);
17154   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17155                               DAG.getConstant(0, T), Node->getOperand(2));
17156   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17157                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17158                        Node->getOperand(0),
17159                        Node->getOperand(1), negOp,
17160                        cast<AtomicSDNode>(Node)->getMemOperand(),
17161                        cast<AtomicSDNode>(Node)->getOrdering(),
17162                        cast<AtomicSDNode>(Node)->getSynchScope());
17163 }
17164
17165 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17166   SDNode *Node = Op.getNode();
17167   SDLoc dl(Node);
17168   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17169
17170   // Convert seq_cst store -> xchg
17171   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17172   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17173   //        (The only way to get a 16-byte store is cmpxchg16b)
17174   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17175   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17176       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17177     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17178                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17179                                  Node->getOperand(0),
17180                                  Node->getOperand(1), Node->getOperand(2),
17181                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17182                                  cast<AtomicSDNode>(Node)->getOrdering(),
17183                                  cast<AtomicSDNode>(Node)->getSynchScope());
17184     return Swap.getValue(1);
17185   }
17186   // Other atomic stores have a simple pattern.
17187   return Op;
17188 }
17189
17190 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17191   EVT VT = Op.getNode()->getSimpleValueType(0);
17192
17193   // Let legalize expand this if it isn't a legal type yet.
17194   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17195     return SDValue();
17196
17197   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17198
17199   unsigned Opc;
17200   bool ExtraOp = false;
17201   switch (Op.getOpcode()) {
17202   default: llvm_unreachable("Invalid code");
17203   case ISD::ADDC: Opc = X86ISD::ADD; break;
17204   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17205   case ISD::SUBC: Opc = X86ISD::SUB; break;
17206   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17207   }
17208
17209   if (!ExtraOp)
17210     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17211                        Op.getOperand(1));
17212   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17213                      Op.getOperand(1), Op.getOperand(2));
17214 }
17215
17216 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17217                             SelectionDAG &DAG) {
17218   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17219
17220   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17221   // which returns the values as { float, float } (in XMM0) or
17222   // { double, double } (which is returned in XMM0, XMM1).
17223   SDLoc dl(Op);
17224   SDValue Arg = Op.getOperand(0);
17225   EVT ArgVT = Arg.getValueType();
17226   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17227
17228   TargetLowering::ArgListTy Args;
17229   TargetLowering::ArgListEntry Entry;
17230
17231   Entry.Node = Arg;
17232   Entry.Ty = ArgTy;
17233   Entry.isSExt = false;
17234   Entry.isZExt = false;
17235   Args.push_back(Entry);
17236
17237   bool isF64 = ArgVT == MVT::f64;
17238   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17239   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17240   // the results are returned via SRet in memory.
17241   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17242   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17243   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17244
17245   Type *RetTy = isF64
17246     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17247     : (Type*)VectorType::get(ArgTy, 4);
17248
17249   TargetLowering::CallLoweringInfo CLI(DAG);
17250   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17251     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17252
17253   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17254
17255   if (isF64)
17256     // Returned in xmm0 and xmm1.
17257     return CallResult.first;
17258
17259   // Returned in bits 0:31 and 32:64 xmm0.
17260   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17261                                CallResult.first, DAG.getIntPtrConstant(0));
17262   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17263                                CallResult.first, DAG.getIntPtrConstant(1));
17264   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17265   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17266 }
17267
17268 /// LowerOperation - Provide custom lowering hooks for some operations.
17269 ///
17270 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17271   switch (Op.getOpcode()) {
17272   default: llvm_unreachable("Should not custom lower this!");
17273   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17274   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17275     return LowerCMP_SWAP(Op, Subtarget, DAG);
17276   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17277   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17278   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17279   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17280   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17281   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17282   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17283   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17284   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17285   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17286   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17287   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17288   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17289   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17290   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17291   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17292   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17293   case ISD::SHL_PARTS:
17294   case ISD::SRA_PARTS:
17295   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17296   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17297   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17298   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17299   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17300   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17301   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17302   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17303   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17304   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17305   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17306   case ISD::FABS:
17307   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17308   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17309   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17310   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17311   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17312   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17313   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17314   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17315   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17316   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17317   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17318   case ISD::INTRINSIC_VOID:
17319   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17320   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17321   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17322   case ISD::FRAME_TO_ARGS_OFFSET:
17323                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17324   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17325   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17326   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17327   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17328   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17329   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17330   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17331   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17332   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17333   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17334   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17335   case ISD::UMUL_LOHI:
17336   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17337   case ISD::SRA:
17338   case ISD::SRL:
17339   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17340   case ISD::SADDO:
17341   case ISD::UADDO:
17342   case ISD::SSUBO:
17343   case ISD::USUBO:
17344   case ISD::SMULO:
17345   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17346   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17347   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17348   case ISD::ADDC:
17349   case ISD::ADDE:
17350   case ISD::SUBC:
17351   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17352   case ISD::ADD:                return LowerADD(Op, DAG);
17353   case ISD::SUB:                return LowerSUB(Op, DAG);
17354   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17355   }
17356 }
17357
17358 /// ReplaceNodeResults - Replace a node with an illegal result type
17359 /// with a new node built out of custom code.
17360 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17361                                            SmallVectorImpl<SDValue>&Results,
17362                                            SelectionDAG &DAG) const {
17363   SDLoc dl(N);
17364   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17365   switch (N->getOpcode()) {
17366   default:
17367     llvm_unreachable("Do not know how to custom type legalize this operation!");
17368   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17369   case X86ISD::FMINC:
17370   case X86ISD::FMIN:
17371   case X86ISD::FMAXC:
17372   case X86ISD::FMAX: {
17373     EVT VT = N->getValueType(0);
17374     if (VT != MVT::v2f32)
17375       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17376     SDValue UNDEF = DAG.getUNDEF(VT);
17377     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17378                               N->getOperand(0), UNDEF);
17379     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17380                               N->getOperand(1), UNDEF);
17381     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17382     return;
17383   }
17384   case ISD::SIGN_EXTEND_INREG:
17385   case ISD::ADDC:
17386   case ISD::ADDE:
17387   case ISD::SUBC:
17388   case ISD::SUBE:
17389     // We don't want to expand or promote these.
17390     return;
17391   case ISD::SDIV:
17392   case ISD::UDIV:
17393   case ISD::SREM:
17394   case ISD::UREM:
17395   case ISD::SDIVREM:
17396   case ISD::UDIVREM: {
17397     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17398     Results.push_back(V);
17399     return;
17400   }
17401   case ISD::FP_TO_SINT:
17402   case ISD::FP_TO_UINT: {
17403     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17404
17405     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17406       return;
17407
17408     std::pair<SDValue,SDValue> Vals =
17409         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17410     SDValue FIST = Vals.first, StackSlot = Vals.second;
17411     if (FIST.getNode()) {
17412       EVT VT = N->getValueType(0);
17413       // Return a load from the stack slot.
17414       if (StackSlot.getNode())
17415         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17416                                       MachinePointerInfo(),
17417                                       false, false, false, 0));
17418       else
17419         Results.push_back(FIST);
17420     }
17421     return;
17422   }
17423   case ISD::UINT_TO_FP: {
17424     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17425     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17426         N->getValueType(0) != MVT::v2f32)
17427       return;
17428     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17429                                  N->getOperand(0));
17430     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17431                                      MVT::f64);
17432     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17433     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17434                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17435     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17436     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17437     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17438     return;
17439   }
17440   case ISD::FP_ROUND: {
17441     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17442         return;
17443     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17444     Results.push_back(V);
17445     return;
17446   }
17447   case ISD::INTRINSIC_W_CHAIN: {
17448     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17449     switch (IntNo) {
17450     default : llvm_unreachable("Do not know how to custom type "
17451                                "legalize this intrinsic operation!");
17452     case Intrinsic::x86_rdtsc:
17453       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17454                                      Results);
17455     case Intrinsic::x86_rdtscp:
17456       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17457                                      Results);
17458     case Intrinsic::x86_rdpmc:
17459       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17460     }
17461   }
17462   case ISD::READCYCLECOUNTER: {
17463     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17464                                    Results);
17465   }
17466   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17467     EVT T = N->getValueType(0);
17468     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17469     bool Regs64bit = T == MVT::i128;
17470     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17471     SDValue cpInL, cpInH;
17472     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17473                         DAG.getConstant(0, HalfT));
17474     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17475                         DAG.getConstant(1, HalfT));
17476     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17477                              Regs64bit ? X86::RAX : X86::EAX,
17478                              cpInL, SDValue());
17479     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17480                              Regs64bit ? X86::RDX : X86::EDX,
17481                              cpInH, cpInL.getValue(1));
17482     SDValue swapInL, swapInH;
17483     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17484                           DAG.getConstant(0, HalfT));
17485     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17486                           DAG.getConstant(1, HalfT));
17487     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17488                                Regs64bit ? X86::RBX : X86::EBX,
17489                                swapInL, cpInH.getValue(1));
17490     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17491                                Regs64bit ? X86::RCX : X86::ECX,
17492                                swapInH, swapInL.getValue(1));
17493     SDValue Ops[] = { swapInH.getValue(0),
17494                       N->getOperand(1),
17495                       swapInH.getValue(1) };
17496     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17497     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17498     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17499                                   X86ISD::LCMPXCHG8_DAG;
17500     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17501     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17502                                         Regs64bit ? X86::RAX : X86::EAX,
17503                                         HalfT, Result.getValue(1));
17504     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17505                                         Regs64bit ? X86::RDX : X86::EDX,
17506                                         HalfT, cpOutL.getValue(2));
17507     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17508
17509     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17510                                         MVT::i32, cpOutH.getValue(2));
17511     SDValue Success =
17512         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17513                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17514     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17515
17516     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17517     Results.push_back(Success);
17518     Results.push_back(EFLAGS.getValue(1));
17519     return;
17520   }
17521   case ISD::ATOMIC_SWAP:
17522   case ISD::ATOMIC_LOAD_ADD:
17523   case ISD::ATOMIC_LOAD_SUB:
17524   case ISD::ATOMIC_LOAD_AND:
17525   case ISD::ATOMIC_LOAD_OR:
17526   case ISD::ATOMIC_LOAD_XOR:
17527   case ISD::ATOMIC_LOAD_NAND:
17528   case ISD::ATOMIC_LOAD_MIN:
17529   case ISD::ATOMIC_LOAD_MAX:
17530   case ISD::ATOMIC_LOAD_UMIN:
17531   case ISD::ATOMIC_LOAD_UMAX:
17532   case ISD::ATOMIC_LOAD: {
17533     // Delegate to generic TypeLegalization. Situations we can really handle
17534     // should have already been dealt with by AtomicExpandPass.cpp.
17535     break;
17536   }
17537   case ISD::BITCAST: {
17538     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17539     EVT DstVT = N->getValueType(0);
17540     EVT SrcVT = N->getOperand(0)->getValueType(0);
17541
17542     if (SrcVT != MVT::f64 ||
17543         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17544       return;
17545
17546     unsigned NumElts = DstVT.getVectorNumElements();
17547     EVT SVT = DstVT.getVectorElementType();
17548     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17549     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17550                                    MVT::v2f64, N->getOperand(0));
17551     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17552
17553     if (ExperimentalVectorWideningLegalization) {
17554       // If we are legalizing vectors by widening, we already have the desired
17555       // legal vector type, just return it.
17556       Results.push_back(ToVecInt);
17557       return;
17558     }
17559
17560     SmallVector<SDValue, 8> Elts;
17561     for (unsigned i = 0, e = NumElts; i != e; ++i)
17562       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17563                                    ToVecInt, DAG.getIntPtrConstant(i)));
17564
17565     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17566   }
17567   }
17568 }
17569
17570 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17571   switch (Opcode) {
17572   default: return nullptr;
17573   case X86ISD::BSF:                return "X86ISD::BSF";
17574   case X86ISD::BSR:                return "X86ISD::BSR";
17575   case X86ISD::SHLD:               return "X86ISD::SHLD";
17576   case X86ISD::SHRD:               return "X86ISD::SHRD";
17577   case X86ISD::FAND:               return "X86ISD::FAND";
17578   case X86ISD::FANDN:              return "X86ISD::FANDN";
17579   case X86ISD::FOR:                return "X86ISD::FOR";
17580   case X86ISD::FXOR:               return "X86ISD::FXOR";
17581   case X86ISD::FSRL:               return "X86ISD::FSRL";
17582   case X86ISD::FILD:               return "X86ISD::FILD";
17583   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17584   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17585   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17586   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17587   case X86ISD::FLD:                return "X86ISD::FLD";
17588   case X86ISD::FST:                return "X86ISD::FST";
17589   case X86ISD::CALL:               return "X86ISD::CALL";
17590   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17591   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17592   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17593   case X86ISD::BT:                 return "X86ISD::BT";
17594   case X86ISD::CMP:                return "X86ISD::CMP";
17595   case X86ISD::COMI:               return "X86ISD::COMI";
17596   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17597   case X86ISD::CMPM:               return "X86ISD::CMPM";
17598   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17599   case X86ISD::SETCC:              return "X86ISD::SETCC";
17600   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17601   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17602   case X86ISD::CMOV:               return "X86ISD::CMOV";
17603   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17604   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17605   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17606   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17607   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17608   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17609   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17610   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17611   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17612   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17613   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17614   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17615   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17616   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17617   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17618   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17619   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17620   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17621   case X86ISD::HADD:               return "X86ISD::HADD";
17622   case X86ISD::HSUB:               return "X86ISD::HSUB";
17623   case X86ISD::FHADD:              return "X86ISD::FHADD";
17624   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17625   case X86ISD::UMAX:               return "X86ISD::UMAX";
17626   case X86ISD::UMIN:               return "X86ISD::UMIN";
17627   case X86ISD::SMAX:               return "X86ISD::SMAX";
17628   case X86ISD::SMIN:               return "X86ISD::SMIN";
17629   case X86ISD::FMAX:               return "X86ISD::FMAX";
17630   case X86ISD::FMIN:               return "X86ISD::FMIN";
17631   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17632   case X86ISD::FMINC:              return "X86ISD::FMINC";
17633   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17634   case X86ISD::FRCP:               return "X86ISD::FRCP";
17635   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17636   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17637   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17638   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17639   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17640   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17641   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17642   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17643   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17644   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17645   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17646   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17647   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17648   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17649   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17650   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17651   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17652   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17653   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17654   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17655   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17656   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17657   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17658   case X86ISD::VSHL:               return "X86ISD::VSHL";
17659   case X86ISD::VSRL:               return "X86ISD::VSRL";
17660   case X86ISD::VSRA:               return "X86ISD::VSRA";
17661   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17662   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17663   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17664   case X86ISD::CMPP:               return "X86ISD::CMPP";
17665   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17666   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17667   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17668   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17669   case X86ISD::ADD:                return "X86ISD::ADD";
17670   case X86ISD::SUB:                return "X86ISD::SUB";
17671   case X86ISD::ADC:                return "X86ISD::ADC";
17672   case X86ISD::SBB:                return "X86ISD::SBB";
17673   case X86ISD::SMUL:               return "X86ISD::SMUL";
17674   case X86ISD::UMUL:               return "X86ISD::UMUL";
17675   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17676   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17677   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17678   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17679   case X86ISD::INC:                return "X86ISD::INC";
17680   case X86ISD::DEC:                return "X86ISD::DEC";
17681   case X86ISD::OR:                 return "X86ISD::OR";
17682   case X86ISD::XOR:                return "X86ISD::XOR";
17683   case X86ISD::AND:                return "X86ISD::AND";
17684   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17685   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17686   case X86ISD::PTEST:              return "X86ISD::PTEST";
17687   case X86ISD::TESTP:              return "X86ISD::TESTP";
17688   case X86ISD::TESTM:              return "X86ISD::TESTM";
17689   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17690   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17691   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17692   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17693   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17694   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17695   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17696   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17697   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17698   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17699   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17700   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17701   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17702   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17703   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17704   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17705   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17706   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17707   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17708   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17709   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17710   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17711   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17712   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17713   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17714   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17715   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17716   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17717   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17718   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17719   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17720   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17721   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17722   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17723   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17724   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17725   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17726   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17727   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17728   case X86ISD::SAHF:               return "X86ISD::SAHF";
17729   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17730   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17731   case X86ISD::FMADD:              return "X86ISD::FMADD";
17732   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17733   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17734   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17735   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17736   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17737   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17738   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17739   case X86ISD::XTEST:              return "X86ISD::XTEST";
17740   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
17741   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
17742   case X86ISD::SELECT:             return "X86ISD::SELECT";
17743   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
17744   case X86ISD::RCP28:              return "X86ISD::RCP28";
17745   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
17746   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
17747   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
17748   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
17749   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
17750   }
17751 }
17752
17753 // isLegalAddressingMode - Return true if the addressing mode represented
17754 // by AM is legal for this target, for a load/store of the specified type.
17755 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17756                                               Type *Ty) const {
17757   // X86 supports extremely general addressing modes.
17758   CodeModel::Model M = getTargetMachine().getCodeModel();
17759   Reloc::Model R = getTargetMachine().getRelocationModel();
17760
17761   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17762   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17763     return false;
17764
17765   if (AM.BaseGV) {
17766     unsigned GVFlags =
17767       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17768
17769     // If a reference to this global requires an extra load, we can't fold it.
17770     if (isGlobalStubReference(GVFlags))
17771       return false;
17772
17773     // If BaseGV requires a register for the PIC base, we cannot also have a
17774     // BaseReg specified.
17775     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17776       return false;
17777
17778     // If lower 4G is not available, then we must use rip-relative addressing.
17779     if ((M != CodeModel::Small || R != Reloc::Static) &&
17780         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17781       return false;
17782   }
17783
17784   switch (AM.Scale) {
17785   case 0:
17786   case 1:
17787   case 2:
17788   case 4:
17789   case 8:
17790     // These scales always work.
17791     break;
17792   case 3:
17793   case 5:
17794   case 9:
17795     // These scales are formed with basereg+scalereg.  Only accept if there is
17796     // no basereg yet.
17797     if (AM.HasBaseReg)
17798       return false;
17799     break;
17800   default:  // Other stuff never works.
17801     return false;
17802   }
17803
17804   return true;
17805 }
17806
17807 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17808   unsigned Bits = Ty->getScalarSizeInBits();
17809
17810   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17811   // particularly cheaper than those without.
17812   if (Bits == 8)
17813     return false;
17814
17815   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17816   // variable shifts just as cheap as scalar ones.
17817   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17818     return false;
17819
17820   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17821   // fully general vector.
17822   return true;
17823 }
17824
17825 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17826   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17827     return false;
17828   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17829   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17830   return NumBits1 > NumBits2;
17831 }
17832
17833 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17834   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17835     return false;
17836
17837   if (!isTypeLegal(EVT::getEVT(Ty1)))
17838     return false;
17839
17840   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17841
17842   // Assuming the caller doesn't have a zeroext or signext return parameter,
17843   // truncation all the way down to i1 is valid.
17844   return true;
17845 }
17846
17847 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17848   return isInt<32>(Imm);
17849 }
17850
17851 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17852   // Can also use sub to handle negated immediates.
17853   return isInt<32>(Imm);
17854 }
17855
17856 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17857   if (!VT1.isInteger() || !VT2.isInteger())
17858     return false;
17859   unsigned NumBits1 = VT1.getSizeInBits();
17860   unsigned NumBits2 = VT2.getSizeInBits();
17861   return NumBits1 > NumBits2;
17862 }
17863
17864 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17865   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17866   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17867 }
17868
17869 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17870   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17871   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17872 }
17873
17874 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17875   EVT VT1 = Val.getValueType();
17876   if (isZExtFree(VT1, VT2))
17877     return true;
17878
17879   if (Val.getOpcode() != ISD::LOAD)
17880     return false;
17881
17882   if (!VT1.isSimple() || !VT1.isInteger() ||
17883       !VT2.isSimple() || !VT2.isInteger())
17884     return false;
17885
17886   switch (VT1.getSimpleVT().SimpleTy) {
17887   default: break;
17888   case MVT::i8:
17889   case MVT::i16:
17890   case MVT::i32:
17891     // X86 has 8, 16, and 32-bit zero-extending loads.
17892     return true;
17893   }
17894
17895   return false;
17896 }
17897
17898 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
17899
17900 bool
17901 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17902   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17903     return false;
17904
17905   VT = VT.getScalarType();
17906
17907   if (!VT.isSimple())
17908     return false;
17909
17910   switch (VT.getSimpleVT().SimpleTy) {
17911   case MVT::f32:
17912   case MVT::f64:
17913     return true;
17914   default:
17915     break;
17916   }
17917
17918   return false;
17919 }
17920
17921 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17922   // i16 instructions are longer (0x66 prefix) and potentially slower.
17923   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17924 }
17925
17926 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17927 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17928 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17929 /// are assumed to be legal.
17930 bool
17931 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17932                                       EVT VT) const {
17933   if (!VT.isSimple())
17934     return false;
17935
17936   // Very little shuffling can be done for 64-bit vectors right now.
17937   if (VT.getSizeInBits() == 64)
17938     return false;
17939
17940   // We only care that the types being shuffled are legal. The lowering can
17941   // handle any possible shuffle mask that results.
17942   return isTypeLegal(VT.getSimpleVT());
17943 }
17944
17945 bool
17946 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17947                                           EVT VT) const {
17948   // Just delegate to the generic legality, clear masks aren't special.
17949   return isShuffleMaskLegal(Mask, VT);
17950 }
17951
17952 //===----------------------------------------------------------------------===//
17953 //                           X86 Scheduler Hooks
17954 //===----------------------------------------------------------------------===//
17955
17956 /// Utility function to emit xbegin specifying the start of an RTM region.
17957 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17958                                      const TargetInstrInfo *TII) {
17959   DebugLoc DL = MI->getDebugLoc();
17960
17961   const BasicBlock *BB = MBB->getBasicBlock();
17962   MachineFunction::iterator I = MBB;
17963   ++I;
17964
17965   // For the v = xbegin(), we generate
17966   //
17967   // thisMBB:
17968   //  xbegin sinkMBB
17969   //
17970   // mainMBB:
17971   //  eax = -1
17972   //
17973   // sinkMBB:
17974   //  v = eax
17975
17976   MachineBasicBlock *thisMBB = MBB;
17977   MachineFunction *MF = MBB->getParent();
17978   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17979   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17980   MF->insert(I, mainMBB);
17981   MF->insert(I, sinkMBB);
17982
17983   // Transfer the remainder of BB and its successor edges to sinkMBB.
17984   sinkMBB->splice(sinkMBB->begin(), MBB,
17985                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17986   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17987
17988   // thisMBB:
17989   //  xbegin sinkMBB
17990   //  # fallthrough to mainMBB
17991   //  # abortion to sinkMBB
17992   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17993   thisMBB->addSuccessor(mainMBB);
17994   thisMBB->addSuccessor(sinkMBB);
17995
17996   // mainMBB:
17997   //  EAX = -1
17998   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17999   mainMBB->addSuccessor(sinkMBB);
18000
18001   // sinkMBB:
18002   // EAX is live into the sinkMBB
18003   sinkMBB->addLiveIn(X86::EAX);
18004   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18005           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18006     .addReg(X86::EAX);
18007
18008   MI->eraseFromParent();
18009   return sinkMBB;
18010 }
18011
18012 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18013 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18014 // in the .td file.
18015 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18016                                        const TargetInstrInfo *TII) {
18017   unsigned Opc;
18018   switch (MI->getOpcode()) {
18019   default: llvm_unreachable("illegal opcode!");
18020   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18021   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18022   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18023   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18024   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18025   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18026   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18027   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18028   }
18029
18030   DebugLoc dl = MI->getDebugLoc();
18031   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18032
18033   unsigned NumArgs = MI->getNumOperands();
18034   for (unsigned i = 1; i < NumArgs; ++i) {
18035     MachineOperand &Op = MI->getOperand(i);
18036     if (!(Op.isReg() && Op.isImplicit()))
18037       MIB.addOperand(Op);
18038   }
18039   if (MI->hasOneMemOperand())
18040     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18041
18042   BuildMI(*BB, MI, dl,
18043     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18044     .addReg(X86::XMM0);
18045
18046   MI->eraseFromParent();
18047   return BB;
18048 }
18049
18050 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18051 // defs in an instruction pattern
18052 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18053                                        const TargetInstrInfo *TII) {
18054   unsigned Opc;
18055   switch (MI->getOpcode()) {
18056   default: llvm_unreachable("illegal opcode!");
18057   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18058   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18059   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18060   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18061   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18062   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18063   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18064   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18065   }
18066
18067   DebugLoc dl = MI->getDebugLoc();
18068   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18069
18070   unsigned NumArgs = MI->getNumOperands(); // remove the results
18071   for (unsigned i = 1; i < NumArgs; ++i) {
18072     MachineOperand &Op = MI->getOperand(i);
18073     if (!(Op.isReg() && Op.isImplicit()))
18074       MIB.addOperand(Op);
18075   }
18076   if (MI->hasOneMemOperand())
18077     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18078
18079   BuildMI(*BB, MI, dl,
18080     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18081     .addReg(X86::ECX);
18082
18083   MI->eraseFromParent();
18084   return BB;
18085 }
18086
18087 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18088                                       const X86Subtarget *Subtarget) {
18089   DebugLoc dl = MI->getDebugLoc();
18090   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18091   // Address into RAX/EAX, other two args into ECX, EDX.
18092   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18093   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18094   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18095   for (int i = 0; i < X86::AddrNumOperands; ++i)
18096     MIB.addOperand(MI->getOperand(i));
18097
18098   unsigned ValOps = X86::AddrNumOperands;
18099   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18100     .addReg(MI->getOperand(ValOps).getReg());
18101   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18102     .addReg(MI->getOperand(ValOps+1).getReg());
18103
18104   // The instruction doesn't actually take any operands though.
18105   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18106
18107   MI->eraseFromParent(); // The pseudo is gone now.
18108   return BB;
18109 }
18110
18111 MachineBasicBlock *
18112 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18113                                                  MachineBasicBlock *MBB) const {
18114   // Emit va_arg instruction on X86-64.
18115
18116   // Operands to this pseudo-instruction:
18117   // 0  ) Output        : destination address (reg)
18118   // 1-5) Input         : va_list address (addr, i64mem)
18119   // 6  ) ArgSize       : Size (in bytes) of vararg type
18120   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18121   // 8  ) Align         : Alignment of type
18122   // 9  ) EFLAGS (implicit-def)
18123
18124   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18125   static_assert(X86::AddrNumOperands == 5,
18126                 "VAARG_64 assumes 5 address operands");
18127
18128   unsigned DestReg = MI->getOperand(0).getReg();
18129   MachineOperand &Base = MI->getOperand(1);
18130   MachineOperand &Scale = MI->getOperand(2);
18131   MachineOperand &Index = MI->getOperand(3);
18132   MachineOperand &Disp = MI->getOperand(4);
18133   MachineOperand &Segment = MI->getOperand(5);
18134   unsigned ArgSize = MI->getOperand(6).getImm();
18135   unsigned ArgMode = MI->getOperand(7).getImm();
18136   unsigned Align = MI->getOperand(8).getImm();
18137
18138   // Memory Reference
18139   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18140   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18141   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18142
18143   // Machine Information
18144   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18145   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18146   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18147   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18148   DebugLoc DL = MI->getDebugLoc();
18149
18150   // struct va_list {
18151   //   i32   gp_offset
18152   //   i32   fp_offset
18153   //   i64   overflow_area (address)
18154   //   i64   reg_save_area (address)
18155   // }
18156   // sizeof(va_list) = 24
18157   // alignment(va_list) = 8
18158
18159   unsigned TotalNumIntRegs = 6;
18160   unsigned TotalNumXMMRegs = 8;
18161   bool UseGPOffset = (ArgMode == 1);
18162   bool UseFPOffset = (ArgMode == 2);
18163   unsigned MaxOffset = TotalNumIntRegs * 8 +
18164                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18165
18166   /* Align ArgSize to a multiple of 8 */
18167   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18168   bool NeedsAlign = (Align > 8);
18169
18170   MachineBasicBlock *thisMBB = MBB;
18171   MachineBasicBlock *overflowMBB;
18172   MachineBasicBlock *offsetMBB;
18173   MachineBasicBlock *endMBB;
18174
18175   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18176   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18177   unsigned OffsetReg = 0;
18178
18179   if (!UseGPOffset && !UseFPOffset) {
18180     // If we only pull from the overflow region, we don't create a branch.
18181     // We don't need to alter control flow.
18182     OffsetDestReg = 0; // unused
18183     OverflowDestReg = DestReg;
18184
18185     offsetMBB = nullptr;
18186     overflowMBB = thisMBB;
18187     endMBB = thisMBB;
18188   } else {
18189     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18190     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18191     // If not, pull from overflow_area. (branch to overflowMBB)
18192     //
18193     //       thisMBB
18194     //         |     .
18195     //         |        .
18196     //     offsetMBB   overflowMBB
18197     //         |        .
18198     //         |     .
18199     //        endMBB
18200
18201     // Registers for the PHI in endMBB
18202     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18203     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18204
18205     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18206     MachineFunction *MF = MBB->getParent();
18207     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18208     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18209     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18210
18211     MachineFunction::iterator MBBIter = MBB;
18212     ++MBBIter;
18213
18214     // Insert the new basic blocks
18215     MF->insert(MBBIter, offsetMBB);
18216     MF->insert(MBBIter, overflowMBB);
18217     MF->insert(MBBIter, endMBB);
18218
18219     // Transfer the remainder of MBB and its successor edges to endMBB.
18220     endMBB->splice(endMBB->begin(), thisMBB,
18221                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18222     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18223
18224     // Make offsetMBB and overflowMBB successors of thisMBB
18225     thisMBB->addSuccessor(offsetMBB);
18226     thisMBB->addSuccessor(overflowMBB);
18227
18228     // endMBB is a successor of both offsetMBB and overflowMBB
18229     offsetMBB->addSuccessor(endMBB);
18230     overflowMBB->addSuccessor(endMBB);
18231
18232     // Load the offset value into a register
18233     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18234     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18235       .addOperand(Base)
18236       .addOperand(Scale)
18237       .addOperand(Index)
18238       .addDisp(Disp, UseFPOffset ? 4 : 0)
18239       .addOperand(Segment)
18240       .setMemRefs(MMOBegin, MMOEnd);
18241
18242     // Check if there is enough room left to pull this argument.
18243     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18244       .addReg(OffsetReg)
18245       .addImm(MaxOffset + 8 - ArgSizeA8);
18246
18247     // Branch to "overflowMBB" if offset >= max
18248     // Fall through to "offsetMBB" otherwise
18249     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18250       .addMBB(overflowMBB);
18251   }
18252
18253   // In offsetMBB, emit code to use the reg_save_area.
18254   if (offsetMBB) {
18255     assert(OffsetReg != 0);
18256
18257     // Read the reg_save_area address.
18258     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18259     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18260       .addOperand(Base)
18261       .addOperand(Scale)
18262       .addOperand(Index)
18263       .addDisp(Disp, 16)
18264       .addOperand(Segment)
18265       .setMemRefs(MMOBegin, MMOEnd);
18266
18267     // Zero-extend the offset
18268     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18269       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18270         .addImm(0)
18271         .addReg(OffsetReg)
18272         .addImm(X86::sub_32bit);
18273
18274     // Add the offset to the reg_save_area to get the final address.
18275     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18276       .addReg(OffsetReg64)
18277       .addReg(RegSaveReg);
18278
18279     // Compute the offset for the next argument
18280     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18281     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18282       .addReg(OffsetReg)
18283       .addImm(UseFPOffset ? 16 : 8);
18284
18285     // Store it back into the va_list.
18286     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18287       .addOperand(Base)
18288       .addOperand(Scale)
18289       .addOperand(Index)
18290       .addDisp(Disp, UseFPOffset ? 4 : 0)
18291       .addOperand(Segment)
18292       .addReg(NextOffsetReg)
18293       .setMemRefs(MMOBegin, MMOEnd);
18294
18295     // Jump to endMBB
18296     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18297       .addMBB(endMBB);
18298   }
18299
18300   //
18301   // Emit code to use overflow area
18302   //
18303
18304   // Load the overflow_area address into a register.
18305   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18306   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18307     .addOperand(Base)
18308     .addOperand(Scale)
18309     .addOperand(Index)
18310     .addDisp(Disp, 8)
18311     .addOperand(Segment)
18312     .setMemRefs(MMOBegin, MMOEnd);
18313
18314   // If we need to align it, do so. Otherwise, just copy the address
18315   // to OverflowDestReg.
18316   if (NeedsAlign) {
18317     // Align the overflow address
18318     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18319     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18320
18321     // aligned_addr = (addr + (align-1)) & ~(align-1)
18322     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18323       .addReg(OverflowAddrReg)
18324       .addImm(Align-1);
18325
18326     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18327       .addReg(TmpReg)
18328       .addImm(~(uint64_t)(Align-1));
18329   } else {
18330     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18331       .addReg(OverflowAddrReg);
18332   }
18333
18334   // Compute the next overflow address after this argument.
18335   // (the overflow address should be kept 8-byte aligned)
18336   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18337   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18338     .addReg(OverflowDestReg)
18339     .addImm(ArgSizeA8);
18340
18341   // Store the new overflow address.
18342   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18343     .addOperand(Base)
18344     .addOperand(Scale)
18345     .addOperand(Index)
18346     .addDisp(Disp, 8)
18347     .addOperand(Segment)
18348     .addReg(NextAddrReg)
18349     .setMemRefs(MMOBegin, MMOEnd);
18350
18351   // If we branched, emit the PHI to the front of endMBB.
18352   if (offsetMBB) {
18353     BuildMI(*endMBB, endMBB->begin(), DL,
18354             TII->get(X86::PHI), DestReg)
18355       .addReg(OffsetDestReg).addMBB(offsetMBB)
18356       .addReg(OverflowDestReg).addMBB(overflowMBB);
18357   }
18358
18359   // Erase the pseudo instruction
18360   MI->eraseFromParent();
18361
18362   return endMBB;
18363 }
18364
18365 MachineBasicBlock *
18366 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18367                                                  MachineInstr *MI,
18368                                                  MachineBasicBlock *MBB) const {
18369   // Emit code to save XMM registers to the stack. The ABI says that the
18370   // number of registers to save is given in %al, so it's theoretically
18371   // possible to do an indirect jump trick to avoid saving all of them,
18372   // however this code takes a simpler approach and just executes all
18373   // of the stores if %al is non-zero. It's less code, and it's probably
18374   // easier on the hardware branch predictor, and stores aren't all that
18375   // expensive anyway.
18376
18377   // Create the new basic blocks. One block contains all the XMM stores,
18378   // and one block is the final destination regardless of whether any
18379   // stores were performed.
18380   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18381   MachineFunction *F = MBB->getParent();
18382   MachineFunction::iterator MBBIter = MBB;
18383   ++MBBIter;
18384   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18385   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18386   F->insert(MBBIter, XMMSaveMBB);
18387   F->insert(MBBIter, EndMBB);
18388
18389   // Transfer the remainder of MBB and its successor edges to EndMBB.
18390   EndMBB->splice(EndMBB->begin(), MBB,
18391                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18392   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18393
18394   // The original block will now fall through to the XMM save block.
18395   MBB->addSuccessor(XMMSaveMBB);
18396   // The XMMSaveMBB will fall through to the end block.
18397   XMMSaveMBB->addSuccessor(EndMBB);
18398
18399   // Now add the instructions.
18400   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18401   DebugLoc DL = MI->getDebugLoc();
18402
18403   unsigned CountReg = MI->getOperand(0).getReg();
18404   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18405   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18406
18407   if (!Subtarget->isTargetWin64()) {
18408     // If %al is 0, branch around the XMM save block.
18409     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18410     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18411     MBB->addSuccessor(EndMBB);
18412   }
18413
18414   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18415   // that was just emitted, but clearly shouldn't be "saved".
18416   assert((MI->getNumOperands() <= 3 ||
18417           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18418           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18419          && "Expected last argument to be EFLAGS");
18420   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18421   // In the XMM save block, save all the XMM argument registers.
18422   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18423     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18424     MachineMemOperand *MMO =
18425       F->getMachineMemOperand(
18426           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18427         MachineMemOperand::MOStore,
18428         /*Size=*/16, /*Align=*/16);
18429     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18430       .addFrameIndex(RegSaveFrameIndex)
18431       .addImm(/*Scale=*/1)
18432       .addReg(/*IndexReg=*/0)
18433       .addImm(/*Disp=*/Offset)
18434       .addReg(/*Segment=*/0)
18435       .addReg(MI->getOperand(i).getReg())
18436       .addMemOperand(MMO);
18437   }
18438
18439   MI->eraseFromParent();   // The pseudo instruction is gone now.
18440
18441   return EndMBB;
18442 }
18443
18444 // The EFLAGS operand of SelectItr might be missing a kill marker
18445 // because there were multiple uses of EFLAGS, and ISel didn't know
18446 // which to mark. Figure out whether SelectItr should have had a
18447 // kill marker, and set it if it should. Returns the correct kill
18448 // marker value.
18449 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18450                                      MachineBasicBlock* BB,
18451                                      const TargetRegisterInfo* TRI) {
18452   // Scan forward through BB for a use/def of EFLAGS.
18453   MachineBasicBlock::iterator miI(std::next(SelectItr));
18454   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18455     const MachineInstr& mi = *miI;
18456     if (mi.readsRegister(X86::EFLAGS))
18457       return false;
18458     if (mi.definesRegister(X86::EFLAGS))
18459       break; // Should have kill-flag - update below.
18460   }
18461
18462   // If we hit the end of the block, check whether EFLAGS is live into a
18463   // successor.
18464   if (miI == BB->end()) {
18465     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18466                                           sEnd = BB->succ_end();
18467          sItr != sEnd; ++sItr) {
18468       MachineBasicBlock* succ = *sItr;
18469       if (succ->isLiveIn(X86::EFLAGS))
18470         return false;
18471     }
18472   }
18473
18474   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18475   // out. SelectMI should have a kill flag on EFLAGS.
18476   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18477   return true;
18478 }
18479
18480 MachineBasicBlock *
18481 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18482                                      MachineBasicBlock *BB) const {
18483   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18484   DebugLoc DL = MI->getDebugLoc();
18485
18486   // To "insert" a SELECT_CC instruction, we actually have to insert the
18487   // diamond control-flow pattern.  The incoming instruction knows the
18488   // destination vreg to set, the condition code register to branch on, the
18489   // true/false values to select between, and a branch opcode to use.
18490   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18491   MachineFunction::iterator It = BB;
18492   ++It;
18493
18494   //  thisMBB:
18495   //  ...
18496   //   TrueVal = ...
18497   //   cmpTY ccX, r1, r2
18498   //   bCC copy1MBB
18499   //   fallthrough --> copy0MBB
18500   MachineBasicBlock *thisMBB = BB;
18501   MachineFunction *F = BB->getParent();
18502
18503   // We also lower double CMOVs:
18504   //   (CMOV (CMOV F, T, cc1), T, cc2)
18505   // to two successives branches.  For that, we look for another CMOV as the
18506   // following instruction.
18507   //
18508   // Without this, we would add a PHI between the two jumps, which ends up
18509   // creating a few copies all around. For instance, for
18510   //
18511   //    (sitofp (zext (fcmp une)))
18512   //
18513   // we would generate:
18514   //
18515   //         ucomiss %xmm1, %xmm0
18516   //         movss  <1.0f>, %xmm0
18517   //         movaps  %xmm0, %xmm1
18518   //         jne     .LBB5_2
18519   //         xorps   %xmm1, %xmm1
18520   // .LBB5_2:
18521   //         jp      .LBB5_4
18522   //         movaps  %xmm1, %xmm0
18523   // .LBB5_4:
18524   //         retq
18525   //
18526   // because this custom-inserter would have generated:
18527   //
18528   //   A
18529   //   | \
18530   //   |  B
18531   //   | /
18532   //   C
18533   //   | \
18534   //   |  D
18535   //   | /
18536   //   E
18537   //
18538   // A: X = ...; Y = ...
18539   // B: empty
18540   // C: Z = PHI [X, A], [Y, B]
18541   // D: empty
18542   // E: PHI [X, C], [Z, D]
18543   //
18544   // If we lower both CMOVs in a single step, we can instead generate:
18545   //
18546   //   A
18547   //   | \
18548   //   |  C
18549   //   | /|
18550   //   |/ |
18551   //   |  |
18552   //   |  D
18553   //   | /
18554   //   E
18555   //
18556   // A: X = ...; Y = ...
18557   // D: empty
18558   // E: PHI [X, A], [X, C], [Y, D]
18559   //
18560   // Which, in our sitofp/fcmp example, gives us something like:
18561   //
18562   //         ucomiss %xmm1, %xmm0
18563   //         movss  <1.0f>, %xmm0
18564   //         jne     .LBB5_4
18565   //         jp      .LBB5_4
18566   //         xorps   %xmm0, %xmm0
18567   // .LBB5_4:
18568   //         retq
18569   //
18570   MachineInstr *NextCMOV = nullptr;
18571   MachineBasicBlock::iterator NextMIIt =
18572       std::next(MachineBasicBlock::iterator(MI));
18573   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18574       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18575       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18576     NextCMOV = &*NextMIIt;
18577
18578   MachineBasicBlock *jcc1MBB = nullptr;
18579
18580   // If we have a double CMOV, we lower it to two successive branches to
18581   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18582   if (NextCMOV) {
18583     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18584     F->insert(It, jcc1MBB);
18585     jcc1MBB->addLiveIn(X86::EFLAGS);
18586   }
18587
18588   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18589   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18590   F->insert(It, copy0MBB);
18591   F->insert(It, sinkMBB);
18592
18593   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18594   // live into the sink and copy blocks.
18595   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18596
18597   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18598   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18599       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18600     copy0MBB->addLiveIn(X86::EFLAGS);
18601     sinkMBB->addLiveIn(X86::EFLAGS);
18602   }
18603
18604   // Transfer the remainder of BB and its successor edges to sinkMBB.
18605   sinkMBB->splice(sinkMBB->begin(), BB,
18606                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18607   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18608
18609   // Add the true and fallthrough blocks as its successors.
18610   if (NextCMOV) {
18611     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18612     BB->addSuccessor(jcc1MBB);
18613
18614     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18615     // jump to the sinkMBB.
18616     jcc1MBB->addSuccessor(copy0MBB);
18617     jcc1MBB->addSuccessor(sinkMBB);
18618   } else {
18619     BB->addSuccessor(copy0MBB);
18620   }
18621
18622   // The true block target of the first (or only) branch is always sinkMBB.
18623   BB->addSuccessor(sinkMBB);
18624
18625   // Create the conditional branch instruction.
18626   unsigned Opc =
18627     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18628   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18629
18630   if (NextCMOV) {
18631     unsigned Opc2 = X86::GetCondBranchFromCond(
18632         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18633     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18634   }
18635
18636   //  copy0MBB:
18637   //   %FalseValue = ...
18638   //   # fallthrough to sinkMBB
18639   copy0MBB->addSuccessor(sinkMBB);
18640
18641   //  sinkMBB:
18642   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18643   //  ...
18644   MachineInstrBuilder MIB =
18645       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18646               MI->getOperand(0).getReg())
18647           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18648           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18649
18650   // If we have a double CMOV, the second Jcc provides the same incoming
18651   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18652   if (NextCMOV) {
18653     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18654     // Copy the PHI result to the register defined by the second CMOV.
18655     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18656             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18657         .addReg(MI->getOperand(0).getReg());
18658     NextCMOV->eraseFromParent();
18659   }
18660
18661   MI->eraseFromParent();   // The pseudo instruction is gone now.
18662   return sinkMBB;
18663 }
18664
18665 MachineBasicBlock *
18666 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18667                                         MachineBasicBlock *BB) const {
18668   MachineFunction *MF = BB->getParent();
18669   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18670   DebugLoc DL = MI->getDebugLoc();
18671   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18672
18673   assert(MF->shouldSplitStack());
18674
18675   const bool Is64Bit = Subtarget->is64Bit();
18676   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18677
18678   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18679   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18680
18681   // BB:
18682   //  ... [Till the alloca]
18683   // If stacklet is not large enough, jump to mallocMBB
18684   //
18685   // bumpMBB:
18686   //  Allocate by subtracting from RSP
18687   //  Jump to continueMBB
18688   //
18689   // mallocMBB:
18690   //  Allocate by call to runtime
18691   //
18692   // continueMBB:
18693   //  ...
18694   //  [rest of original BB]
18695   //
18696
18697   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18698   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18699   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18700
18701   MachineRegisterInfo &MRI = MF->getRegInfo();
18702   const TargetRegisterClass *AddrRegClass =
18703     getRegClassFor(getPointerTy());
18704
18705   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18706     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18707     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18708     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18709     sizeVReg = MI->getOperand(1).getReg(),
18710     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18711
18712   MachineFunction::iterator MBBIter = BB;
18713   ++MBBIter;
18714
18715   MF->insert(MBBIter, bumpMBB);
18716   MF->insert(MBBIter, mallocMBB);
18717   MF->insert(MBBIter, continueMBB);
18718
18719   continueMBB->splice(continueMBB->begin(), BB,
18720                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18721   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18722
18723   // Add code to the main basic block to check if the stack limit has been hit,
18724   // and if so, jump to mallocMBB otherwise to bumpMBB.
18725   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18726   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18727     .addReg(tmpSPVReg).addReg(sizeVReg);
18728   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18729     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18730     .addReg(SPLimitVReg);
18731   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18732
18733   // bumpMBB simply decreases the stack pointer, since we know the current
18734   // stacklet has enough space.
18735   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18736     .addReg(SPLimitVReg);
18737   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18738     .addReg(SPLimitVReg);
18739   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18740
18741   // Calls into a routine in libgcc to allocate more space from the heap.
18742   const uint32_t *RegMask =
18743       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
18744   if (IsLP64) {
18745     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18746       .addReg(sizeVReg);
18747     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18748       .addExternalSymbol("__morestack_allocate_stack_space")
18749       .addRegMask(RegMask)
18750       .addReg(X86::RDI, RegState::Implicit)
18751       .addReg(X86::RAX, RegState::ImplicitDefine);
18752   } else if (Is64Bit) {
18753     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18754       .addReg(sizeVReg);
18755     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18756       .addExternalSymbol("__morestack_allocate_stack_space")
18757       .addRegMask(RegMask)
18758       .addReg(X86::EDI, RegState::Implicit)
18759       .addReg(X86::EAX, RegState::ImplicitDefine);
18760   } else {
18761     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18762       .addImm(12);
18763     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18764     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18765       .addExternalSymbol("__morestack_allocate_stack_space")
18766       .addRegMask(RegMask)
18767       .addReg(X86::EAX, RegState::ImplicitDefine);
18768   }
18769
18770   if (!Is64Bit)
18771     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18772       .addImm(16);
18773
18774   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18775     .addReg(IsLP64 ? X86::RAX : X86::EAX);
18776   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18777
18778   // Set up the CFG correctly.
18779   BB->addSuccessor(bumpMBB);
18780   BB->addSuccessor(mallocMBB);
18781   mallocMBB->addSuccessor(continueMBB);
18782   bumpMBB->addSuccessor(continueMBB);
18783
18784   // Take care of the PHI nodes.
18785   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18786           MI->getOperand(0).getReg())
18787     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18788     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18789
18790   // Delete the original pseudo instruction.
18791   MI->eraseFromParent();
18792
18793   // And we're done.
18794   return continueMBB;
18795 }
18796
18797 MachineBasicBlock *
18798 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18799                                         MachineBasicBlock *BB) const {
18800   DebugLoc DL = MI->getDebugLoc();
18801
18802   assert(!Subtarget->isTargetMachO());
18803
18804   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
18805
18806   MI->eraseFromParent();   // The pseudo instruction is gone now.
18807   return BB;
18808 }
18809
18810 MachineBasicBlock *
18811 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18812                                       MachineBasicBlock *BB) const {
18813   // This is pretty easy.  We're taking the value that we received from
18814   // our load from the relocation, sticking it in either RDI (x86-64)
18815   // or EAX and doing an indirect call.  The return value will then
18816   // be in the normal return register.
18817   MachineFunction *F = BB->getParent();
18818   const X86InstrInfo *TII = Subtarget->getInstrInfo();
18819   DebugLoc DL = MI->getDebugLoc();
18820
18821   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18822   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18823
18824   // Get a register mask for the lowered call.
18825   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18826   // proper register mask.
18827   const uint32_t *RegMask =
18828       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
18829   if (Subtarget->is64Bit()) {
18830     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18831                                       TII->get(X86::MOV64rm), X86::RDI)
18832     .addReg(X86::RIP)
18833     .addImm(0).addReg(0)
18834     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18835                       MI->getOperand(3).getTargetFlags())
18836     .addReg(0);
18837     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18838     addDirectMem(MIB, X86::RDI);
18839     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18840   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18841     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18842                                       TII->get(X86::MOV32rm), X86::EAX)
18843     .addReg(0)
18844     .addImm(0).addReg(0)
18845     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18846                       MI->getOperand(3).getTargetFlags())
18847     .addReg(0);
18848     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18849     addDirectMem(MIB, X86::EAX);
18850     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18851   } else {
18852     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18853                                       TII->get(X86::MOV32rm), X86::EAX)
18854     .addReg(TII->getGlobalBaseReg(F))
18855     .addImm(0).addReg(0)
18856     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18857                       MI->getOperand(3).getTargetFlags())
18858     .addReg(0);
18859     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18860     addDirectMem(MIB, X86::EAX);
18861     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18862   }
18863
18864   MI->eraseFromParent(); // The pseudo instruction is gone now.
18865   return BB;
18866 }
18867
18868 MachineBasicBlock *
18869 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18870                                     MachineBasicBlock *MBB) const {
18871   DebugLoc DL = MI->getDebugLoc();
18872   MachineFunction *MF = MBB->getParent();
18873   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18874   MachineRegisterInfo &MRI = MF->getRegInfo();
18875
18876   const BasicBlock *BB = MBB->getBasicBlock();
18877   MachineFunction::iterator I = MBB;
18878   ++I;
18879
18880   // Memory Reference
18881   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18882   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18883
18884   unsigned DstReg;
18885   unsigned MemOpndSlot = 0;
18886
18887   unsigned CurOp = 0;
18888
18889   DstReg = MI->getOperand(CurOp++).getReg();
18890   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18891   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18892   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18893   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18894
18895   MemOpndSlot = CurOp;
18896
18897   MVT PVT = getPointerTy();
18898   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18899          "Invalid Pointer Size!");
18900
18901   // For v = setjmp(buf), we generate
18902   //
18903   // thisMBB:
18904   //  buf[LabelOffset] = restoreMBB
18905   //  SjLjSetup restoreMBB
18906   //
18907   // mainMBB:
18908   //  v_main = 0
18909   //
18910   // sinkMBB:
18911   //  v = phi(main, restore)
18912   //
18913   // restoreMBB:
18914   //  if base pointer being used, load it from frame
18915   //  v_restore = 1
18916
18917   MachineBasicBlock *thisMBB = MBB;
18918   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18919   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18920   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18921   MF->insert(I, mainMBB);
18922   MF->insert(I, sinkMBB);
18923   MF->push_back(restoreMBB);
18924
18925   MachineInstrBuilder MIB;
18926
18927   // Transfer the remainder of BB and its successor edges to sinkMBB.
18928   sinkMBB->splice(sinkMBB->begin(), MBB,
18929                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18930   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18931
18932   // thisMBB:
18933   unsigned PtrStoreOpc = 0;
18934   unsigned LabelReg = 0;
18935   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18936   Reloc::Model RM = MF->getTarget().getRelocationModel();
18937   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18938                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18939
18940   // Prepare IP either in reg or imm.
18941   if (!UseImmLabel) {
18942     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18943     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18944     LabelReg = MRI.createVirtualRegister(PtrRC);
18945     if (Subtarget->is64Bit()) {
18946       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18947               .addReg(X86::RIP)
18948               .addImm(0)
18949               .addReg(0)
18950               .addMBB(restoreMBB)
18951               .addReg(0);
18952     } else {
18953       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18954       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18955               .addReg(XII->getGlobalBaseReg(MF))
18956               .addImm(0)
18957               .addReg(0)
18958               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18959               .addReg(0);
18960     }
18961   } else
18962     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18963   // Store IP
18964   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18965   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18966     if (i == X86::AddrDisp)
18967       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18968     else
18969       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18970   }
18971   if (!UseImmLabel)
18972     MIB.addReg(LabelReg);
18973   else
18974     MIB.addMBB(restoreMBB);
18975   MIB.setMemRefs(MMOBegin, MMOEnd);
18976   // Setup
18977   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18978           .addMBB(restoreMBB);
18979
18980   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18981   MIB.addRegMask(RegInfo->getNoPreservedMask());
18982   thisMBB->addSuccessor(mainMBB);
18983   thisMBB->addSuccessor(restoreMBB);
18984
18985   // mainMBB:
18986   //  EAX = 0
18987   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18988   mainMBB->addSuccessor(sinkMBB);
18989
18990   // sinkMBB:
18991   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18992           TII->get(X86::PHI), DstReg)
18993     .addReg(mainDstReg).addMBB(mainMBB)
18994     .addReg(restoreDstReg).addMBB(restoreMBB);
18995
18996   // restoreMBB:
18997   if (RegInfo->hasBasePointer(*MF)) {
18998     const bool Uses64BitFramePtr =
18999         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19000     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19001     X86FI->setRestoreBasePointer(MF);
19002     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19003     unsigned BasePtr = RegInfo->getBaseRegister();
19004     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19005     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19006                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19007       .setMIFlag(MachineInstr::FrameSetup);
19008   }
19009   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19010   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19011   restoreMBB->addSuccessor(sinkMBB);
19012
19013   MI->eraseFromParent();
19014   return sinkMBB;
19015 }
19016
19017 MachineBasicBlock *
19018 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19019                                      MachineBasicBlock *MBB) const {
19020   DebugLoc DL = MI->getDebugLoc();
19021   MachineFunction *MF = MBB->getParent();
19022   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19023   MachineRegisterInfo &MRI = MF->getRegInfo();
19024
19025   // Memory Reference
19026   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19027   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19028
19029   MVT PVT = getPointerTy();
19030   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19031          "Invalid Pointer Size!");
19032
19033   const TargetRegisterClass *RC =
19034     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19035   unsigned Tmp = MRI.createVirtualRegister(RC);
19036   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19037   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19038   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19039   unsigned SP = RegInfo->getStackRegister();
19040
19041   MachineInstrBuilder MIB;
19042
19043   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19044   const int64_t SPOffset = 2 * PVT.getStoreSize();
19045
19046   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19047   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19048
19049   // Reload FP
19050   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19051   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19052     MIB.addOperand(MI->getOperand(i));
19053   MIB.setMemRefs(MMOBegin, MMOEnd);
19054   // Reload IP
19055   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19056   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19057     if (i == X86::AddrDisp)
19058       MIB.addDisp(MI->getOperand(i), LabelOffset);
19059     else
19060       MIB.addOperand(MI->getOperand(i));
19061   }
19062   MIB.setMemRefs(MMOBegin, MMOEnd);
19063   // Reload SP
19064   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19065   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19066     if (i == X86::AddrDisp)
19067       MIB.addDisp(MI->getOperand(i), SPOffset);
19068     else
19069       MIB.addOperand(MI->getOperand(i));
19070   }
19071   MIB.setMemRefs(MMOBegin, MMOEnd);
19072   // Jump
19073   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19074
19075   MI->eraseFromParent();
19076   return MBB;
19077 }
19078
19079 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19080 // accumulator loops. Writing back to the accumulator allows the coalescer
19081 // to remove extra copies in the loop.
19082 MachineBasicBlock *
19083 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19084                                  MachineBasicBlock *MBB) const {
19085   MachineOperand &AddendOp = MI->getOperand(3);
19086
19087   // Bail out early if the addend isn't a register - we can't switch these.
19088   if (!AddendOp.isReg())
19089     return MBB;
19090
19091   MachineFunction &MF = *MBB->getParent();
19092   MachineRegisterInfo &MRI = MF.getRegInfo();
19093
19094   // Check whether the addend is defined by a PHI:
19095   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19096   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19097   if (!AddendDef.isPHI())
19098     return MBB;
19099
19100   // Look for the following pattern:
19101   // loop:
19102   //   %addend = phi [%entry, 0], [%loop, %result]
19103   //   ...
19104   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19105
19106   // Replace with:
19107   //   loop:
19108   //   %addend = phi [%entry, 0], [%loop, %result]
19109   //   ...
19110   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19111
19112   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19113     assert(AddendDef.getOperand(i).isReg());
19114     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19115     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19116     if (&PHISrcInst == MI) {
19117       // Found a matching instruction.
19118       unsigned NewFMAOpc = 0;
19119       switch (MI->getOpcode()) {
19120         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19121         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19122         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19123         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19124         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19125         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19126         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19127         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19128         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19129         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19130         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19131         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19132         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19133         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19134         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19135         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19136         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19137         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19138         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19139         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19140
19141         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19142         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19143         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19144         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19145         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19146         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19147         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19148         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19149         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19150         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19151         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19152         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19153         default: llvm_unreachable("Unrecognized FMA variant.");
19154       }
19155
19156       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19157       MachineInstrBuilder MIB =
19158         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19159         .addOperand(MI->getOperand(0))
19160         .addOperand(MI->getOperand(3))
19161         .addOperand(MI->getOperand(2))
19162         .addOperand(MI->getOperand(1));
19163       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19164       MI->eraseFromParent();
19165     }
19166   }
19167
19168   return MBB;
19169 }
19170
19171 MachineBasicBlock *
19172 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19173                                                MachineBasicBlock *BB) const {
19174   switch (MI->getOpcode()) {
19175   default: llvm_unreachable("Unexpected instr type to insert");
19176   case X86::TAILJMPd64:
19177   case X86::TAILJMPr64:
19178   case X86::TAILJMPm64:
19179   case X86::TAILJMPd64_REX:
19180   case X86::TAILJMPr64_REX:
19181   case X86::TAILJMPm64_REX:
19182     llvm_unreachable("TAILJMP64 would not be touched here.");
19183   case X86::TCRETURNdi64:
19184   case X86::TCRETURNri64:
19185   case X86::TCRETURNmi64:
19186     return BB;
19187   case X86::WIN_ALLOCA:
19188     return EmitLoweredWinAlloca(MI, BB);
19189   case X86::SEG_ALLOCA_32:
19190   case X86::SEG_ALLOCA_64:
19191     return EmitLoweredSegAlloca(MI, BB);
19192   case X86::TLSCall_32:
19193   case X86::TLSCall_64:
19194     return EmitLoweredTLSCall(MI, BB);
19195   case X86::CMOV_GR8:
19196   case X86::CMOV_FR32:
19197   case X86::CMOV_FR64:
19198   case X86::CMOV_V4F32:
19199   case X86::CMOV_V2F64:
19200   case X86::CMOV_V2I64:
19201   case X86::CMOV_V8F32:
19202   case X86::CMOV_V4F64:
19203   case X86::CMOV_V4I64:
19204   case X86::CMOV_V16F32:
19205   case X86::CMOV_V8F64:
19206   case X86::CMOV_V8I64:
19207   case X86::CMOV_GR16:
19208   case X86::CMOV_GR32:
19209   case X86::CMOV_RFP32:
19210   case X86::CMOV_RFP64:
19211   case X86::CMOV_RFP80:
19212     return EmitLoweredSelect(MI, BB);
19213
19214   case X86::FP32_TO_INT16_IN_MEM:
19215   case X86::FP32_TO_INT32_IN_MEM:
19216   case X86::FP32_TO_INT64_IN_MEM:
19217   case X86::FP64_TO_INT16_IN_MEM:
19218   case X86::FP64_TO_INT32_IN_MEM:
19219   case X86::FP64_TO_INT64_IN_MEM:
19220   case X86::FP80_TO_INT16_IN_MEM:
19221   case X86::FP80_TO_INT32_IN_MEM:
19222   case X86::FP80_TO_INT64_IN_MEM: {
19223     MachineFunction *F = BB->getParent();
19224     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19225     DebugLoc DL = MI->getDebugLoc();
19226
19227     // Change the floating point control register to use "round towards zero"
19228     // mode when truncating to an integer value.
19229     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19230     addFrameReference(BuildMI(*BB, MI, DL,
19231                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19232
19233     // Load the old value of the high byte of the control word...
19234     unsigned OldCW =
19235       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19236     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19237                       CWFrameIdx);
19238
19239     // Set the high part to be round to zero...
19240     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19241       .addImm(0xC7F);
19242
19243     // Reload the modified control word now...
19244     addFrameReference(BuildMI(*BB, MI, DL,
19245                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19246
19247     // Restore the memory image of control word to original value
19248     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19249       .addReg(OldCW);
19250
19251     // Get the X86 opcode to use.
19252     unsigned Opc;
19253     switch (MI->getOpcode()) {
19254     default: llvm_unreachable("illegal opcode!");
19255     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19256     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19257     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19258     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19259     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19260     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19261     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19262     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19263     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19264     }
19265
19266     X86AddressMode AM;
19267     MachineOperand &Op = MI->getOperand(0);
19268     if (Op.isReg()) {
19269       AM.BaseType = X86AddressMode::RegBase;
19270       AM.Base.Reg = Op.getReg();
19271     } else {
19272       AM.BaseType = X86AddressMode::FrameIndexBase;
19273       AM.Base.FrameIndex = Op.getIndex();
19274     }
19275     Op = MI->getOperand(1);
19276     if (Op.isImm())
19277       AM.Scale = Op.getImm();
19278     Op = MI->getOperand(2);
19279     if (Op.isImm())
19280       AM.IndexReg = Op.getImm();
19281     Op = MI->getOperand(3);
19282     if (Op.isGlobal()) {
19283       AM.GV = Op.getGlobal();
19284     } else {
19285       AM.Disp = Op.getImm();
19286     }
19287     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19288                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19289
19290     // Reload the original control word now.
19291     addFrameReference(BuildMI(*BB, MI, DL,
19292                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19293
19294     MI->eraseFromParent();   // The pseudo instruction is gone now.
19295     return BB;
19296   }
19297     // String/text processing lowering.
19298   case X86::PCMPISTRM128REG:
19299   case X86::VPCMPISTRM128REG:
19300   case X86::PCMPISTRM128MEM:
19301   case X86::VPCMPISTRM128MEM:
19302   case X86::PCMPESTRM128REG:
19303   case X86::VPCMPESTRM128REG:
19304   case X86::PCMPESTRM128MEM:
19305   case X86::VPCMPESTRM128MEM:
19306     assert(Subtarget->hasSSE42() &&
19307            "Target must have SSE4.2 or AVX features enabled");
19308     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19309
19310   // String/text processing lowering.
19311   case X86::PCMPISTRIREG:
19312   case X86::VPCMPISTRIREG:
19313   case X86::PCMPISTRIMEM:
19314   case X86::VPCMPISTRIMEM:
19315   case X86::PCMPESTRIREG:
19316   case X86::VPCMPESTRIREG:
19317   case X86::PCMPESTRIMEM:
19318   case X86::VPCMPESTRIMEM:
19319     assert(Subtarget->hasSSE42() &&
19320            "Target must have SSE4.2 or AVX features enabled");
19321     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19322
19323   // Thread synchronization.
19324   case X86::MONITOR:
19325     return EmitMonitor(MI, BB, Subtarget);
19326
19327   // xbegin
19328   case X86::XBEGIN:
19329     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19330
19331   case X86::VASTART_SAVE_XMM_REGS:
19332     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19333
19334   case X86::VAARG_64:
19335     return EmitVAARG64WithCustomInserter(MI, BB);
19336
19337   case X86::EH_SjLj_SetJmp32:
19338   case X86::EH_SjLj_SetJmp64:
19339     return emitEHSjLjSetJmp(MI, BB);
19340
19341   case X86::EH_SjLj_LongJmp32:
19342   case X86::EH_SjLj_LongJmp64:
19343     return emitEHSjLjLongJmp(MI, BB);
19344
19345   case TargetOpcode::STATEPOINT:
19346     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19347     // this point in the process.  We diverge later.
19348     return emitPatchPoint(MI, BB);
19349
19350   case TargetOpcode::STACKMAP:
19351   case TargetOpcode::PATCHPOINT:
19352     return emitPatchPoint(MI, BB);
19353
19354   case X86::VFMADDPDr213r:
19355   case X86::VFMADDPSr213r:
19356   case X86::VFMADDSDr213r:
19357   case X86::VFMADDSSr213r:
19358   case X86::VFMSUBPDr213r:
19359   case X86::VFMSUBPSr213r:
19360   case X86::VFMSUBSDr213r:
19361   case X86::VFMSUBSSr213r:
19362   case X86::VFNMADDPDr213r:
19363   case X86::VFNMADDPSr213r:
19364   case X86::VFNMADDSDr213r:
19365   case X86::VFNMADDSSr213r:
19366   case X86::VFNMSUBPDr213r:
19367   case X86::VFNMSUBPSr213r:
19368   case X86::VFNMSUBSDr213r:
19369   case X86::VFNMSUBSSr213r:
19370   case X86::VFMADDSUBPDr213r:
19371   case X86::VFMADDSUBPSr213r:
19372   case X86::VFMSUBADDPDr213r:
19373   case X86::VFMSUBADDPSr213r:
19374   case X86::VFMADDPDr213rY:
19375   case X86::VFMADDPSr213rY:
19376   case X86::VFMSUBPDr213rY:
19377   case X86::VFMSUBPSr213rY:
19378   case X86::VFNMADDPDr213rY:
19379   case X86::VFNMADDPSr213rY:
19380   case X86::VFNMSUBPDr213rY:
19381   case X86::VFNMSUBPSr213rY:
19382   case X86::VFMADDSUBPDr213rY:
19383   case X86::VFMADDSUBPSr213rY:
19384   case X86::VFMSUBADDPDr213rY:
19385   case X86::VFMSUBADDPSr213rY:
19386     return emitFMA3Instr(MI, BB);
19387   }
19388 }
19389
19390 //===----------------------------------------------------------------------===//
19391 //                           X86 Optimization Hooks
19392 //===----------------------------------------------------------------------===//
19393
19394 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19395                                                       APInt &KnownZero,
19396                                                       APInt &KnownOne,
19397                                                       const SelectionDAG &DAG,
19398                                                       unsigned Depth) const {
19399   unsigned BitWidth = KnownZero.getBitWidth();
19400   unsigned Opc = Op.getOpcode();
19401   assert((Opc >= ISD::BUILTIN_OP_END ||
19402           Opc == ISD::INTRINSIC_WO_CHAIN ||
19403           Opc == ISD::INTRINSIC_W_CHAIN ||
19404           Opc == ISD::INTRINSIC_VOID) &&
19405          "Should use MaskedValueIsZero if you don't know whether Op"
19406          " is a target node!");
19407
19408   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19409   switch (Opc) {
19410   default: break;
19411   case X86ISD::ADD:
19412   case X86ISD::SUB:
19413   case X86ISD::ADC:
19414   case X86ISD::SBB:
19415   case X86ISD::SMUL:
19416   case X86ISD::UMUL:
19417   case X86ISD::INC:
19418   case X86ISD::DEC:
19419   case X86ISD::OR:
19420   case X86ISD::XOR:
19421   case X86ISD::AND:
19422     // These nodes' second result is a boolean.
19423     if (Op.getResNo() == 0)
19424       break;
19425     // Fallthrough
19426   case X86ISD::SETCC:
19427     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19428     break;
19429   case ISD::INTRINSIC_WO_CHAIN: {
19430     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19431     unsigned NumLoBits = 0;
19432     switch (IntId) {
19433     default: break;
19434     case Intrinsic::x86_sse_movmsk_ps:
19435     case Intrinsic::x86_avx_movmsk_ps_256:
19436     case Intrinsic::x86_sse2_movmsk_pd:
19437     case Intrinsic::x86_avx_movmsk_pd_256:
19438     case Intrinsic::x86_mmx_pmovmskb:
19439     case Intrinsic::x86_sse2_pmovmskb_128:
19440     case Intrinsic::x86_avx2_pmovmskb: {
19441       // High bits of movmskp{s|d}, pmovmskb are known zero.
19442       switch (IntId) {
19443         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19444         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19445         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19446         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19447         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19448         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19449         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19450         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19451       }
19452       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19453       break;
19454     }
19455     }
19456     break;
19457   }
19458   }
19459 }
19460
19461 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19462   SDValue Op,
19463   const SelectionDAG &,
19464   unsigned Depth) const {
19465   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19466   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19467     return Op.getValueType().getScalarType().getSizeInBits();
19468
19469   // Fallback case.
19470   return 1;
19471 }
19472
19473 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19474 /// node is a GlobalAddress + offset.
19475 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19476                                        const GlobalValue* &GA,
19477                                        int64_t &Offset) const {
19478   if (N->getOpcode() == X86ISD::Wrapper) {
19479     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19480       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19481       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19482       return true;
19483     }
19484   }
19485   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19486 }
19487
19488 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19489 /// same as extracting the high 128-bit part of 256-bit vector and then
19490 /// inserting the result into the low part of a new 256-bit vector
19491 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19492   EVT VT = SVOp->getValueType(0);
19493   unsigned NumElems = VT.getVectorNumElements();
19494
19495   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19496   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19497     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19498         SVOp->getMaskElt(j) >= 0)
19499       return false;
19500
19501   return true;
19502 }
19503
19504 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19505 /// same as extracting the low 128-bit part of 256-bit vector and then
19506 /// inserting the result into the high part of a new 256-bit vector
19507 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19508   EVT VT = SVOp->getValueType(0);
19509   unsigned NumElems = VT.getVectorNumElements();
19510
19511   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19512   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19513     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19514         SVOp->getMaskElt(j) >= 0)
19515       return false;
19516
19517   return true;
19518 }
19519
19520 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19521 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19522                                         TargetLowering::DAGCombinerInfo &DCI,
19523                                         const X86Subtarget* Subtarget) {
19524   SDLoc dl(N);
19525   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19526   SDValue V1 = SVOp->getOperand(0);
19527   SDValue V2 = SVOp->getOperand(1);
19528   EVT VT = SVOp->getValueType(0);
19529   unsigned NumElems = VT.getVectorNumElements();
19530
19531   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19532       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19533     //
19534     //                   0,0,0,...
19535     //                      |
19536     //    V      UNDEF    BUILD_VECTOR    UNDEF
19537     //     \      /           \           /
19538     //  CONCAT_VECTOR         CONCAT_VECTOR
19539     //         \                  /
19540     //          \                /
19541     //          RESULT: V + zero extended
19542     //
19543     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19544         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19545         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19546       return SDValue();
19547
19548     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19549       return SDValue();
19550
19551     // To match the shuffle mask, the first half of the mask should
19552     // be exactly the first vector, and all the rest a splat with the
19553     // first element of the second one.
19554     for (unsigned i = 0; i != NumElems/2; ++i)
19555       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19556           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19557         return SDValue();
19558
19559     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19560     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19561       if (Ld->hasNUsesOfValue(1, 0)) {
19562         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19563         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19564         SDValue ResNode =
19565           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19566                                   Ld->getMemoryVT(),
19567                                   Ld->getPointerInfo(),
19568                                   Ld->getAlignment(),
19569                                   false/*isVolatile*/, true/*ReadMem*/,
19570                                   false/*WriteMem*/);
19571
19572         // Make sure the newly-created LOAD is in the same position as Ld in
19573         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19574         // and update uses of Ld's output chain to use the TokenFactor.
19575         if (Ld->hasAnyUseOfValue(1)) {
19576           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19577                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19578           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19579           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19580                                  SDValue(ResNode.getNode(), 1));
19581         }
19582
19583         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19584       }
19585     }
19586
19587     // Emit a zeroed vector and insert the desired subvector on its
19588     // first half.
19589     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19590     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19591     return DCI.CombineTo(N, InsV);
19592   }
19593
19594   //===--------------------------------------------------------------------===//
19595   // Combine some shuffles into subvector extracts and inserts:
19596   //
19597
19598   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19599   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19600     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19601     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19602     return DCI.CombineTo(N, InsV);
19603   }
19604
19605   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19606   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19607     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19608     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19609     return DCI.CombineTo(N, InsV);
19610   }
19611
19612   return SDValue();
19613 }
19614
19615 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19616 /// possible.
19617 ///
19618 /// This is the leaf of the recursive combinine below. When we have found some
19619 /// chain of single-use x86 shuffle instructions and accumulated the combined
19620 /// shuffle mask represented by them, this will try to pattern match that mask
19621 /// into either a single instruction if there is a special purpose instruction
19622 /// for this operation, or into a PSHUFB instruction which is a fully general
19623 /// instruction but should only be used to replace chains over a certain depth.
19624 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19625                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19626                                    TargetLowering::DAGCombinerInfo &DCI,
19627                                    const X86Subtarget *Subtarget) {
19628   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19629
19630   // Find the operand that enters the chain. Note that multiple uses are OK
19631   // here, we're not going to remove the operand we find.
19632   SDValue Input = Op.getOperand(0);
19633   while (Input.getOpcode() == ISD::BITCAST)
19634     Input = Input.getOperand(0);
19635
19636   MVT VT = Input.getSimpleValueType();
19637   MVT RootVT = Root.getSimpleValueType();
19638   SDLoc DL(Root);
19639
19640   // Just remove no-op shuffle masks.
19641   if (Mask.size() == 1) {
19642     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19643                   /*AddTo*/ true);
19644     return true;
19645   }
19646
19647   // Use the float domain if the operand type is a floating point type.
19648   bool FloatDomain = VT.isFloatingPoint();
19649
19650   // For floating point shuffles, we don't have free copies in the shuffle
19651   // instructions or the ability to load as part of the instruction, so
19652   // canonicalize their shuffles to UNPCK or MOV variants.
19653   //
19654   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19655   // vectors because it can have a load folded into it that UNPCK cannot. This
19656   // doesn't preclude something switching to the shorter encoding post-RA.
19657   //
19658   // FIXME: Should teach these routines about AVX vector widths.
19659   if (FloatDomain && VT.getSizeInBits() == 128) {
19660     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19661       bool Lo = Mask.equals({0, 0});
19662       unsigned Shuffle;
19663       MVT ShuffleVT;
19664       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19665       // is no slower than UNPCKLPD but has the option to fold the input operand
19666       // into even an unaligned memory load.
19667       if (Lo && Subtarget->hasSSE3()) {
19668         Shuffle = X86ISD::MOVDDUP;
19669         ShuffleVT = MVT::v2f64;
19670       } else {
19671         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19672         // than the UNPCK variants.
19673         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19674         ShuffleVT = MVT::v4f32;
19675       }
19676       if (Depth == 1 && Root->getOpcode() == Shuffle)
19677         return false; // Nothing to do!
19678       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19679       DCI.AddToWorklist(Op.getNode());
19680       if (Shuffle == X86ISD::MOVDDUP)
19681         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19682       else
19683         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19684       DCI.AddToWorklist(Op.getNode());
19685       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19686                     /*AddTo*/ true);
19687       return true;
19688     }
19689     if (Subtarget->hasSSE3() &&
19690         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19691       bool Lo = Mask.equals({0, 0, 2, 2});
19692       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19693       MVT ShuffleVT = MVT::v4f32;
19694       if (Depth == 1 && Root->getOpcode() == Shuffle)
19695         return false; // Nothing to do!
19696       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19697       DCI.AddToWorklist(Op.getNode());
19698       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19699       DCI.AddToWorklist(Op.getNode());
19700       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19701                     /*AddTo*/ true);
19702       return true;
19703     }
19704     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19705       bool Lo = Mask.equals({0, 0, 1, 1});
19706       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19707       MVT ShuffleVT = MVT::v4f32;
19708       if (Depth == 1 && Root->getOpcode() == Shuffle)
19709         return false; // Nothing to do!
19710       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19711       DCI.AddToWorklist(Op.getNode());
19712       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19713       DCI.AddToWorklist(Op.getNode());
19714       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19715                     /*AddTo*/ true);
19716       return true;
19717     }
19718   }
19719
19720   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19721   // variants as none of these have single-instruction variants that are
19722   // superior to the UNPCK formulation.
19723   if (!FloatDomain && VT.getSizeInBits() == 128 &&
19724       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19725        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19726        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19727        Mask.equals(
19728            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19729     bool Lo = Mask[0] == 0;
19730     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19731     if (Depth == 1 && Root->getOpcode() == Shuffle)
19732       return false; // Nothing to do!
19733     MVT ShuffleVT;
19734     switch (Mask.size()) {
19735     case 8:
19736       ShuffleVT = MVT::v8i16;
19737       break;
19738     case 16:
19739       ShuffleVT = MVT::v16i8;
19740       break;
19741     default:
19742       llvm_unreachable("Impossible mask size!");
19743     };
19744     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19745     DCI.AddToWorklist(Op.getNode());
19746     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19747     DCI.AddToWorklist(Op.getNode());
19748     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19749                   /*AddTo*/ true);
19750     return true;
19751   }
19752
19753   // Don't try to re-form single instruction chains under any circumstances now
19754   // that we've done encoding canonicalization for them.
19755   if (Depth < 2)
19756     return false;
19757
19758   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19759   // can replace them with a single PSHUFB instruction profitably. Intel's
19760   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19761   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19762   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19763     SmallVector<SDValue, 16> PSHUFBMask;
19764     int NumBytes = VT.getSizeInBits() / 8;
19765     int Ratio = NumBytes / Mask.size();
19766     for (int i = 0; i < NumBytes; ++i) {
19767       if (Mask[i / Ratio] == SM_SentinelUndef) {
19768         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
19769         continue;
19770       }
19771       int M = Mask[i / Ratio] != SM_SentinelZero
19772                   ? Ratio * Mask[i / Ratio] + i % Ratio
19773                   : 255;
19774       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19775     }
19776     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
19777     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
19778     DCI.AddToWorklist(Op.getNode());
19779     SDValue PSHUFBMaskOp =
19780         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
19781     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19782     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
19783     DCI.AddToWorklist(Op.getNode());
19784     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19785                   /*AddTo*/ true);
19786     return true;
19787   }
19788
19789   // Failed to find any combines.
19790   return false;
19791 }
19792
19793 /// \brief Fully generic combining of x86 shuffle instructions.
19794 ///
19795 /// This should be the last combine run over the x86 shuffle instructions. Once
19796 /// they have been fully optimized, this will recursively consider all chains
19797 /// of single-use shuffle instructions, build a generic model of the cumulative
19798 /// shuffle operation, and check for simpler instructions which implement this
19799 /// operation. We use this primarily for two purposes:
19800 ///
19801 /// 1) Collapse generic shuffles to specialized single instructions when
19802 ///    equivalent. In most cases, this is just an encoding size win, but
19803 ///    sometimes we will collapse multiple generic shuffles into a single
19804 ///    special-purpose shuffle.
19805 /// 2) Look for sequences of shuffle instructions with 3 or more total
19806 ///    instructions, and replace them with the slightly more expensive SSSE3
19807 ///    PSHUFB instruction if available. We do this as the last combining step
19808 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19809 ///    a suitable short sequence of other instructions. The PHUFB will either
19810 ///    use a register or have to read from memory and so is slightly (but only
19811 ///    slightly) more expensive than the other shuffle instructions.
19812 ///
19813 /// Because this is inherently a quadratic operation (for each shuffle in
19814 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19815 /// This should never be an issue in practice as the shuffle lowering doesn't
19816 /// produce sequences of more than 8 instructions.
19817 ///
19818 /// FIXME: We will currently miss some cases where the redundant shuffling
19819 /// would simplify under the threshold for PSHUFB formation because of
19820 /// combine-ordering. To fix this, we should do the redundant instruction
19821 /// combining in this recursive walk.
19822 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19823                                           ArrayRef<int> RootMask,
19824                                           int Depth, bool HasPSHUFB,
19825                                           SelectionDAG &DAG,
19826                                           TargetLowering::DAGCombinerInfo &DCI,
19827                                           const X86Subtarget *Subtarget) {
19828   // Bound the depth of our recursive combine because this is ultimately
19829   // quadratic in nature.
19830   if (Depth > 8)
19831     return false;
19832
19833   // Directly rip through bitcasts to find the underlying operand.
19834   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19835     Op = Op.getOperand(0);
19836
19837   MVT VT = Op.getSimpleValueType();
19838   if (!VT.isVector())
19839     return false; // Bail if we hit a non-vector.
19840
19841   assert(Root.getSimpleValueType().isVector() &&
19842          "Shuffles operate on vector types!");
19843   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19844          "Can only combine shuffles of the same vector register size.");
19845
19846   if (!isTargetShuffle(Op.getOpcode()))
19847     return false;
19848   SmallVector<int, 16> OpMask;
19849   bool IsUnary;
19850   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19851   // We only can combine unary shuffles which we can decode the mask for.
19852   if (!HaveMask || !IsUnary)
19853     return false;
19854
19855   assert(VT.getVectorNumElements() == OpMask.size() &&
19856          "Different mask size from vector size!");
19857   assert(((RootMask.size() > OpMask.size() &&
19858            RootMask.size() % OpMask.size() == 0) ||
19859           (OpMask.size() > RootMask.size() &&
19860            OpMask.size() % RootMask.size() == 0) ||
19861           OpMask.size() == RootMask.size()) &&
19862          "The smaller number of elements must divide the larger.");
19863   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19864   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19865   assert(((RootRatio == 1 && OpRatio == 1) ||
19866           (RootRatio == 1) != (OpRatio == 1)) &&
19867          "Must not have a ratio for both incoming and op masks!");
19868
19869   SmallVector<int, 16> Mask;
19870   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19871
19872   // Merge this shuffle operation's mask into our accumulated mask. Note that
19873   // this shuffle's mask will be the first applied to the input, followed by the
19874   // root mask to get us all the way to the root value arrangement. The reason
19875   // for this order is that we are recursing up the operation chain.
19876   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19877     int RootIdx = i / RootRatio;
19878     if (RootMask[RootIdx] < 0) {
19879       // This is a zero or undef lane, we're done.
19880       Mask.push_back(RootMask[RootIdx]);
19881       continue;
19882     }
19883
19884     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19885     int OpIdx = RootMaskedIdx / OpRatio;
19886     if (OpMask[OpIdx] < 0) {
19887       // The incoming lanes are zero or undef, it doesn't matter which ones we
19888       // are using.
19889       Mask.push_back(OpMask[OpIdx]);
19890       continue;
19891     }
19892
19893     // Ok, we have non-zero lanes, map them through.
19894     Mask.push_back(OpMask[OpIdx] * OpRatio +
19895                    RootMaskedIdx % OpRatio);
19896   }
19897
19898   // See if we can recurse into the operand to combine more things.
19899   switch (Op.getOpcode()) {
19900     case X86ISD::PSHUFB:
19901       HasPSHUFB = true;
19902     case X86ISD::PSHUFD:
19903     case X86ISD::PSHUFHW:
19904     case X86ISD::PSHUFLW:
19905       if (Op.getOperand(0).hasOneUse() &&
19906           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19907                                         HasPSHUFB, DAG, DCI, Subtarget))
19908         return true;
19909       break;
19910
19911     case X86ISD::UNPCKL:
19912     case X86ISD::UNPCKH:
19913       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19914       // We can't check for single use, we have to check that this shuffle is the only user.
19915       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19916           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19917                                         HasPSHUFB, DAG, DCI, Subtarget))
19918           return true;
19919       break;
19920   }
19921
19922   // Minor canonicalization of the accumulated shuffle mask to make it easier
19923   // to match below. All this does is detect masks with squential pairs of
19924   // elements, and shrink them to the half-width mask. It does this in a loop
19925   // so it will reduce the size of the mask to the minimal width mask which
19926   // performs an equivalent shuffle.
19927   SmallVector<int, 16> WidenedMask;
19928   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
19929     Mask = std::move(WidenedMask);
19930     WidenedMask.clear();
19931   }
19932
19933   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19934                                 Subtarget);
19935 }
19936
19937 /// \brief Get the PSHUF-style mask from PSHUF node.
19938 ///
19939 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19940 /// PSHUF-style masks that can be reused with such instructions.
19941 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19942   MVT VT = N.getSimpleValueType();
19943   SmallVector<int, 4> Mask;
19944   bool IsUnary;
19945   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
19946   (void)HaveMask;
19947   assert(HaveMask);
19948
19949   // If we have more than 128-bits, only the low 128-bits of shuffle mask
19950   // matter. Check that the upper masks are repeats and remove them.
19951   if (VT.getSizeInBits() > 128) {
19952     int LaneElts = 128 / VT.getScalarSizeInBits();
19953 #ifndef NDEBUG
19954     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
19955       for (int j = 0; j < LaneElts; ++j)
19956         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
19957                "Mask doesn't repeat in high 128-bit lanes!");
19958 #endif
19959     Mask.resize(LaneElts);
19960   }
19961
19962   switch (N.getOpcode()) {
19963   case X86ISD::PSHUFD:
19964     return Mask;
19965   case X86ISD::PSHUFLW:
19966     Mask.resize(4);
19967     return Mask;
19968   case X86ISD::PSHUFHW:
19969     Mask.erase(Mask.begin(), Mask.begin() + 4);
19970     for (int &M : Mask)
19971       M -= 4;
19972     return Mask;
19973   default:
19974     llvm_unreachable("No valid shuffle instruction found!");
19975   }
19976 }
19977
19978 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19979 ///
19980 /// We walk up the chain and look for a combinable shuffle, skipping over
19981 /// shuffles that we could hoist this shuffle's transformation past without
19982 /// altering anything.
19983 static SDValue
19984 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19985                              SelectionDAG &DAG,
19986                              TargetLowering::DAGCombinerInfo &DCI) {
19987   assert(N.getOpcode() == X86ISD::PSHUFD &&
19988          "Called with something other than an x86 128-bit half shuffle!");
19989   SDLoc DL(N);
19990
19991   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19992   // of the shuffles in the chain so that we can form a fresh chain to replace
19993   // this one.
19994   SmallVector<SDValue, 8> Chain;
19995   SDValue V = N.getOperand(0);
19996   for (; V.hasOneUse(); V = V.getOperand(0)) {
19997     switch (V.getOpcode()) {
19998     default:
19999       return SDValue(); // Nothing combined!
20000
20001     case ISD::BITCAST:
20002       // Skip bitcasts as we always know the type for the target specific
20003       // instructions.
20004       continue;
20005
20006     case X86ISD::PSHUFD:
20007       // Found another dword shuffle.
20008       break;
20009
20010     case X86ISD::PSHUFLW:
20011       // Check that the low words (being shuffled) are the identity in the
20012       // dword shuffle, and the high words are self-contained.
20013       if (Mask[0] != 0 || Mask[1] != 1 ||
20014           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20015         return SDValue();
20016
20017       Chain.push_back(V);
20018       continue;
20019
20020     case X86ISD::PSHUFHW:
20021       // Check that the high words (being shuffled) are the identity in the
20022       // dword shuffle, and the low words are self-contained.
20023       if (Mask[2] != 2 || Mask[3] != 3 ||
20024           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20025         return SDValue();
20026
20027       Chain.push_back(V);
20028       continue;
20029
20030     case X86ISD::UNPCKL:
20031     case X86ISD::UNPCKH:
20032       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20033       // shuffle into a preceding word shuffle.
20034       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20035           V.getSimpleValueType().getScalarType() != MVT::i16)
20036         return SDValue();
20037
20038       // Search for a half-shuffle which we can combine with.
20039       unsigned CombineOp =
20040           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20041       if (V.getOperand(0) != V.getOperand(1) ||
20042           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20043         return SDValue();
20044       Chain.push_back(V);
20045       V = V.getOperand(0);
20046       do {
20047         switch (V.getOpcode()) {
20048         default:
20049           return SDValue(); // Nothing to combine.
20050
20051         case X86ISD::PSHUFLW:
20052         case X86ISD::PSHUFHW:
20053           if (V.getOpcode() == CombineOp)
20054             break;
20055
20056           Chain.push_back(V);
20057
20058           // Fallthrough!
20059         case ISD::BITCAST:
20060           V = V.getOperand(0);
20061           continue;
20062         }
20063         break;
20064       } while (V.hasOneUse());
20065       break;
20066     }
20067     // Break out of the loop if we break out of the switch.
20068     break;
20069   }
20070
20071   if (!V.hasOneUse())
20072     // We fell out of the loop without finding a viable combining instruction.
20073     return SDValue();
20074
20075   // Merge this node's mask and our incoming mask.
20076   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20077   for (int &M : Mask)
20078     M = VMask[M];
20079   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20080                   getV4X86ShuffleImm8ForMask(Mask, DAG));
20081
20082   // Rebuild the chain around this new shuffle.
20083   while (!Chain.empty()) {
20084     SDValue W = Chain.pop_back_val();
20085
20086     if (V.getValueType() != W.getOperand(0).getValueType())
20087       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20088
20089     switch (W.getOpcode()) {
20090     default:
20091       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20092
20093     case X86ISD::UNPCKL:
20094     case X86ISD::UNPCKH:
20095       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20096       break;
20097
20098     case X86ISD::PSHUFD:
20099     case X86ISD::PSHUFLW:
20100     case X86ISD::PSHUFHW:
20101       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20102       break;
20103     }
20104   }
20105   if (V.getValueType() != N.getValueType())
20106     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20107
20108   // Return the new chain to replace N.
20109   return V;
20110 }
20111
20112 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20113 ///
20114 /// We walk up the chain, skipping shuffles of the other half and looking
20115 /// through shuffles which switch halves trying to find a shuffle of the same
20116 /// pair of dwords.
20117 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20118                                         SelectionDAG &DAG,
20119                                         TargetLowering::DAGCombinerInfo &DCI) {
20120   assert(
20121       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20122       "Called with something other than an x86 128-bit half shuffle!");
20123   SDLoc DL(N);
20124   unsigned CombineOpcode = N.getOpcode();
20125
20126   // Walk up a single-use chain looking for a combinable shuffle.
20127   SDValue V = N.getOperand(0);
20128   for (; V.hasOneUse(); V = V.getOperand(0)) {
20129     switch (V.getOpcode()) {
20130     default:
20131       return false; // Nothing combined!
20132
20133     case ISD::BITCAST:
20134       // Skip bitcasts as we always know the type for the target specific
20135       // instructions.
20136       continue;
20137
20138     case X86ISD::PSHUFLW:
20139     case X86ISD::PSHUFHW:
20140       if (V.getOpcode() == CombineOpcode)
20141         break;
20142
20143       // Other-half shuffles are no-ops.
20144       continue;
20145     }
20146     // Break out of the loop if we break out of the switch.
20147     break;
20148   }
20149
20150   if (!V.hasOneUse())
20151     // We fell out of the loop without finding a viable combining instruction.
20152     return false;
20153
20154   // Combine away the bottom node as its shuffle will be accumulated into
20155   // a preceding shuffle.
20156   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20157
20158   // Record the old value.
20159   SDValue Old = V;
20160
20161   // Merge this node's mask and our incoming mask (adjusted to account for all
20162   // the pshufd instructions encountered).
20163   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20164   for (int &M : Mask)
20165     M = VMask[M];
20166   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20167                   getV4X86ShuffleImm8ForMask(Mask, DAG));
20168
20169   // Check that the shuffles didn't cancel each other out. If not, we need to
20170   // combine to the new one.
20171   if (Old != V)
20172     // Replace the combinable shuffle with the combined one, updating all users
20173     // so that we re-evaluate the chain here.
20174     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20175
20176   return true;
20177 }
20178
20179 /// \brief Try to combine x86 target specific shuffles.
20180 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20181                                            TargetLowering::DAGCombinerInfo &DCI,
20182                                            const X86Subtarget *Subtarget) {
20183   SDLoc DL(N);
20184   MVT VT = N.getSimpleValueType();
20185   SmallVector<int, 4> Mask;
20186
20187   switch (N.getOpcode()) {
20188   case X86ISD::PSHUFD:
20189   case X86ISD::PSHUFLW:
20190   case X86ISD::PSHUFHW:
20191     Mask = getPSHUFShuffleMask(N);
20192     assert(Mask.size() == 4);
20193     break;
20194   default:
20195     return SDValue();
20196   }
20197
20198   // Nuke no-op shuffles that show up after combining.
20199   if (isNoopShuffleMask(Mask))
20200     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20201
20202   // Look for simplifications involving one or two shuffle instructions.
20203   SDValue V = N.getOperand(0);
20204   switch (N.getOpcode()) {
20205   default:
20206     break;
20207   case X86ISD::PSHUFLW:
20208   case X86ISD::PSHUFHW:
20209     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20210
20211     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20212       return SDValue(); // We combined away this shuffle, so we're done.
20213
20214     // See if this reduces to a PSHUFD which is no more expensive and can
20215     // combine with more operations. Note that it has to at least flip the
20216     // dwords as otherwise it would have been removed as a no-op.
20217     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20218       int DMask[] = {0, 1, 2, 3};
20219       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20220       DMask[DOffset + 0] = DOffset + 1;
20221       DMask[DOffset + 1] = DOffset + 0;
20222       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20223       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20224       DCI.AddToWorklist(V.getNode());
20225       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20226                       getV4X86ShuffleImm8ForMask(DMask, DAG));
20227       DCI.AddToWorklist(V.getNode());
20228       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20229     }
20230
20231     // Look for shuffle patterns which can be implemented as a single unpack.
20232     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20233     // only works when we have a PSHUFD followed by two half-shuffles.
20234     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20235         (V.getOpcode() == X86ISD::PSHUFLW ||
20236          V.getOpcode() == X86ISD::PSHUFHW) &&
20237         V.getOpcode() != N.getOpcode() &&
20238         V.hasOneUse()) {
20239       SDValue D = V.getOperand(0);
20240       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20241         D = D.getOperand(0);
20242       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20243         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20244         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20245         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20246         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20247         int WordMask[8];
20248         for (int i = 0; i < 4; ++i) {
20249           WordMask[i + NOffset] = Mask[i] + NOffset;
20250           WordMask[i + VOffset] = VMask[i] + VOffset;
20251         }
20252         // Map the word mask through the DWord mask.
20253         int MappedMask[8];
20254         for (int i = 0; i < 8; ++i)
20255           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20256         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20257             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20258           // We can replace all three shuffles with an unpack.
20259           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20260           DCI.AddToWorklist(V.getNode());
20261           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20262                                                 : X86ISD::UNPCKH,
20263                              DL, VT, V, V);
20264         }
20265       }
20266     }
20267
20268     break;
20269
20270   case X86ISD::PSHUFD:
20271     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20272       return NewN;
20273
20274     break;
20275   }
20276
20277   return SDValue();
20278 }
20279
20280 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20281 ///
20282 /// We combine this directly on the abstract vector shuffle nodes so it is
20283 /// easier to generically match. We also insert dummy vector shuffle nodes for
20284 /// the operands which explicitly discard the lanes which are unused by this
20285 /// operation to try to flow through the rest of the combiner the fact that
20286 /// they're unused.
20287 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20288   SDLoc DL(N);
20289   EVT VT = N->getValueType(0);
20290
20291   // We only handle target-independent shuffles.
20292   // FIXME: It would be easy and harmless to use the target shuffle mask
20293   // extraction tool to support more.
20294   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20295     return SDValue();
20296
20297   auto *SVN = cast<ShuffleVectorSDNode>(N);
20298   ArrayRef<int> Mask = SVN->getMask();
20299   SDValue V1 = N->getOperand(0);
20300   SDValue V2 = N->getOperand(1);
20301
20302   // We require the first shuffle operand to be the SUB node, and the second to
20303   // be the ADD node.
20304   // FIXME: We should support the commuted patterns.
20305   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20306     return SDValue();
20307
20308   // If there are other uses of these operations we can't fold them.
20309   if (!V1->hasOneUse() || !V2->hasOneUse())
20310     return SDValue();
20311
20312   // Ensure that both operations have the same operands. Note that we can
20313   // commute the FADD operands.
20314   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20315   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20316       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20317     return SDValue();
20318
20319   // We're looking for blends between FADD and FSUB nodes. We insist on these
20320   // nodes being lined up in a specific expected pattern.
20321   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20322         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20323         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20324     return SDValue();
20325
20326   // Only specific types are legal at this point, assert so we notice if and
20327   // when these change.
20328   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20329           VT == MVT::v4f64) &&
20330          "Unknown vector type encountered!");
20331
20332   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20333 }
20334
20335 /// PerformShuffleCombine - Performs several different shuffle combines.
20336 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20337                                      TargetLowering::DAGCombinerInfo &DCI,
20338                                      const X86Subtarget *Subtarget) {
20339   SDLoc dl(N);
20340   SDValue N0 = N->getOperand(0);
20341   SDValue N1 = N->getOperand(1);
20342   EVT VT = N->getValueType(0);
20343
20344   // Don't create instructions with illegal types after legalize types has run.
20345   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20346   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20347     return SDValue();
20348
20349   // If we have legalized the vector types, look for blends of FADD and FSUB
20350   // nodes that we can fuse into an ADDSUB node.
20351   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20352     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20353       return AddSub;
20354
20355   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20356   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20357       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20358     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20359
20360   // During Type Legalization, when promoting illegal vector types,
20361   // the backend might introduce new shuffle dag nodes and bitcasts.
20362   //
20363   // This code performs the following transformation:
20364   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20365   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20366   //
20367   // We do this only if both the bitcast and the BINOP dag nodes have
20368   // one use. Also, perform this transformation only if the new binary
20369   // operation is legal. This is to avoid introducing dag nodes that
20370   // potentially need to be further expanded (or custom lowered) into a
20371   // less optimal sequence of dag nodes.
20372   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20373       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20374       N0.getOpcode() == ISD::BITCAST) {
20375     SDValue BC0 = N0.getOperand(0);
20376     EVT SVT = BC0.getValueType();
20377     unsigned Opcode = BC0.getOpcode();
20378     unsigned NumElts = VT.getVectorNumElements();
20379
20380     if (BC0.hasOneUse() && SVT.isVector() &&
20381         SVT.getVectorNumElements() * 2 == NumElts &&
20382         TLI.isOperationLegal(Opcode, VT)) {
20383       bool CanFold = false;
20384       switch (Opcode) {
20385       default : break;
20386       case ISD::ADD :
20387       case ISD::FADD :
20388       case ISD::SUB :
20389       case ISD::FSUB :
20390       case ISD::MUL :
20391       case ISD::FMUL :
20392         CanFold = true;
20393       }
20394
20395       unsigned SVTNumElts = SVT.getVectorNumElements();
20396       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20397       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20398         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20399       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20400         CanFold = SVOp->getMaskElt(i) < 0;
20401
20402       if (CanFold) {
20403         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20404         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20405         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20406         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20407       }
20408     }
20409   }
20410
20411   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20412   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20413   // consecutive, non-overlapping, and in the right order.
20414   SmallVector<SDValue, 16> Elts;
20415   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20416     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20417
20418   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20419   if (LD.getNode())
20420     return LD;
20421
20422   if (isTargetShuffle(N->getOpcode())) {
20423     SDValue Shuffle =
20424         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20425     if (Shuffle.getNode())
20426       return Shuffle;
20427
20428     // Try recursively combining arbitrary sequences of x86 shuffle
20429     // instructions into higher-order shuffles. We do this after combining
20430     // specific PSHUF instruction sequences into their minimal form so that we
20431     // can evaluate how many specialized shuffle instructions are involved in
20432     // a particular chain.
20433     SmallVector<int, 1> NonceMask; // Just a placeholder.
20434     NonceMask.push_back(0);
20435     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20436                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20437                                       DCI, Subtarget))
20438       return SDValue(); // This routine will use CombineTo to replace N.
20439   }
20440
20441   return SDValue();
20442 }
20443
20444 /// PerformTruncateCombine - Converts truncate operation to
20445 /// a sequence of vector shuffle operations.
20446 /// It is possible when we truncate 256-bit vector to 128-bit vector
20447 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20448                                       TargetLowering::DAGCombinerInfo &DCI,
20449                                       const X86Subtarget *Subtarget)  {
20450   return SDValue();
20451 }
20452
20453 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20454 /// specific shuffle of a load can be folded into a single element load.
20455 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20456 /// shuffles have been custom lowered so we need to handle those here.
20457 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20458                                          TargetLowering::DAGCombinerInfo &DCI) {
20459   if (DCI.isBeforeLegalizeOps())
20460     return SDValue();
20461
20462   SDValue InVec = N->getOperand(0);
20463   SDValue EltNo = N->getOperand(1);
20464
20465   if (!isa<ConstantSDNode>(EltNo))
20466     return SDValue();
20467
20468   EVT OriginalVT = InVec.getValueType();
20469
20470   if (InVec.getOpcode() == ISD::BITCAST) {
20471     // Don't duplicate a load with other uses.
20472     if (!InVec.hasOneUse())
20473       return SDValue();
20474     EVT BCVT = InVec.getOperand(0).getValueType();
20475     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20476       return SDValue();
20477     InVec = InVec.getOperand(0);
20478   }
20479
20480   EVT CurrentVT = InVec.getValueType();
20481
20482   if (!isTargetShuffle(InVec.getOpcode()))
20483     return SDValue();
20484
20485   // Don't duplicate a load with other uses.
20486   if (!InVec.hasOneUse())
20487     return SDValue();
20488
20489   SmallVector<int, 16> ShuffleMask;
20490   bool UnaryShuffle;
20491   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20492                             ShuffleMask, UnaryShuffle))
20493     return SDValue();
20494
20495   // Select the input vector, guarding against out of range extract vector.
20496   unsigned NumElems = CurrentVT.getVectorNumElements();
20497   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20498   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20499   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20500                                          : InVec.getOperand(1);
20501
20502   // If inputs to shuffle are the same for both ops, then allow 2 uses
20503   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20504                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20505
20506   if (LdNode.getOpcode() == ISD::BITCAST) {
20507     // Don't duplicate a load with other uses.
20508     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20509       return SDValue();
20510
20511     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20512     LdNode = LdNode.getOperand(0);
20513   }
20514
20515   if (!ISD::isNormalLoad(LdNode.getNode()))
20516     return SDValue();
20517
20518   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20519
20520   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20521     return SDValue();
20522
20523   EVT EltVT = N->getValueType(0);
20524   // If there's a bitcast before the shuffle, check if the load type and
20525   // alignment is valid.
20526   unsigned Align = LN0->getAlignment();
20527   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20528   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20529       EltVT.getTypeForEVT(*DAG.getContext()));
20530
20531   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20532     return SDValue();
20533
20534   // All checks match so transform back to vector_shuffle so that DAG combiner
20535   // can finish the job
20536   SDLoc dl(N);
20537
20538   // Create shuffle node taking into account the case that its a unary shuffle
20539   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20540                                    : InVec.getOperand(1);
20541   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20542                                  InVec.getOperand(0), Shuffle,
20543                                  &ShuffleMask[0]);
20544   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20545   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20546                      EltNo);
20547 }
20548
20549 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20550 /// special and don't usually play with other vector types, it's better to
20551 /// handle them early to be sure we emit efficient code by avoiding
20552 /// store-load conversions.
20553 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20554   if (N->getValueType(0) != MVT::x86mmx ||
20555       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20556       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20557     return SDValue();
20558
20559   SDValue V = N->getOperand(0);
20560   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20561   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20562     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20563                        N->getValueType(0), V.getOperand(0));
20564
20565   return SDValue();
20566 }
20567
20568 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20569 /// generation and convert it from being a bunch of shuffles and extracts
20570 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20571 /// storing the value and loading scalars back, while for x64 we should
20572 /// use 64-bit extracts and shifts.
20573 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20574                                          TargetLowering::DAGCombinerInfo &DCI) {
20575   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20576   if (NewOp.getNode())
20577     return NewOp;
20578
20579   SDValue InputVector = N->getOperand(0);
20580
20581   // Detect mmx to i32 conversion through a v2i32 elt extract.
20582   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20583       N->getValueType(0) == MVT::i32 &&
20584       InputVector.getValueType() == MVT::v2i32) {
20585
20586     // The bitcast source is a direct mmx result.
20587     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20588     if (MMXSrc.getValueType() == MVT::x86mmx)
20589       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20590                          N->getValueType(0),
20591                          InputVector.getNode()->getOperand(0));
20592
20593     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20594     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20595     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20596         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20597         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20598         MMXSrcOp.getValueType() == MVT::v1i64 &&
20599         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20600       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20601                          N->getValueType(0),
20602                          MMXSrcOp.getOperand(0));
20603   }
20604
20605   // Only operate on vectors of 4 elements, where the alternative shuffling
20606   // gets to be more expensive.
20607   if (InputVector.getValueType() != MVT::v4i32)
20608     return SDValue();
20609
20610   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20611   // single use which is a sign-extend or zero-extend, and all elements are
20612   // used.
20613   SmallVector<SDNode *, 4> Uses;
20614   unsigned ExtractedElements = 0;
20615   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20616        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20617     if (UI.getUse().getResNo() != InputVector.getResNo())
20618       return SDValue();
20619
20620     SDNode *Extract = *UI;
20621     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20622       return SDValue();
20623
20624     if (Extract->getValueType(0) != MVT::i32)
20625       return SDValue();
20626     if (!Extract->hasOneUse())
20627       return SDValue();
20628     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20629         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20630       return SDValue();
20631     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20632       return SDValue();
20633
20634     // Record which element was extracted.
20635     ExtractedElements |=
20636       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20637
20638     Uses.push_back(Extract);
20639   }
20640
20641   // If not all the elements were used, this may not be worthwhile.
20642   if (ExtractedElements != 15)
20643     return SDValue();
20644
20645   // Ok, we've now decided to do the transformation.
20646   // If 64-bit shifts are legal, use the extract-shift sequence,
20647   // otherwise bounce the vector off the cache.
20648   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20649   SDValue Vals[4];
20650   SDLoc dl(InputVector);
20651
20652   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20653     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20654     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20655     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20656       DAG.getConstant(0, VecIdxTy));
20657     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20658       DAG.getConstant(1, VecIdxTy));
20659
20660     SDValue ShAmt = DAG.getConstant(32,
20661       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20662     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20663     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20664       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20665     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20666     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20667       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20668   } else {
20669     // Store the value to a temporary stack slot.
20670     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20671     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20672       MachinePointerInfo(), false, false, 0);
20673
20674     EVT ElementType = InputVector.getValueType().getVectorElementType();
20675     unsigned EltSize = ElementType.getSizeInBits() / 8;
20676
20677     // Replace each use (extract) with a load of the appropriate element.
20678     for (unsigned i = 0; i < 4; ++i) {
20679       uint64_t Offset = EltSize * i;
20680       SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20681
20682       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20683                                        StackPtr, OffsetVal);
20684
20685       // Load the scalar.
20686       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20687                             ScalarAddr, MachinePointerInfo(),
20688                             false, false, false, 0);
20689
20690     }
20691   }
20692
20693   // Replace the extracts
20694   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20695     UE = Uses.end(); UI != UE; ++UI) {
20696     SDNode *Extract = *UI;
20697
20698     SDValue Idx = Extract->getOperand(1);
20699     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20700     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20701   }
20702
20703   // The replacement was made in place; don't return anything.
20704   return SDValue();
20705 }
20706
20707 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20708 static std::pair<unsigned, bool>
20709 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20710                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20711   if (!VT.isVector())
20712     return std::make_pair(0, false);
20713
20714   bool NeedSplit = false;
20715   switch (VT.getSimpleVT().SimpleTy) {
20716   default: return std::make_pair(0, false);
20717   case MVT::v4i64:
20718   case MVT::v2i64:
20719     if (!Subtarget->hasVLX())
20720       return std::make_pair(0, false);
20721     break;
20722   case MVT::v64i8:
20723   case MVT::v32i16:
20724     if (!Subtarget->hasBWI())
20725       return std::make_pair(0, false);
20726     break;
20727   case MVT::v16i32:
20728   case MVT::v8i64:
20729     if (!Subtarget->hasAVX512())
20730       return std::make_pair(0, false);
20731     break;
20732   case MVT::v32i8:
20733   case MVT::v16i16:
20734   case MVT::v8i32:
20735     if (!Subtarget->hasAVX2())
20736       NeedSplit = true;
20737     if (!Subtarget->hasAVX())
20738       return std::make_pair(0, false);
20739     break;
20740   case MVT::v16i8:
20741   case MVT::v8i16:
20742   case MVT::v4i32:
20743     if (!Subtarget->hasSSE2())
20744       return std::make_pair(0, false);
20745   }
20746
20747   // SSE2 has only a small subset of the operations.
20748   bool hasUnsigned = Subtarget->hasSSE41() ||
20749                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20750   bool hasSigned = Subtarget->hasSSE41() ||
20751                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20752
20753   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20754
20755   unsigned Opc = 0;
20756   // Check for x CC y ? x : y.
20757   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20758       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20759     switch (CC) {
20760     default: break;
20761     case ISD::SETULT:
20762     case ISD::SETULE:
20763       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20764     case ISD::SETUGT:
20765     case ISD::SETUGE:
20766       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20767     case ISD::SETLT:
20768     case ISD::SETLE:
20769       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20770     case ISD::SETGT:
20771     case ISD::SETGE:
20772       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20773     }
20774   // Check for x CC y ? y : x -- a min/max with reversed arms.
20775   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20776              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20777     switch (CC) {
20778     default: break;
20779     case ISD::SETULT:
20780     case ISD::SETULE:
20781       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20782     case ISD::SETUGT:
20783     case ISD::SETUGE:
20784       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20785     case ISD::SETLT:
20786     case ISD::SETLE:
20787       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20788     case ISD::SETGT:
20789     case ISD::SETGE:
20790       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20791     }
20792   }
20793
20794   return std::make_pair(Opc, NeedSplit);
20795 }
20796
20797 static SDValue
20798 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20799                                       const X86Subtarget *Subtarget) {
20800   SDLoc dl(N);
20801   SDValue Cond = N->getOperand(0);
20802   SDValue LHS = N->getOperand(1);
20803   SDValue RHS = N->getOperand(2);
20804
20805   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20806     SDValue CondSrc = Cond->getOperand(0);
20807     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20808       Cond = CondSrc->getOperand(0);
20809   }
20810
20811   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20812     return SDValue();
20813
20814   // A vselect where all conditions and data are constants can be optimized into
20815   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20816   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20817       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20818     return SDValue();
20819
20820   unsigned MaskValue = 0;
20821   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20822     return SDValue();
20823
20824   MVT VT = N->getSimpleValueType(0);
20825   unsigned NumElems = VT.getVectorNumElements();
20826   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20827   for (unsigned i = 0; i < NumElems; ++i) {
20828     // Be sure we emit undef where we can.
20829     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20830       ShuffleMask[i] = -1;
20831     else
20832       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20833   }
20834
20835   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20836   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
20837     return SDValue();
20838   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20839 }
20840
20841 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20842 /// nodes.
20843 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20844                                     TargetLowering::DAGCombinerInfo &DCI,
20845                                     const X86Subtarget *Subtarget) {
20846   SDLoc DL(N);
20847   SDValue Cond = N->getOperand(0);
20848   // Get the LHS/RHS of the select.
20849   SDValue LHS = N->getOperand(1);
20850   SDValue RHS = N->getOperand(2);
20851   EVT VT = LHS.getValueType();
20852   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20853
20854   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20855   // instructions match the semantics of the common C idiom x<y?x:y but not
20856   // x<=y?x:y, because of how they handle negative zero (which can be
20857   // ignored in unsafe-math mode).
20858   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
20859   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20860       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
20861       (Subtarget->hasSSE2() ||
20862        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20863     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20864
20865     unsigned Opcode = 0;
20866     // Check for x CC y ? x : y.
20867     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20868         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20869       switch (CC) {
20870       default: break;
20871       case ISD::SETULT:
20872         // Converting this to a min would handle NaNs incorrectly, and swapping
20873         // the operands would cause it to handle comparisons between positive
20874         // and negative zero incorrectly.
20875         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20876           if (!DAG.getTarget().Options.UnsafeFPMath &&
20877               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20878             break;
20879           std::swap(LHS, RHS);
20880         }
20881         Opcode = X86ISD::FMIN;
20882         break;
20883       case ISD::SETOLE:
20884         // Converting this to a min would handle comparisons between positive
20885         // and negative zero incorrectly.
20886         if (!DAG.getTarget().Options.UnsafeFPMath &&
20887             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20888           break;
20889         Opcode = X86ISD::FMIN;
20890         break;
20891       case ISD::SETULE:
20892         // Converting this to a min would handle both negative zeros and NaNs
20893         // incorrectly, but we can swap the operands to fix both.
20894         std::swap(LHS, RHS);
20895       case ISD::SETOLT:
20896       case ISD::SETLT:
20897       case ISD::SETLE:
20898         Opcode = X86ISD::FMIN;
20899         break;
20900
20901       case ISD::SETOGE:
20902         // Converting this to a max would handle comparisons between positive
20903         // and negative zero incorrectly.
20904         if (!DAG.getTarget().Options.UnsafeFPMath &&
20905             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20906           break;
20907         Opcode = X86ISD::FMAX;
20908         break;
20909       case ISD::SETUGT:
20910         // Converting this to a max would handle NaNs incorrectly, and swapping
20911         // the operands would cause it to handle comparisons between positive
20912         // and negative zero incorrectly.
20913         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20914           if (!DAG.getTarget().Options.UnsafeFPMath &&
20915               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20916             break;
20917           std::swap(LHS, RHS);
20918         }
20919         Opcode = X86ISD::FMAX;
20920         break;
20921       case ISD::SETUGE:
20922         // Converting this to a max would handle both negative zeros and NaNs
20923         // incorrectly, but we can swap the operands to fix both.
20924         std::swap(LHS, RHS);
20925       case ISD::SETOGT:
20926       case ISD::SETGT:
20927       case ISD::SETGE:
20928         Opcode = X86ISD::FMAX;
20929         break;
20930       }
20931     // Check for x CC y ? y : x -- a min/max with reversed arms.
20932     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20933                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20934       switch (CC) {
20935       default: break;
20936       case ISD::SETOGE:
20937         // Converting this to a min would handle comparisons between positive
20938         // and negative zero incorrectly, and swapping the operands would
20939         // cause it to handle NaNs incorrectly.
20940         if (!DAG.getTarget().Options.UnsafeFPMath &&
20941             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20942           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20943             break;
20944           std::swap(LHS, RHS);
20945         }
20946         Opcode = X86ISD::FMIN;
20947         break;
20948       case ISD::SETUGT:
20949         // Converting this to a min would handle NaNs incorrectly.
20950         if (!DAG.getTarget().Options.UnsafeFPMath &&
20951             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20952           break;
20953         Opcode = X86ISD::FMIN;
20954         break;
20955       case ISD::SETUGE:
20956         // Converting this to a min would handle both negative zeros and NaNs
20957         // incorrectly, but we can swap the operands to fix both.
20958         std::swap(LHS, RHS);
20959       case ISD::SETOGT:
20960       case ISD::SETGT:
20961       case ISD::SETGE:
20962         Opcode = X86ISD::FMIN;
20963         break;
20964
20965       case ISD::SETULT:
20966         // Converting this to a max would handle NaNs incorrectly.
20967         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20968           break;
20969         Opcode = X86ISD::FMAX;
20970         break;
20971       case ISD::SETOLE:
20972         // Converting this to a max would handle comparisons between positive
20973         // and negative zero incorrectly, and swapping the operands would
20974         // cause it to handle NaNs incorrectly.
20975         if (!DAG.getTarget().Options.UnsafeFPMath &&
20976             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20977           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20978             break;
20979           std::swap(LHS, RHS);
20980         }
20981         Opcode = X86ISD::FMAX;
20982         break;
20983       case ISD::SETULE:
20984         // Converting this to a max would handle both negative zeros and NaNs
20985         // incorrectly, but we can swap the operands to fix both.
20986         std::swap(LHS, RHS);
20987       case ISD::SETOLT:
20988       case ISD::SETLT:
20989       case ISD::SETLE:
20990         Opcode = X86ISD::FMAX;
20991         break;
20992       }
20993     }
20994
20995     if (Opcode)
20996       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20997   }
20998
20999   EVT CondVT = Cond.getValueType();
21000   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21001       CondVT.getVectorElementType() == MVT::i1) {
21002     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21003     // lowering on KNL. In this case we convert it to
21004     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21005     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21006     // Since SKX these selects have a proper lowering.
21007     EVT OpVT = LHS.getValueType();
21008     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21009         (OpVT.getVectorElementType() == MVT::i8 ||
21010          OpVT.getVectorElementType() == MVT::i16) &&
21011         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21012       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21013       DCI.AddToWorklist(Cond.getNode());
21014       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21015     }
21016   }
21017   // If this is a select between two integer constants, try to do some
21018   // optimizations.
21019   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21020     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21021       // Don't do this for crazy integer types.
21022       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21023         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21024         // so that TrueC (the true value) is larger than FalseC.
21025         bool NeedsCondInvert = false;
21026
21027         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21028             // Efficiently invertible.
21029             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21030              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21031               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21032           NeedsCondInvert = true;
21033           std::swap(TrueC, FalseC);
21034         }
21035
21036         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21037         if (FalseC->getAPIntValue() == 0 &&
21038             TrueC->getAPIntValue().isPowerOf2()) {
21039           if (NeedsCondInvert) // Invert the condition if needed.
21040             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21041                                DAG.getConstant(1, Cond.getValueType()));
21042
21043           // Zero extend the condition if needed.
21044           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21045
21046           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21047           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21048                              DAG.getConstant(ShAmt, MVT::i8));
21049         }
21050
21051         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21052         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21053           if (NeedsCondInvert) // Invert the condition if needed.
21054             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21055                                DAG.getConstant(1, Cond.getValueType()));
21056
21057           // Zero extend the condition if needed.
21058           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21059                              FalseC->getValueType(0), Cond);
21060           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21061                              SDValue(FalseC, 0));
21062         }
21063
21064         // Optimize cases that will turn into an LEA instruction.  This requires
21065         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21066         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21067           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21068           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21069
21070           bool isFastMultiplier = false;
21071           if (Diff < 10) {
21072             switch ((unsigned char)Diff) {
21073               default: break;
21074               case 1:  // result = add base, cond
21075               case 2:  // result = lea base(    , cond*2)
21076               case 3:  // result = lea base(cond, cond*2)
21077               case 4:  // result = lea base(    , cond*4)
21078               case 5:  // result = lea base(cond, cond*4)
21079               case 8:  // result = lea base(    , cond*8)
21080               case 9:  // result = lea base(cond, cond*8)
21081                 isFastMultiplier = true;
21082                 break;
21083             }
21084           }
21085
21086           if (isFastMultiplier) {
21087             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21088             if (NeedsCondInvert) // Invert the condition if needed.
21089               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21090                                  DAG.getConstant(1, Cond.getValueType()));
21091
21092             // Zero extend the condition if needed.
21093             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21094                                Cond);
21095             // Scale the condition by the difference.
21096             if (Diff != 1)
21097               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21098                                  DAG.getConstant(Diff, Cond.getValueType()));
21099
21100             // Add the base if non-zero.
21101             if (FalseC->getAPIntValue() != 0)
21102               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21103                                  SDValue(FalseC, 0));
21104             return Cond;
21105           }
21106         }
21107       }
21108   }
21109
21110   // Canonicalize max and min:
21111   // (x > y) ? x : y -> (x >= y) ? x : y
21112   // (x < y) ? x : y -> (x <= y) ? x : y
21113   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21114   // the need for an extra compare
21115   // against zero. e.g.
21116   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21117   // subl   %esi, %edi
21118   // testl  %edi, %edi
21119   // movl   $0, %eax
21120   // cmovgl %edi, %eax
21121   // =>
21122   // xorl   %eax, %eax
21123   // subl   %esi, $edi
21124   // cmovsl %eax, %edi
21125   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21126       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21127       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21128     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21129     switch (CC) {
21130     default: break;
21131     case ISD::SETLT:
21132     case ISD::SETGT: {
21133       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21134       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21135                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21136       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21137     }
21138     }
21139   }
21140
21141   // Early exit check
21142   if (!TLI.isTypeLegal(VT))
21143     return SDValue();
21144
21145   // Match VSELECTs into subs with unsigned saturation.
21146   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21147       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21148       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21149        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21150     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21151
21152     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21153     // left side invert the predicate to simplify logic below.
21154     SDValue Other;
21155     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21156       Other = RHS;
21157       CC = ISD::getSetCCInverse(CC, true);
21158     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21159       Other = LHS;
21160     }
21161
21162     if (Other.getNode() && Other->getNumOperands() == 2 &&
21163         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21164       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21165       SDValue CondRHS = Cond->getOperand(1);
21166
21167       // Look for a general sub with unsigned saturation first.
21168       // x >= y ? x-y : 0 --> subus x, y
21169       // x >  y ? x-y : 0 --> subus x, y
21170       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21171           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21172         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21173
21174       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21175         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21176           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21177             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21178               // If the RHS is a constant we have to reverse the const
21179               // canonicalization.
21180               // x > C-1 ? x+-C : 0 --> subus x, C
21181               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21182                   CondRHSConst->getAPIntValue() ==
21183                       (-OpRHSConst->getAPIntValue() - 1))
21184                 return DAG.getNode(
21185                     X86ISD::SUBUS, DL, VT, OpLHS,
21186                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
21187
21188           // Another special case: If C was a sign bit, the sub has been
21189           // canonicalized into a xor.
21190           // FIXME: Would it be better to use computeKnownBits to determine
21191           //        whether it's safe to decanonicalize the xor?
21192           // x s< 0 ? x^C : 0 --> subus x, C
21193           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21194               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21195               OpRHSConst->getAPIntValue().isSignBit())
21196             // Note that we have to rebuild the RHS constant here to ensure we
21197             // don't rely on particular values of undef lanes.
21198             return DAG.getNode(
21199                 X86ISD::SUBUS, DL, VT, OpLHS,
21200                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
21201         }
21202     }
21203   }
21204
21205   // Try to match a min/max vector operation.
21206   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21207     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21208     unsigned Opc = ret.first;
21209     bool NeedSplit = ret.second;
21210
21211     if (Opc && NeedSplit) {
21212       unsigned NumElems = VT.getVectorNumElements();
21213       // Extract the LHS vectors
21214       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21215       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21216
21217       // Extract the RHS vectors
21218       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21219       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21220
21221       // Create min/max for each subvector
21222       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21223       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21224
21225       // Merge the result
21226       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21227     } else if (Opc)
21228       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21229   }
21230
21231   // Simplify vector selection if condition value type matches vselect
21232   // operand type
21233   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21234     assert(Cond.getValueType().isVector() &&
21235            "vector select expects a vector selector!");
21236
21237     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21238     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21239
21240     // Try invert the condition if true value is not all 1s and false value
21241     // is not all 0s.
21242     if (!TValIsAllOnes && !FValIsAllZeros &&
21243         // Check if the selector will be produced by CMPP*/PCMP*
21244         Cond.getOpcode() == ISD::SETCC &&
21245         // Check if SETCC has already been promoted
21246         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21247       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21248       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21249
21250       if (TValIsAllZeros || FValIsAllOnes) {
21251         SDValue CC = Cond.getOperand(2);
21252         ISD::CondCode NewCC =
21253           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21254                                Cond.getOperand(0).getValueType().isInteger());
21255         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21256         std::swap(LHS, RHS);
21257         TValIsAllOnes = FValIsAllOnes;
21258         FValIsAllZeros = TValIsAllZeros;
21259       }
21260     }
21261
21262     if (TValIsAllOnes || FValIsAllZeros) {
21263       SDValue Ret;
21264
21265       if (TValIsAllOnes && FValIsAllZeros)
21266         Ret = Cond;
21267       else if (TValIsAllOnes)
21268         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21269                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21270       else if (FValIsAllZeros)
21271         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21272                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21273
21274       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21275     }
21276   }
21277
21278   // We should generate an X86ISD::BLENDI from a vselect if its argument
21279   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21280   // constants. This specific pattern gets generated when we split a
21281   // selector for a 512 bit vector in a machine without AVX512 (but with
21282   // 256-bit vectors), during legalization:
21283   //
21284   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21285   //
21286   // Iff we find this pattern and the build_vectors are built from
21287   // constants, we translate the vselect into a shuffle_vector that we
21288   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21289   if ((N->getOpcode() == ISD::VSELECT ||
21290        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21291       !DCI.isBeforeLegalize()) {
21292     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21293     if (Shuffle.getNode())
21294       return Shuffle;
21295   }
21296
21297   // If this is a *dynamic* select (non-constant condition) and we can match
21298   // this node with one of the variable blend instructions, restructure the
21299   // condition so that the blends can use the high bit of each element and use
21300   // SimplifyDemandedBits to simplify the condition operand.
21301   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21302       !DCI.isBeforeLegalize() &&
21303       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21304     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21305
21306     // Don't optimize vector selects that map to mask-registers.
21307     if (BitWidth == 1)
21308       return SDValue();
21309
21310     // We can only handle the cases where VSELECT is directly legal on the
21311     // subtarget. We custom lower VSELECT nodes with constant conditions and
21312     // this makes it hard to see whether a dynamic VSELECT will correctly
21313     // lower, so we both check the operation's status and explicitly handle the
21314     // cases where a *dynamic* blend will fail even though a constant-condition
21315     // blend could be custom lowered.
21316     // FIXME: We should find a better way to handle this class of problems.
21317     // Potentially, we should combine constant-condition vselect nodes
21318     // pre-legalization into shuffles and not mark as many types as custom
21319     // lowered.
21320     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21321       return SDValue();
21322     // FIXME: We don't support i16-element blends currently. We could and
21323     // should support them by making *all* the bits in the condition be set
21324     // rather than just the high bit and using an i8-element blend.
21325     if (VT.getScalarType() == MVT::i16)
21326       return SDValue();
21327     // Dynamic blending was only available from SSE4.1 onward.
21328     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21329       return SDValue();
21330     // Byte blends are only available in AVX2
21331     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21332         !Subtarget->hasAVX2())
21333       return SDValue();
21334
21335     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21336     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21337
21338     APInt KnownZero, KnownOne;
21339     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21340                                           DCI.isBeforeLegalizeOps());
21341     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21342         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21343                                  TLO)) {
21344       // If we changed the computation somewhere in the DAG, this change
21345       // will affect all users of Cond.
21346       // Make sure it is fine and update all the nodes so that we do not
21347       // use the generic VSELECT anymore. Otherwise, we may perform
21348       // wrong optimizations as we messed up with the actual expectation
21349       // for the vector boolean values.
21350       if (Cond != TLO.Old) {
21351         // Check all uses of that condition operand to check whether it will be
21352         // consumed by non-BLEND instructions, which may depend on all bits are
21353         // set properly.
21354         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21355              I != E; ++I)
21356           if (I->getOpcode() != ISD::VSELECT)
21357             // TODO: Add other opcodes eventually lowered into BLEND.
21358             return SDValue();
21359
21360         // Update all the users of the condition, before committing the change,
21361         // so that the VSELECT optimizations that expect the correct vector
21362         // boolean value will not be triggered.
21363         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21364              I != E; ++I)
21365           DAG.ReplaceAllUsesOfValueWith(
21366               SDValue(*I, 0),
21367               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21368                           Cond, I->getOperand(1), I->getOperand(2)));
21369         DCI.CommitTargetLoweringOpt(TLO);
21370         return SDValue();
21371       }
21372       // At this point, only Cond is changed. Change the condition
21373       // just for N to keep the opportunity to optimize all other
21374       // users their own way.
21375       DAG.ReplaceAllUsesOfValueWith(
21376           SDValue(N, 0),
21377           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21378                       TLO.New, N->getOperand(1), N->getOperand(2)));
21379       return SDValue();
21380     }
21381   }
21382
21383   return SDValue();
21384 }
21385
21386 // Check whether a boolean test is testing a boolean value generated by
21387 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21388 // code.
21389 //
21390 // Simplify the following patterns:
21391 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21392 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21393 // to (Op EFLAGS Cond)
21394 //
21395 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21396 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21397 // to (Op EFLAGS !Cond)
21398 //
21399 // where Op could be BRCOND or CMOV.
21400 //
21401 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21402   // Quit if not CMP and SUB with its value result used.
21403   if (Cmp.getOpcode() != X86ISD::CMP &&
21404       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21405       return SDValue();
21406
21407   // Quit if not used as a boolean value.
21408   if (CC != X86::COND_E && CC != X86::COND_NE)
21409     return SDValue();
21410
21411   // Check CMP operands. One of them should be 0 or 1 and the other should be
21412   // an SetCC or extended from it.
21413   SDValue Op1 = Cmp.getOperand(0);
21414   SDValue Op2 = Cmp.getOperand(1);
21415
21416   SDValue SetCC;
21417   const ConstantSDNode* C = nullptr;
21418   bool needOppositeCond = (CC == X86::COND_E);
21419   bool checkAgainstTrue = false; // Is it a comparison against 1?
21420
21421   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21422     SetCC = Op2;
21423   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21424     SetCC = Op1;
21425   else // Quit if all operands are not constants.
21426     return SDValue();
21427
21428   if (C->getZExtValue() == 1) {
21429     needOppositeCond = !needOppositeCond;
21430     checkAgainstTrue = true;
21431   } else if (C->getZExtValue() != 0)
21432     // Quit if the constant is neither 0 or 1.
21433     return SDValue();
21434
21435   bool truncatedToBoolWithAnd = false;
21436   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21437   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21438          SetCC.getOpcode() == ISD::TRUNCATE ||
21439          SetCC.getOpcode() == ISD::AND) {
21440     if (SetCC.getOpcode() == ISD::AND) {
21441       int OpIdx = -1;
21442       ConstantSDNode *CS;
21443       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21444           CS->getZExtValue() == 1)
21445         OpIdx = 1;
21446       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21447           CS->getZExtValue() == 1)
21448         OpIdx = 0;
21449       if (OpIdx == -1)
21450         break;
21451       SetCC = SetCC.getOperand(OpIdx);
21452       truncatedToBoolWithAnd = true;
21453     } else
21454       SetCC = SetCC.getOperand(0);
21455   }
21456
21457   switch (SetCC.getOpcode()) {
21458   case X86ISD::SETCC_CARRY:
21459     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21460     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21461     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21462     // truncated to i1 using 'and'.
21463     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21464       break;
21465     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21466            "Invalid use of SETCC_CARRY!");
21467     // FALL THROUGH
21468   case X86ISD::SETCC:
21469     // Set the condition code or opposite one if necessary.
21470     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21471     if (needOppositeCond)
21472       CC = X86::GetOppositeBranchCondition(CC);
21473     return SetCC.getOperand(1);
21474   case X86ISD::CMOV: {
21475     // Check whether false/true value has canonical one, i.e. 0 or 1.
21476     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21477     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21478     // Quit if true value is not a constant.
21479     if (!TVal)
21480       return SDValue();
21481     // Quit if false value is not a constant.
21482     if (!FVal) {
21483       SDValue Op = SetCC.getOperand(0);
21484       // Skip 'zext' or 'trunc' node.
21485       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21486           Op.getOpcode() == ISD::TRUNCATE)
21487         Op = Op.getOperand(0);
21488       // A special case for rdrand/rdseed, where 0 is set if false cond is
21489       // found.
21490       if ((Op.getOpcode() != X86ISD::RDRAND &&
21491            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21492         return SDValue();
21493     }
21494     // Quit if false value is not the constant 0 or 1.
21495     bool FValIsFalse = true;
21496     if (FVal && FVal->getZExtValue() != 0) {
21497       if (FVal->getZExtValue() != 1)
21498         return SDValue();
21499       // If FVal is 1, opposite cond is needed.
21500       needOppositeCond = !needOppositeCond;
21501       FValIsFalse = false;
21502     }
21503     // Quit if TVal is not the constant opposite of FVal.
21504     if (FValIsFalse && TVal->getZExtValue() != 1)
21505       return SDValue();
21506     if (!FValIsFalse && TVal->getZExtValue() != 0)
21507       return SDValue();
21508     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21509     if (needOppositeCond)
21510       CC = X86::GetOppositeBranchCondition(CC);
21511     return SetCC.getOperand(3);
21512   }
21513   }
21514
21515   return SDValue();
21516 }
21517
21518 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21519 /// Match:
21520 ///   (X86or (X86setcc) (X86setcc))
21521 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21522 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21523                                            X86::CondCode &CC1, SDValue &Flags,
21524                                            bool &isAnd) {
21525   if (Cond->getOpcode() == X86ISD::CMP) {
21526     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21527     if (!CondOp1C || !CondOp1C->isNullValue())
21528       return false;
21529
21530     Cond = Cond->getOperand(0);
21531   }
21532
21533   isAnd = false;
21534
21535   SDValue SetCC0, SetCC1;
21536   switch (Cond->getOpcode()) {
21537   default: return false;
21538   case ISD::AND:
21539   case X86ISD::AND:
21540     isAnd = true;
21541     // fallthru
21542   case ISD::OR:
21543   case X86ISD::OR:
21544     SetCC0 = Cond->getOperand(0);
21545     SetCC1 = Cond->getOperand(1);
21546     break;
21547   };
21548
21549   // Make sure we have SETCC nodes, using the same flags value.
21550   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21551       SetCC1.getOpcode() != X86ISD::SETCC ||
21552       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21553     return false;
21554
21555   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21556   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21557   Flags = SetCC0->getOperand(1);
21558   return true;
21559 }
21560
21561 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21562 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21563                                   TargetLowering::DAGCombinerInfo &DCI,
21564                                   const X86Subtarget *Subtarget) {
21565   SDLoc DL(N);
21566
21567   // If the flag operand isn't dead, don't touch this CMOV.
21568   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21569     return SDValue();
21570
21571   SDValue FalseOp = N->getOperand(0);
21572   SDValue TrueOp = N->getOperand(1);
21573   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21574   SDValue Cond = N->getOperand(3);
21575
21576   if (CC == X86::COND_E || CC == X86::COND_NE) {
21577     switch (Cond.getOpcode()) {
21578     default: break;
21579     case X86ISD::BSR:
21580     case X86ISD::BSF:
21581       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21582       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21583         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21584     }
21585   }
21586
21587   SDValue Flags;
21588
21589   Flags = checkBoolTestSetCCCombine(Cond, CC);
21590   if (Flags.getNode() &&
21591       // Extra check as FCMOV only supports a subset of X86 cond.
21592       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21593     SDValue Ops[] = { FalseOp, TrueOp,
21594                       DAG.getConstant(CC, MVT::i8), Flags };
21595     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21596   }
21597
21598   // If this is a select between two integer constants, try to do some
21599   // optimizations.  Note that the operands are ordered the opposite of SELECT
21600   // operands.
21601   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21602     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21603       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21604       // larger than FalseC (the false value).
21605       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21606         CC = X86::GetOppositeBranchCondition(CC);
21607         std::swap(TrueC, FalseC);
21608         std::swap(TrueOp, FalseOp);
21609       }
21610
21611       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21612       // This is efficient for any integer data type (including i8/i16) and
21613       // shift amount.
21614       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21615         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21616                            DAG.getConstant(CC, MVT::i8), Cond);
21617
21618         // Zero extend the condition if needed.
21619         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21620
21621         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21622         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21623                            DAG.getConstant(ShAmt, MVT::i8));
21624         if (N->getNumValues() == 2)  // Dead flag value?
21625           return DCI.CombineTo(N, Cond, SDValue());
21626         return Cond;
21627       }
21628
21629       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21630       // for any integer data type, including i8/i16.
21631       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21632         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21633                            DAG.getConstant(CC, MVT::i8), Cond);
21634
21635         // Zero extend the condition if needed.
21636         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21637                            FalseC->getValueType(0), Cond);
21638         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21639                            SDValue(FalseC, 0));
21640
21641         if (N->getNumValues() == 2)  // Dead flag value?
21642           return DCI.CombineTo(N, Cond, SDValue());
21643         return Cond;
21644       }
21645
21646       // Optimize cases that will turn into an LEA instruction.  This requires
21647       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21648       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21649         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21650         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21651
21652         bool isFastMultiplier = false;
21653         if (Diff < 10) {
21654           switch ((unsigned char)Diff) {
21655           default: break;
21656           case 1:  // result = add base, cond
21657           case 2:  // result = lea base(    , cond*2)
21658           case 3:  // result = lea base(cond, cond*2)
21659           case 4:  // result = lea base(    , cond*4)
21660           case 5:  // result = lea base(cond, cond*4)
21661           case 8:  // result = lea base(    , cond*8)
21662           case 9:  // result = lea base(cond, cond*8)
21663             isFastMultiplier = true;
21664             break;
21665           }
21666         }
21667
21668         if (isFastMultiplier) {
21669           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21670           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21671                              DAG.getConstant(CC, MVT::i8), Cond);
21672           // Zero extend the condition if needed.
21673           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21674                              Cond);
21675           // Scale the condition by the difference.
21676           if (Diff != 1)
21677             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21678                                DAG.getConstant(Diff, Cond.getValueType()));
21679
21680           // Add the base if non-zero.
21681           if (FalseC->getAPIntValue() != 0)
21682             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21683                                SDValue(FalseC, 0));
21684           if (N->getNumValues() == 2)  // Dead flag value?
21685             return DCI.CombineTo(N, Cond, SDValue());
21686           return Cond;
21687         }
21688       }
21689     }
21690   }
21691
21692   // Handle these cases:
21693   //   (select (x != c), e, c) -> select (x != c), e, x),
21694   //   (select (x == c), c, e) -> select (x == c), x, e)
21695   // where the c is an integer constant, and the "select" is the combination
21696   // of CMOV and CMP.
21697   //
21698   // The rationale for this change is that the conditional-move from a constant
21699   // needs two instructions, however, conditional-move from a register needs
21700   // only one instruction.
21701   //
21702   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21703   //  some instruction-combining opportunities. This opt needs to be
21704   //  postponed as late as possible.
21705   //
21706   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21707     // the DCI.xxxx conditions are provided to postpone the optimization as
21708     // late as possible.
21709
21710     ConstantSDNode *CmpAgainst = nullptr;
21711     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21712         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21713         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21714
21715       if (CC == X86::COND_NE &&
21716           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21717         CC = X86::GetOppositeBranchCondition(CC);
21718         std::swap(TrueOp, FalseOp);
21719       }
21720
21721       if (CC == X86::COND_E &&
21722           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21723         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21724                           DAG.getConstant(CC, MVT::i8), Cond };
21725         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21726       }
21727     }
21728   }
21729
21730   // Fold and/or of setcc's to double CMOV:
21731   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21732   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21733   //
21734   // This combine lets us generate:
21735   //   cmovcc1 (jcc1 if we don't have CMOV)
21736   //   cmovcc2 (same)
21737   // instead of:
21738   //   setcc1
21739   //   setcc2
21740   //   and/or
21741   //   cmovne (jne if we don't have CMOV)
21742   // When we can't use the CMOV instruction, it might increase branch
21743   // mispredicts.
21744   // When we can use CMOV, or when there is no mispredict, this improves
21745   // throughput and reduces register pressure.
21746   //
21747   if (CC == X86::COND_NE) {
21748     SDValue Flags;
21749     X86::CondCode CC0, CC1;
21750     bool isAndSetCC;
21751     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
21752       if (isAndSetCC) {
21753         std::swap(FalseOp, TrueOp);
21754         CC0 = X86::GetOppositeBranchCondition(CC0);
21755         CC1 = X86::GetOppositeBranchCondition(CC1);
21756       }
21757
21758       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, MVT::i8),
21759         Flags};
21760       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
21761       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, MVT::i8), Flags};
21762       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21763       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
21764       return CMOV;
21765     }
21766   }
21767
21768   return SDValue();
21769 }
21770
21771 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21772                                                 const X86Subtarget *Subtarget) {
21773   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21774   switch (IntNo) {
21775   default: return SDValue();
21776   // SSE/AVX/AVX2 blend intrinsics.
21777   case Intrinsic::x86_avx2_pblendvb:
21778     // Don't try to simplify this intrinsic if we don't have AVX2.
21779     if (!Subtarget->hasAVX2())
21780       return SDValue();
21781     // FALL-THROUGH
21782   case Intrinsic::x86_avx_blendv_pd_256:
21783   case Intrinsic::x86_avx_blendv_ps_256:
21784     // Don't try to simplify this intrinsic if we don't have AVX.
21785     if (!Subtarget->hasAVX())
21786       return SDValue();
21787     // FALL-THROUGH
21788   case Intrinsic::x86_sse41_blendvps:
21789   case Intrinsic::x86_sse41_blendvpd:
21790   case Intrinsic::x86_sse41_pblendvb: {
21791     SDValue Op0 = N->getOperand(1);
21792     SDValue Op1 = N->getOperand(2);
21793     SDValue Mask = N->getOperand(3);
21794
21795     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21796     if (!Subtarget->hasSSE41())
21797       return SDValue();
21798
21799     // fold (blend A, A, Mask) -> A
21800     if (Op0 == Op1)
21801       return Op0;
21802     // fold (blend A, B, allZeros) -> A
21803     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21804       return Op0;
21805     // fold (blend A, B, allOnes) -> B
21806     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21807       return Op1;
21808
21809     // Simplify the case where the mask is a constant i32 value.
21810     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21811       if (C->isNullValue())
21812         return Op0;
21813       if (C->isAllOnesValue())
21814         return Op1;
21815     }
21816
21817     return SDValue();
21818   }
21819
21820   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21821   case Intrinsic::x86_sse2_psrai_w:
21822   case Intrinsic::x86_sse2_psrai_d:
21823   case Intrinsic::x86_avx2_psrai_w:
21824   case Intrinsic::x86_avx2_psrai_d:
21825   case Intrinsic::x86_sse2_psra_w:
21826   case Intrinsic::x86_sse2_psra_d:
21827   case Intrinsic::x86_avx2_psra_w:
21828   case Intrinsic::x86_avx2_psra_d: {
21829     SDValue Op0 = N->getOperand(1);
21830     SDValue Op1 = N->getOperand(2);
21831     EVT VT = Op0.getValueType();
21832     assert(VT.isVector() && "Expected a vector type!");
21833
21834     if (isa<BuildVectorSDNode>(Op1))
21835       Op1 = Op1.getOperand(0);
21836
21837     if (!isa<ConstantSDNode>(Op1))
21838       return SDValue();
21839
21840     EVT SVT = VT.getVectorElementType();
21841     unsigned SVTBits = SVT.getSizeInBits();
21842
21843     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21844     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21845     uint64_t ShAmt = C.getZExtValue();
21846
21847     // Don't try to convert this shift into a ISD::SRA if the shift
21848     // count is bigger than or equal to the element size.
21849     if (ShAmt >= SVTBits)
21850       return SDValue();
21851
21852     // Trivial case: if the shift count is zero, then fold this
21853     // into the first operand.
21854     if (ShAmt == 0)
21855       return Op0;
21856
21857     // Replace this packed shift intrinsic with a target independent
21858     // shift dag node.
21859     SDValue Splat = DAG.getConstant(C, VT);
21860     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21861   }
21862   }
21863 }
21864
21865 /// PerformMulCombine - Optimize a single multiply with constant into two
21866 /// in order to implement it with two cheaper instructions, e.g.
21867 /// LEA + SHL, LEA + LEA.
21868 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21869                                  TargetLowering::DAGCombinerInfo &DCI) {
21870   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21871     return SDValue();
21872
21873   EVT VT = N->getValueType(0);
21874   if (VT != MVT::i64 && VT != MVT::i32)
21875     return SDValue();
21876
21877   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21878   if (!C)
21879     return SDValue();
21880   uint64_t MulAmt = C->getZExtValue();
21881   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21882     return SDValue();
21883
21884   uint64_t MulAmt1 = 0;
21885   uint64_t MulAmt2 = 0;
21886   if ((MulAmt % 9) == 0) {
21887     MulAmt1 = 9;
21888     MulAmt2 = MulAmt / 9;
21889   } else if ((MulAmt % 5) == 0) {
21890     MulAmt1 = 5;
21891     MulAmt2 = MulAmt / 5;
21892   } else if ((MulAmt % 3) == 0) {
21893     MulAmt1 = 3;
21894     MulAmt2 = MulAmt / 3;
21895   }
21896   if (MulAmt2 &&
21897       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21898     SDLoc DL(N);
21899
21900     if (isPowerOf2_64(MulAmt2) &&
21901         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21902       // If second multiplifer is pow2, issue it first. We want the multiply by
21903       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21904       // is an add.
21905       std::swap(MulAmt1, MulAmt2);
21906
21907     SDValue NewMul;
21908     if (isPowerOf2_64(MulAmt1))
21909       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21910                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21911     else
21912       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21913                            DAG.getConstant(MulAmt1, VT));
21914
21915     if (isPowerOf2_64(MulAmt2))
21916       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21917                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21918     else
21919       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21920                            DAG.getConstant(MulAmt2, VT));
21921
21922     // Do not add new nodes to DAG combiner worklist.
21923     DCI.CombineTo(N, NewMul, false);
21924   }
21925   return SDValue();
21926 }
21927
21928 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21929   SDValue N0 = N->getOperand(0);
21930   SDValue N1 = N->getOperand(1);
21931   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21932   EVT VT = N0.getValueType();
21933
21934   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21935   // since the result of setcc_c is all zero's or all ones.
21936   if (VT.isInteger() && !VT.isVector() &&
21937       N1C && N0.getOpcode() == ISD::AND &&
21938       N0.getOperand(1).getOpcode() == ISD::Constant) {
21939     SDValue N00 = N0.getOperand(0);
21940     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21941         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21942           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21943          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21944       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21945       APInt ShAmt = N1C->getAPIntValue();
21946       Mask = Mask.shl(ShAmt);
21947       if (Mask != 0)
21948         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21949                            N00, DAG.getConstant(Mask, VT));
21950     }
21951   }
21952
21953   // Hardware support for vector shifts is sparse which makes us scalarize the
21954   // vector operations in many cases. Also, on sandybridge ADD is faster than
21955   // shl.
21956   // (shl V, 1) -> add V,V
21957   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21958     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21959       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21960       // We shift all of the values by one. In many cases we do not have
21961       // hardware support for this operation. This is better expressed as an ADD
21962       // of two values.
21963       if (N1SplatC->getZExtValue() == 1)
21964         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21965     }
21966
21967   return SDValue();
21968 }
21969
21970 /// \brief Returns a vector of 0s if the node in input is a vector logical
21971 /// shift by a constant amount which is known to be bigger than or equal
21972 /// to the vector element size in bits.
21973 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21974                                       const X86Subtarget *Subtarget) {
21975   EVT VT = N->getValueType(0);
21976
21977   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21978       (!Subtarget->hasInt256() ||
21979        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21980     return SDValue();
21981
21982   SDValue Amt = N->getOperand(1);
21983   SDLoc DL(N);
21984   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21985     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21986       APInt ShiftAmt = AmtSplat->getAPIntValue();
21987       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21988
21989       // SSE2/AVX2 logical shifts always return a vector of 0s
21990       // if the shift amount is bigger than or equal to
21991       // the element size. The constant shift amount will be
21992       // encoded as a 8-bit immediate.
21993       if (ShiftAmt.trunc(8).uge(MaxAmount))
21994         return getZeroVector(VT, Subtarget, DAG, DL);
21995     }
21996
21997   return SDValue();
21998 }
21999
22000 /// PerformShiftCombine - Combine shifts.
22001 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22002                                    TargetLowering::DAGCombinerInfo &DCI,
22003                                    const X86Subtarget *Subtarget) {
22004   if (N->getOpcode() == ISD::SHL) {
22005     SDValue V = PerformSHLCombine(N, DAG);
22006     if (V.getNode()) return V;
22007   }
22008
22009   if (N->getOpcode() != ISD::SRA) {
22010     // Try to fold this logical shift into a zero vector.
22011     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22012     if (V.getNode()) return V;
22013   }
22014
22015   return SDValue();
22016 }
22017
22018 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22019 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22020 // and friends.  Likewise for OR -> CMPNEQSS.
22021 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22022                             TargetLowering::DAGCombinerInfo &DCI,
22023                             const X86Subtarget *Subtarget) {
22024   unsigned opcode;
22025
22026   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22027   // we're requiring SSE2 for both.
22028   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22029     SDValue N0 = N->getOperand(0);
22030     SDValue N1 = N->getOperand(1);
22031     SDValue CMP0 = N0->getOperand(1);
22032     SDValue CMP1 = N1->getOperand(1);
22033     SDLoc DL(N);
22034
22035     // The SETCCs should both refer to the same CMP.
22036     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22037       return SDValue();
22038
22039     SDValue CMP00 = CMP0->getOperand(0);
22040     SDValue CMP01 = CMP0->getOperand(1);
22041     EVT     VT    = CMP00.getValueType();
22042
22043     if (VT == MVT::f32 || VT == MVT::f64) {
22044       bool ExpectingFlags = false;
22045       // Check for any users that want flags:
22046       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22047            !ExpectingFlags && UI != UE; ++UI)
22048         switch (UI->getOpcode()) {
22049         default:
22050         case ISD::BR_CC:
22051         case ISD::BRCOND:
22052         case ISD::SELECT:
22053           ExpectingFlags = true;
22054           break;
22055         case ISD::CopyToReg:
22056         case ISD::SIGN_EXTEND:
22057         case ISD::ZERO_EXTEND:
22058         case ISD::ANY_EXTEND:
22059           break;
22060         }
22061
22062       if (!ExpectingFlags) {
22063         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22064         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22065
22066         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22067           X86::CondCode tmp = cc0;
22068           cc0 = cc1;
22069           cc1 = tmp;
22070         }
22071
22072         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22073             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22074           // FIXME: need symbolic constants for these magic numbers.
22075           // See X86ATTInstPrinter.cpp:printSSECC().
22076           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22077           if (Subtarget->hasAVX512()) {
22078             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22079                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
22080             if (N->getValueType(0) != MVT::i1)
22081               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22082                                  FSetCC);
22083             return FSetCC;
22084           }
22085           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22086                                               CMP00.getValueType(), CMP00, CMP01,
22087                                               DAG.getConstant(x86cc, MVT::i8));
22088
22089           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22090           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22091
22092           if (is64BitFP && !Subtarget->is64Bit()) {
22093             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22094             // 64-bit integer, since that's not a legal type. Since
22095             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22096             // bits, but can do this little dance to extract the lowest 32 bits
22097             // and work with those going forward.
22098             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22099                                            OnesOrZeroesF);
22100             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22101                                            Vector64);
22102             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22103                                         Vector32, DAG.getIntPtrConstant(0));
22104             IntVT = MVT::i32;
22105           }
22106
22107           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
22108           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22109                                       DAG.getConstant(1, IntVT));
22110           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
22111           return OneBitOfTruth;
22112         }
22113       }
22114     }
22115   }
22116   return SDValue();
22117 }
22118
22119 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22120 /// so it can be folded inside ANDNP.
22121 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22122   EVT VT = N->getValueType(0);
22123
22124   // Match direct AllOnes for 128 and 256-bit vectors
22125   if (ISD::isBuildVectorAllOnes(N))
22126     return true;
22127
22128   // Look through a bit convert.
22129   if (N->getOpcode() == ISD::BITCAST)
22130     N = N->getOperand(0).getNode();
22131
22132   // Sometimes the operand may come from a insert_subvector building a 256-bit
22133   // allones vector
22134   if (VT.is256BitVector() &&
22135       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22136     SDValue V1 = N->getOperand(0);
22137     SDValue V2 = N->getOperand(1);
22138
22139     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22140         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22141         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22142         ISD::isBuildVectorAllOnes(V2.getNode()))
22143       return true;
22144   }
22145
22146   return false;
22147 }
22148
22149 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22150 // register. In most cases we actually compare or select YMM-sized registers
22151 // and mixing the two types creates horrible code. This method optimizes
22152 // some of the transition sequences.
22153 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22154                                  TargetLowering::DAGCombinerInfo &DCI,
22155                                  const X86Subtarget *Subtarget) {
22156   EVT VT = N->getValueType(0);
22157   if (!VT.is256BitVector())
22158     return SDValue();
22159
22160   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22161           N->getOpcode() == ISD::ZERO_EXTEND ||
22162           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22163
22164   SDValue Narrow = N->getOperand(0);
22165   EVT NarrowVT = Narrow->getValueType(0);
22166   if (!NarrowVT.is128BitVector())
22167     return SDValue();
22168
22169   if (Narrow->getOpcode() != ISD::XOR &&
22170       Narrow->getOpcode() != ISD::AND &&
22171       Narrow->getOpcode() != ISD::OR)
22172     return SDValue();
22173
22174   SDValue N0  = Narrow->getOperand(0);
22175   SDValue N1  = Narrow->getOperand(1);
22176   SDLoc DL(Narrow);
22177
22178   // The Left side has to be a trunc.
22179   if (N0.getOpcode() != ISD::TRUNCATE)
22180     return SDValue();
22181
22182   // The type of the truncated inputs.
22183   EVT WideVT = N0->getOperand(0)->getValueType(0);
22184   if (WideVT != VT)
22185     return SDValue();
22186
22187   // The right side has to be a 'trunc' or a constant vector.
22188   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22189   ConstantSDNode *RHSConstSplat = nullptr;
22190   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22191     RHSConstSplat = RHSBV->getConstantSplatNode();
22192   if (!RHSTrunc && !RHSConstSplat)
22193     return SDValue();
22194
22195   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22196
22197   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22198     return SDValue();
22199
22200   // Set N0 and N1 to hold the inputs to the new wide operation.
22201   N0 = N0->getOperand(0);
22202   if (RHSConstSplat) {
22203     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22204                      SDValue(RHSConstSplat, 0));
22205     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22206     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22207   } else if (RHSTrunc) {
22208     N1 = N1->getOperand(0);
22209   }
22210
22211   // Generate the wide operation.
22212   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22213   unsigned Opcode = N->getOpcode();
22214   switch (Opcode) {
22215   case ISD::ANY_EXTEND:
22216     return Op;
22217   case ISD::ZERO_EXTEND: {
22218     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22219     APInt Mask = APInt::getAllOnesValue(InBits);
22220     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22221     return DAG.getNode(ISD::AND, DL, VT,
22222                        Op, DAG.getConstant(Mask, VT));
22223   }
22224   case ISD::SIGN_EXTEND:
22225     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22226                        Op, DAG.getValueType(NarrowVT));
22227   default:
22228     llvm_unreachable("Unexpected opcode");
22229   }
22230 }
22231
22232 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22233                                  TargetLowering::DAGCombinerInfo &DCI,
22234                                  const X86Subtarget *Subtarget) {
22235   SDValue N0 = N->getOperand(0);
22236   SDValue N1 = N->getOperand(1);
22237   SDLoc DL(N);
22238
22239   // A vector zext_in_reg may be represented as a shuffle,
22240   // feeding into a bitcast (this represents anyext) feeding into
22241   // an and with a mask.
22242   // We'd like to try to combine that into a shuffle with zero
22243   // plus a bitcast, removing the and.
22244   if (N0.getOpcode() != ISD::BITCAST ||
22245       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22246     return SDValue();
22247
22248   // The other side of the AND should be a splat of 2^C, where C
22249   // is the number of bits in the source type.
22250   if (N1.getOpcode() == ISD::BITCAST)
22251     N1 = N1.getOperand(0);
22252   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22253     return SDValue();
22254   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22255
22256   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22257   EVT SrcType = Shuffle->getValueType(0);
22258
22259   // We expect a single-source shuffle
22260   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22261     return SDValue();
22262
22263   unsigned SrcSize = SrcType.getScalarSizeInBits();
22264
22265   APInt SplatValue, SplatUndef;
22266   unsigned SplatBitSize;
22267   bool HasAnyUndefs;
22268   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22269                                 SplatBitSize, HasAnyUndefs))
22270     return SDValue();
22271
22272   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22273   // Make sure the splat matches the mask we expect
22274   if (SplatBitSize > ResSize ||
22275       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22276     return SDValue();
22277
22278   // Make sure the input and output size make sense
22279   if (SrcSize >= ResSize || ResSize % SrcSize)
22280     return SDValue();
22281
22282   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22283   // The number of u's between each two values depends on the ratio between
22284   // the source and dest type.
22285   unsigned ZextRatio = ResSize / SrcSize;
22286   bool IsZext = true;
22287   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22288     if (i % ZextRatio) {
22289       if (Shuffle->getMaskElt(i) > 0) {
22290         // Expected undef
22291         IsZext = false;
22292         break;
22293       }
22294     } else {
22295       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22296         // Expected element number
22297         IsZext = false;
22298         break;
22299       }
22300     }
22301   }
22302
22303   if (!IsZext)
22304     return SDValue();
22305
22306   // Ok, perform the transformation - replace the shuffle with
22307   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22308   // (instead of undef) where the k elements come from the zero vector.
22309   SmallVector<int, 8> Mask;
22310   unsigned NumElems = SrcType.getVectorNumElements();
22311   for (unsigned i = 0; i < NumElems; ++i)
22312     if (i % ZextRatio)
22313       Mask.push_back(NumElems);
22314     else
22315       Mask.push_back(i / ZextRatio);
22316
22317   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22318     Shuffle->getOperand(0), DAG.getConstant(0, SrcType), Mask);
22319   return DAG.getNode(ISD::BITCAST, DL,  N0.getValueType(), NewShuffle);
22320 }
22321
22322 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22323                                  TargetLowering::DAGCombinerInfo &DCI,
22324                                  const X86Subtarget *Subtarget) {
22325   if (DCI.isBeforeLegalizeOps())
22326     return SDValue();
22327
22328   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22329     return Zext;
22330
22331   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22332     return R;
22333
22334   EVT VT = N->getValueType(0);
22335   SDValue N0 = N->getOperand(0);
22336   SDValue N1 = N->getOperand(1);
22337   SDLoc DL(N);
22338
22339   // Create BEXTR instructions
22340   // BEXTR is ((X >> imm) & (2**size-1))
22341   if (VT == MVT::i32 || VT == MVT::i64) {
22342     // Check for BEXTR.
22343     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22344         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22345       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22346       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22347       if (MaskNode && ShiftNode) {
22348         uint64_t Mask = MaskNode->getZExtValue();
22349         uint64_t Shift = ShiftNode->getZExtValue();
22350         if (isMask_64(Mask)) {
22351           uint64_t MaskSize = countPopulation(Mask);
22352           if (Shift + MaskSize <= VT.getSizeInBits())
22353             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22354                                DAG.getConstant(Shift | (MaskSize << 8), VT));
22355         }
22356       }
22357     } // BEXTR
22358
22359     return SDValue();
22360   }
22361
22362   // Want to form ANDNP nodes:
22363   // 1) In the hopes of then easily combining them with OR and AND nodes
22364   //    to form PBLEND/PSIGN.
22365   // 2) To match ANDN packed intrinsics
22366   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22367     return SDValue();
22368
22369   // Check LHS for vnot
22370   if (N0.getOpcode() == ISD::XOR &&
22371       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22372       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22373     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22374
22375   // Check RHS for vnot
22376   if (N1.getOpcode() == ISD::XOR &&
22377       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22378       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22379     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22380
22381   return SDValue();
22382 }
22383
22384 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22385                                 TargetLowering::DAGCombinerInfo &DCI,
22386                                 const X86Subtarget *Subtarget) {
22387   if (DCI.isBeforeLegalizeOps())
22388     return SDValue();
22389
22390   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22391   if (R.getNode())
22392     return R;
22393
22394   SDValue N0 = N->getOperand(0);
22395   SDValue N1 = N->getOperand(1);
22396   EVT VT = N->getValueType(0);
22397
22398   // look for psign/blend
22399   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22400     if (!Subtarget->hasSSSE3() ||
22401         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22402       return SDValue();
22403
22404     // Canonicalize pandn to RHS
22405     if (N0.getOpcode() == X86ISD::ANDNP)
22406       std::swap(N0, N1);
22407     // or (and (m, y), (pandn m, x))
22408     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22409       SDValue Mask = N1.getOperand(0);
22410       SDValue X    = N1.getOperand(1);
22411       SDValue Y;
22412       if (N0.getOperand(0) == Mask)
22413         Y = N0.getOperand(1);
22414       if (N0.getOperand(1) == Mask)
22415         Y = N0.getOperand(0);
22416
22417       // Check to see if the mask appeared in both the AND and ANDNP and
22418       if (!Y.getNode())
22419         return SDValue();
22420
22421       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22422       // Look through mask bitcast.
22423       if (Mask.getOpcode() == ISD::BITCAST)
22424         Mask = Mask.getOperand(0);
22425       if (X.getOpcode() == ISD::BITCAST)
22426         X = X.getOperand(0);
22427       if (Y.getOpcode() == ISD::BITCAST)
22428         Y = Y.getOperand(0);
22429
22430       EVT MaskVT = Mask.getValueType();
22431
22432       // Validate that the Mask operand is a vector sra node.
22433       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22434       // there is no psrai.b
22435       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22436       unsigned SraAmt = ~0;
22437       if (Mask.getOpcode() == ISD::SRA) {
22438         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22439           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22440             SraAmt = AmtConst->getZExtValue();
22441       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22442         SDValue SraC = Mask.getOperand(1);
22443         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22444       }
22445       if ((SraAmt + 1) != EltBits)
22446         return SDValue();
22447
22448       SDLoc DL(N);
22449
22450       // Now we know we at least have a plendvb with the mask val.  See if
22451       // we can form a psignb/w/d.
22452       // psign = x.type == y.type == mask.type && y = sub(0, x);
22453       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22454           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22455           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22456         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22457                "Unsupported VT for PSIGN");
22458         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22459         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22460       }
22461       // PBLENDVB only available on SSE 4.1
22462       if (!Subtarget->hasSSE41())
22463         return SDValue();
22464
22465       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22466
22467       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22468       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22469       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22470       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22471       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22472     }
22473   }
22474
22475   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22476     return SDValue();
22477
22478   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22479   MachineFunction &MF = DAG.getMachineFunction();
22480   bool OptForSize =
22481       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22482
22483   // SHLD/SHRD instructions have lower register pressure, but on some
22484   // platforms they have higher latency than the equivalent
22485   // series of shifts/or that would otherwise be generated.
22486   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22487   // have higher latencies and we are not optimizing for size.
22488   if (!OptForSize && Subtarget->isSHLDSlow())
22489     return SDValue();
22490
22491   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22492     std::swap(N0, N1);
22493   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22494     return SDValue();
22495   if (!N0.hasOneUse() || !N1.hasOneUse())
22496     return SDValue();
22497
22498   SDValue ShAmt0 = N0.getOperand(1);
22499   if (ShAmt0.getValueType() != MVT::i8)
22500     return SDValue();
22501   SDValue ShAmt1 = N1.getOperand(1);
22502   if (ShAmt1.getValueType() != MVT::i8)
22503     return SDValue();
22504   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22505     ShAmt0 = ShAmt0.getOperand(0);
22506   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22507     ShAmt1 = ShAmt1.getOperand(0);
22508
22509   SDLoc DL(N);
22510   unsigned Opc = X86ISD::SHLD;
22511   SDValue Op0 = N0.getOperand(0);
22512   SDValue Op1 = N1.getOperand(0);
22513   if (ShAmt0.getOpcode() == ISD::SUB) {
22514     Opc = X86ISD::SHRD;
22515     std::swap(Op0, Op1);
22516     std::swap(ShAmt0, ShAmt1);
22517   }
22518
22519   unsigned Bits = VT.getSizeInBits();
22520   if (ShAmt1.getOpcode() == ISD::SUB) {
22521     SDValue Sum = ShAmt1.getOperand(0);
22522     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22523       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22524       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22525         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22526       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22527         return DAG.getNode(Opc, DL, VT,
22528                            Op0, Op1,
22529                            DAG.getNode(ISD::TRUNCATE, DL,
22530                                        MVT::i8, ShAmt0));
22531     }
22532   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22533     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22534     if (ShAmt0C &&
22535         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22536       return DAG.getNode(Opc, DL, VT,
22537                          N0.getOperand(0), N1.getOperand(0),
22538                          DAG.getNode(ISD::TRUNCATE, DL,
22539                                        MVT::i8, ShAmt0));
22540   }
22541
22542   return SDValue();
22543 }
22544
22545 // Generate NEG and CMOV for integer abs.
22546 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22547   EVT VT = N->getValueType(0);
22548
22549   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22550   // 8-bit integer abs to NEG and CMOV.
22551   if (VT.isInteger() && VT.getSizeInBits() == 8)
22552     return SDValue();
22553
22554   SDValue N0 = N->getOperand(0);
22555   SDValue N1 = N->getOperand(1);
22556   SDLoc DL(N);
22557
22558   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22559   // and change it to SUB and CMOV.
22560   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22561       N0.getOpcode() == ISD::ADD &&
22562       N0.getOperand(1) == N1 &&
22563       N1.getOpcode() == ISD::SRA &&
22564       N1.getOperand(0) == N0.getOperand(0))
22565     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22566       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22567         // Generate SUB & CMOV.
22568         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22569                                   DAG.getConstant(0, VT), N0.getOperand(0));
22570
22571         SDValue Ops[] = { N0.getOperand(0), Neg,
22572                           DAG.getConstant(X86::COND_GE, MVT::i8),
22573                           SDValue(Neg.getNode(), 1) };
22574         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22575       }
22576   return SDValue();
22577 }
22578
22579 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22580 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22581                                  TargetLowering::DAGCombinerInfo &DCI,
22582                                  const X86Subtarget *Subtarget) {
22583   if (DCI.isBeforeLegalizeOps())
22584     return SDValue();
22585
22586   if (Subtarget->hasCMov()) {
22587     SDValue RV = performIntegerAbsCombine(N, DAG);
22588     if (RV.getNode())
22589       return RV;
22590   }
22591
22592   return SDValue();
22593 }
22594
22595 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22596 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22597                                   TargetLowering::DAGCombinerInfo &DCI,
22598                                   const X86Subtarget *Subtarget) {
22599   LoadSDNode *Ld = cast<LoadSDNode>(N);
22600   EVT RegVT = Ld->getValueType(0);
22601   EVT MemVT = Ld->getMemoryVT();
22602   SDLoc dl(Ld);
22603   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22604
22605   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22606   // into two 16-byte operations.
22607   ISD::LoadExtType Ext = Ld->getExtensionType();
22608   unsigned Alignment = Ld->getAlignment();
22609   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22610   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22611       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22612     unsigned NumElems = RegVT.getVectorNumElements();
22613     if (NumElems < 2)
22614       return SDValue();
22615
22616     SDValue Ptr = Ld->getBasePtr();
22617     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22618
22619     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22620                                   NumElems/2);
22621     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22622                                 Ld->getPointerInfo(), Ld->isVolatile(),
22623                                 Ld->isNonTemporal(), Ld->isInvariant(),
22624                                 Alignment);
22625     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22626     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22627                                 Ld->getPointerInfo(), Ld->isVolatile(),
22628                                 Ld->isNonTemporal(), Ld->isInvariant(),
22629                                 std::min(16U, Alignment));
22630     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22631                              Load1.getValue(1),
22632                              Load2.getValue(1));
22633
22634     SDValue NewVec = DAG.getUNDEF(RegVT);
22635     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22636     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22637     return DCI.CombineTo(N, NewVec, TF, true);
22638   }
22639
22640   return SDValue();
22641 }
22642
22643 /// PerformMLOADCombine - Resolve extending loads
22644 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22645                                    TargetLowering::DAGCombinerInfo &DCI,
22646                                    const X86Subtarget *Subtarget) {
22647   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22648   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22649     return SDValue();
22650
22651   EVT VT = Mld->getValueType(0);
22652   unsigned NumElems = VT.getVectorNumElements();
22653   EVT LdVT = Mld->getMemoryVT();
22654   SDLoc dl(Mld);
22655
22656   assert(LdVT != VT && "Cannot extend to the same type");
22657   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22658   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22659   // From, To sizes and ElemCount must be pow of two
22660   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22661     "Unexpected size for extending masked load");
22662
22663   unsigned SizeRatio  = ToSz / FromSz;
22664   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22665
22666   // Create a type on which we perform the shuffle
22667   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22668           LdVT.getScalarType(), NumElems*SizeRatio);
22669   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22670
22671   // Convert Src0 value
22672   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22673   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22674     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22675     for (unsigned i = 0; i != NumElems; ++i)
22676       ShuffleVec[i] = i * SizeRatio;
22677
22678     // Can't shuffle using an illegal type.
22679     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22680             && "WideVecVT should be legal");
22681     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22682                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22683   }
22684   // Prepare the new mask
22685   SDValue NewMask;
22686   SDValue Mask = Mld->getMask();
22687   if (Mask.getValueType() == VT) {
22688     // Mask and original value have the same type
22689     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22690     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22691     for (unsigned i = 0; i != NumElems; ++i)
22692       ShuffleVec[i] = i * SizeRatio;
22693     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22694       ShuffleVec[i] = NumElems*SizeRatio;
22695     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22696                                    DAG.getConstant(0, WideVecVT),
22697                                    &ShuffleVec[0]);
22698   }
22699   else {
22700     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22701     unsigned WidenNumElts = NumElems*SizeRatio;
22702     unsigned MaskNumElts = VT.getVectorNumElements();
22703     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22704                                      WidenNumElts);
22705
22706     unsigned NumConcat = WidenNumElts / MaskNumElts;
22707     SmallVector<SDValue, 16> Ops(NumConcat);
22708     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22709     Ops[0] = Mask;
22710     for (unsigned i = 1; i != NumConcat; ++i)
22711       Ops[i] = ZeroVal;
22712
22713     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22714   }
22715
22716   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22717                                      Mld->getBasePtr(), NewMask, WideSrc0,
22718                                      Mld->getMemoryVT(), Mld->getMemOperand(),
22719                                      ISD::NON_EXTLOAD);
22720   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22721   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22722
22723 }
22724 /// PerformMSTORECombine - Resolve truncating stores
22725 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22726                                     const X86Subtarget *Subtarget) {
22727   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22728   if (!Mst->isTruncatingStore())
22729     return SDValue();
22730
22731   EVT VT = Mst->getValue().getValueType();
22732   unsigned NumElems = VT.getVectorNumElements();
22733   EVT StVT = Mst->getMemoryVT();
22734   SDLoc dl(Mst);
22735
22736   assert(StVT != VT && "Cannot truncate to the same type");
22737   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22738   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22739
22740   // From, To sizes and ElemCount must be pow of two
22741   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22742     "Unexpected size for truncating masked store");
22743   // We are going to use the original vector elt for storing.
22744   // Accumulated smaller vector elements must be a multiple of the store size.
22745   assert (((NumElems * FromSz) % ToSz) == 0 &&
22746           "Unexpected ratio for truncating masked store");
22747
22748   unsigned SizeRatio  = FromSz / ToSz;
22749   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22750
22751   // Create a type on which we perform the shuffle
22752   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22753           StVT.getScalarType(), NumElems*SizeRatio);
22754
22755   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22756
22757   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
22758   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22759   for (unsigned i = 0; i != NumElems; ++i)
22760     ShuffleVec[i] = i * SizeRatio;
22761
22762   // Can't shuffle using an illegal type.
22763   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22764           && "WideVecVT should be legal");
22765
22766   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22767                                         DAG.getUNDEF(WideVecVT),
22768                                         &ShuffleVec[0]);
22769
22770   SDValue NewMask;
22771   SDValue Mask = Mst->getMask();
22772   if (Mask.getValueType() == VT) {
22773     // Mask and original value have the same type
22774     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22775     for (unsigned i = 0; i != NumElems; ++i)
22776       ShuffleVec[i] = i * SizeRatio;
22777     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22778       ShuffleVec[i] = NumElems*SizeRatio;
22779     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22780                                    DAG.getConstant(0, WideVecVT),
22781                                    &ShuffleVec[0]);
22782   }
22783   else {
22784     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22785     unsigned WidenNumElts = NumElems*SizeRatio;
22786     unsigned MaskNumElts = VT.getVectorNumElements();
22787     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22788                                      WidenNumElts);
22789
22790     unsigned NumConcat = WidenNumElts / MaskNumElts;
22791     SmallVector<SDValue, 16> Ops(NumConcat);
22792     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22793     Ops[0] = Mask;
22794     for (unsigned i = 1; i != NumConcat; ++i)
22795       Ops[i] = ZeroVal;
22796
22797     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22798   }
22799
22800   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
22801                             NewMask, StVT, Mst->getMemOperand(), false);
22802 }
22803 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22804 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22805                                    const X86Subtarget *Subtarget) {
22806   StoreSDNode *St = cast<StoreSDNode>(N);
22807   EVT VT = St->getValue().getValueType();
22808   EVT StVT = St->getMemoryVT();
22809   SDLoc dl(St);
22810   SDValue StoredVal = St->getOperand(1);
22811   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22812
22813   // If we are saving a concatenation of two XMM registers and 32-byte stores
22814   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
22815   unsigned Alignment = St->getAlignment();
22816   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22817   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22818       StVT == VT && !IsAligned) {
22819     unsigned NumElems = VT.getVectorNumElements();
22820     if (NumElems < 2)
22821       return SDValue();
22822
22823     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22824     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22825
22826     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22827     SDValue Ptr0 = St->getBasePtr();
22828     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22829
22830     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22831                                 St->getPointerInfo(), St->isVolatile(),
22832                                 St->isNonTemporal(), Alignment);
22833     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22834                                 St->getPointerInfo(), St->isVolatile(),
22835                                 St->isNonTemporal(),
22836                                 std::min(16U, Alignment));
22837     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22838   }
22839
22840   // Optimize trunc store (of multiple scalars) to shuffle and store.
22841   // First, pack all of the elements in one place. Next, store to memory
22842   // in fewer chunks.
22843   if (St->isTruncatingStore() && VT.isVector()) {
22844     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22845     unsigned NumElems = VT.getVectorNumElements();
22846     assert(StVT != VT && "Cannot truncate to the same type");
22847     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22848     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22849
22850     // From, To sizes and ElemCount must be pow of two
22851     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22852     // We are going to use the original vector elt for storing.
22853     // Accumulated smaller vector elements must be a multiple of the store size.
22854     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22855
22856     unsigned SizeRatio  = FromSz / ToSz;
22857
22858     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22859
22860     // Create a type on which we perform the shuffle
22861     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22862             StVT.getScalarType(), NumElems*SizeRatio);
22863
22864     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22865
22866     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22867     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22868     for (unsigned i = 0; i != NumElems; ++i)
22869       ShuffleVec[i] = i * SizeRatio;
22870
22871     // Can't shuffle using an illegal type.
22872     if (!TLI.isTypeLegal(WideVecVT))
22873       return SDValue();
22874
22875     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22876                                          DAG.getUNDEF(WideVecVT),
22877                                          &ShuffleVec[0]);
22878     // At this point all of the data is stored at the bottom of the
22879     // register. We now need to save it to mem.
22880
22881     // Find the largest store unit
22882     MVT StoreType = MVT::i8;
22883     for (MVT Tp : MVT::integer_valuetypes()) {
22884       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22885         StoreType = Tp;
22886     }
22887
22888     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22889     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22890         (64 <= NumElems * ToSz))
22891       StoreType = MVT::f64;
22892
22893     // Bitcast the original vector into a vector of store-size units
22894     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22895             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22896     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22897     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22898     SmallVector<SDValue, 8> Chains;
22899     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22900                                         TLI.getPointerTy());
22901     SDValue Ptr = St->getBasePtr();
22902
22903     // Perform one or more big stores into memory.
22904     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22905       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22906                                    StoreType, ShuffWide,
22907                                    DAG.getIntPtrConstant(i));
22908       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22909                                 St->getPointerInfo(), St->isVolatile(),
22910                                 St->isNonTemporal(), St->getAlignment());
22911       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22912       Chains.push_back(Ch);
22913     }
22914
22915     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22916   }
22917
22918   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
22919   // the FP state in cases where an emms may be missing.
22920   // A preferable solution to the general problem is to figure out the right
22921   // places to insert EMMS.  This qualifies as a quick hack.
22922
22923   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22924   if (VT.getSizeInBits() != 64)
22925     return SDValue();
22926
22927   const Function *F = DAG.getMachineFunction().getFunction();
22928   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
22929   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22930                      && Subtarget->hasSSE2();
22931   if ((VT.isVector() ||
22932        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22933       isa<LoadSDNode>(St->getValue()) &&
22934       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22935       St->getChain().hasOneUse() && !St->isVolatile()) {
22936     SDNode* LdVal = St->getValue().getNode();
22937     LoadSDNode *Ld = nullptr;
22938     int TokenFactorIndex = -1;
22939     SmallVector<SDValue, 8> Ops;
22940     SDNode* ChainVal = St->getChain().getNode();
22941     // Must be a store of a load.  We currently handle two cases:  the load
22942     // is a direct child, and it's under an intervening TokenFactor.  It is
22943     // possible to dig deeper under nested TokenFactors.
22944     if (ChainVal == LdVal)
22945       Ld = cast<LoadSDNode>(St->getChain());
22946     else if (St->getValue().hasOneUse() &&
22947              ChainVal->getOpcode() == ISD::TokenFactor) {
22948       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22949         if (ChainVal->getOperand(i).getNode() == LdVal) {
22950           TokenFactorIndex = i;
22951           Ld = cast<LoadSDNode>(St->getValue());
22952         } else
22953           Ops.push_back(ChainVal->getOperand(i));
22954       }
22955     }
22956
22957     if (!Ld || !ISD::isNormalLoad(Ld))
22958       return SDValue();
22959
22960     // If this is not the MMX case, i.e. we are just turning i64 load/store
22961     // into f64 load/store, avoid the transformation if there are multiple
22962     // uses of the loaded value.
22963     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22964       return SDValue();
22965
22966     SDLoc LdDL(Ld);
22967     SDLoc StDL(N);
22968     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22969     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22970     // pair instead.
22971     if (Subtarget->is64Bit() || F64IsLegal) {
22972       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22973       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22974                                   Ld->getPointerInfo(), Ld->isVolatile(),
22975                                   Ld->isNonTemporal(), Ld->isInvariant(),
22976                                   Ld->getAlignment());
22977       SDValue NewChain = NewLd.getValue(1);
22978       if (TokenFactorIndex != -1) {
22979         Ops.push_back(NewChain);
22980         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22981       }
22982       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22983                           St->getPointerInfo(),
22984                           St->isVolatile(), St->isNonTemporal(),
22985                           St->getAlignment());
22986     }
22987
22988     // Otherwise, lower to two pairs of 32-bit loads / stores.
22989     SDValue LoAddr = Ld->getBasePtr();
22990     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22991                                  DAG.getConstant(4, MVT::i32));
22992
22993     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22994                                Ld->getPointerInfo(),
22995                                Ld->isVolatile(), Ld->isNonTemporal(),
22996                                Ld->isInvariant(), Ld->getAlignment());
22997     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22998                                Ld->getPointerInfo().getWithOffset(4),
22999                                Ld->isVolatile(), Ld->isNonTemporal(),
23000                                Ld->isInvariant(),
23001                                MinAlign(Ld->getAlignment(), 4));
23002
23003     SDValue NewChain = LoLd.getValue(1);
23004     if (TokenFactorIndex != -1) {
23005       Ops.push_back(LoLd);
23006       Ops.push_back(HiLd);
23007       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23008     }
23009
23010     LoAddr = St->getBasePtr();
23011     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23012                          DAG.getConstant(4, MVT::i32));
23013
23014     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23015                                 St->getPointerInfo(),
23016                                 St->isVolatile(), St->isNonTemporal(),
23017                                 St->getAlignment());
23018     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23019                                 St->getPointerInfo().getWithOffset(4),
23020                                 St->isVolatile(),
23021                                 St->isNonTemporal(),
23022                                 MinAlign(St->getAlignment(), 4));
23023     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23024   }
23025
23026   // This is similar to the above case, but here we handle a scalar 64-bit
23027   // integer store that is extracted from a vector on a 32-bit target.
23028   // If we have SSE2, then we can treat it like a floating-point double
23029   // to get past legalization. The execution dependencies fixup pass will
23030   // choose the optimal machine instruction for the store if this really is
23031   // an integer or v2f32 rather than an f64.
23032   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23033       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23034     SDValue OldExtract = St->getOperand(1);
23035     SDValue ExtOp0 = OldExtract.getOperand(0);
23036     unsigned VecSize = ExtOp0.getValueSizeInBits();
23037     MVT VecVT = MVT::getVectorVT(MVT::f64, VecSize / 64);
23038     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23039     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23040                                      BitCast, OldExtract.getOperand(1));
23041     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23042                         St->getPointerInfo(), St->isVolatile(),
23043                         St->isNonTemporal(), St->getAlignment());
23044   }
23045
23046   return SDValue();
23047 }
23048
23049 /// Return 'true' if this vector operation is "horizontal"
23050 /// and return the operands for the horizontal operation in LHS and RHS.  A
23051 /// horizontal operation performs the binary operation on successive elements
23052 /// of its first operand, then on successive elements of its second operand,
23053 /// returning the resulting values in a vector.  For example, if
23054 ///   A = < float a0, float a1, float a2, float a3 >
23055 /// and
23056 ///   B = < float b0, float b1, float b2, float b3 >
23057 /// then the result of doing a horizontal operation on A and B is
23058 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23059 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23060 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23061 /// set to A, RHS to B, and the routine returns 'true'.
23062 /// Note that the binary operation should have the property that if one of the
23063 /// operands is UNDEF then the result is UNDEF.
23064 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23065   // Look for the following pattern: if
23066   //   A = < float a0, float a1, float a2, float a3 >
23067   //   B = < float b0, float b1, float b2, float b3 >
23068   // and
23069   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23070   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23071   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23072   // which is A horizontal-op B.
23073
23074   // At least one of the operands should be a vector shuffle.
23075   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23076       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23077     return false;
23078
23079   MVT VT = LHS.getSimpleValueType();
23080
23081   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23082          "Unsupported vector type for horizontal add/sub");
23083
23084   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23085   // operate independently on 128-bit lanes.
23086   unsigned NumElts = VT.getVectorNumElements();
23087   unsigned NumLanes = VT.getSizeInBits()/128;
23088   unsigned NumLaneElts = NumElts / NumLanes;
23089   assert((NumLaneElts % 2 == 0) &&
23090          "Vector type should have an even number of elements in each lane");
23091   unsigned HalfLaneElts = NumLaneElts/2;
23092
23093   // View LHS in the form
23094   //   LHS = VECTOR_SHUFFLE A, B, LMask
23095   // If LHS is not a shuffle then pretend it is the shuffle
23096   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23097   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23098   // type VT.
23099   SDValue A, B;
23100   SmallVector<int, 16> LMask(NumElts);
23101   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23102     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23103       A = LHS.getOperand(0);
23104     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23105       B = LHS.getOperand(1);
23106     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23107     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23108   } else {
23109     if (LHS.getOpcode() != ISD::UNDEF)
23110       A = LHS;
23111     for (unsigned i = 0; i != NumElts; ++i)
23112       LMask[i] = i;
23113   }
23114
23115   // Likewise, view RHS in the form
23116   //   RHS = VECTOR_SHUFFLE C, D, RMask
23117   SDValue C, D;
23118   SmallVector<int, 16> RMask(NumElts);
23119   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23120     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23121       C = RHS.getOperand(0);
23122     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23123       D = RHS.getOperand(1);
23124     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23125     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23126   } else {
23127     if (RHS.getOpcode() != ISD::UNDEF)
23128       C = RHS;
23129     for (unsigned i = 0; i != NumElts; ++i)
23130       RMask[i] = i;
23131   }
23132
23133   // Check that the shuffles are both shuffling the same vectors.
23134   if (!(A == C && B == D) && !(A == D && B == C))
23135     return false;
23136
23137   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23138   if (!A.getNode() && !B.getNode())
23139     return false;
23140
23141   // If A and B occur in reverse order in RHS, then "swap" them (which means
23142   // rewriting the mask).
23143   if (A != C)
23144     ShuffleVectorSDNode::commuteMask(RMask);
23145
23146   // At this point LHS and RHS are equivalent to
23147   //   LHS = VECTOR_SHUFFLE A, B, LMask
23148   //   RHS = VECTOR_SHUFFLE A, B, RMask
23149   // Check that the masks correspond to performing a horizontal operation.
23150   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23151     for (unsigned i = 0; i != NumLaneElts; ++i) {
23152       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23153
23154       // Ignore any UNDEF components.
23155       if (LIdx < 0 || RIdx < 0 ||
23156           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23157           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23158         continue;
23159
23160       // Check that successive elements are being operated on.  If not, this is
23161       // not a horizontal operation.
23162       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23163       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23164       if (!(LIdx == Index && RIdx == Index + 1) &&
23165           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23166         return false;
23167     }
23168   }
23169
23170   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23171   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23172   return true;
23173 }
23174
23175 /// Do target-specific dag combines on floating point adds.
23176 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23177                                   const X86Subtarget *Subtarget) {
23178   EVT VT = N->getValueType(0);
23179   SDValue LHS = N->getOperand(0);
23180   SDValue RHS = N->getOperand(1);
23181
23182   // Try to synthesize horizontal adds from adds of shuffles.
23183   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23184        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23185       isHorizontalBinOp(LHS, RHS, true))
23186     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23187   return SDValue();
23188 }
23189
23190 /// Do target-specific dag combines on floating point subs.
23191 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23192                                   const X86Subtarget *Subtarget) {
23193   EVT VT = N->getValueType(0);
23194   SDValue LHS = N->getOperand(0);
23195   SDValue RHS = N->getOperand(1);
23196
23197   // Try to synthesize horizontal subs from subs of shuffles.
23198   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23199        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23200       isHorizontalBinOp(LHS, RHS, false))
23201     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23202   return SDValue();
23203 }
23204
23205 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23206 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23207   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23208
23209   // F[X]OR(0.0, x) -> x
23210   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23211     if (C->getValueAPF().isPosZero())
23212       return N->getOperand(1);
23213
23214   // F[X]OR(x, 0.0) -> x
23215   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23216     if (C->getValueAPF().isPosZero())
23217       return N->getOperand(0);
23218   return SDValue();
23219 }
23220
23221 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23222 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23223   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23224
23225   // Only perform optimizations if UnsafeMath is used.
23226   if (!DAG.getTarget().Options.UnsafeFPMath)
23227     return SDValue();
23228
23229   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23230   // into FMINC and FMAXC, which are Commutative operations.
23231   unsigned NewOp = 0;
23232   switch (N->getOpcode()) {
23233     default: llvm_unreachable("unknown opcode");
23234     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23235     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23236   }
23237
23238   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23239                      N->getOperand(0), N->getOperand(1));
23240 }
23241
23242 /// Do target-specific dag combines on X86ISD::FAND nodes.
23243 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23244   // FAND(0.0, x) -> 0.0
23245   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23246     if (C->getValueAPF().isPosZero())
23247       return N->getOperand(0);
23248
23249   // FAND(x, 0.0) -> 0.0
23250   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23251     if (C->getValueAPF().isPosZero())
23252       return N->getOperand(1);
23253
23254   return SDValue();
23255 }
23256
23257 /// Do target-specific dag combines on X86ISD::FANDN nodes
23258 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23259   // FANDN(0.0, x) -> x
23260   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23261     if (C->getValueAPF().isPosZero())
23262       return N->getOperand(1);
23263
23264   // FANDN(x, 0.0) -> 0.0
23265   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23266     if (C->getValueAPF().isPosZero())
23267       return N->getOperand(1);
23268
23269   return SDValue();
23270 }
23271
23272 static SDValue PerformBTCombine(SDNode *N,
23273                                 SelectionDAG &DAG,
23274                                 TargetLowering::DAGCombinerInfo &DCI) {
23275   // BT ignores high bits in the bit index operand.
23276   SDValue Op1 = N->getOperand(1);
23277   if (Op1.hasOneUse()) {
23278     unsigned BitWidth = Op1.getValueSizeInBits();
23279     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23280     APInt KnownZero, KnownOne;
23281     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23282                                           !DCI.isBeforeLegalizeOps());
23283     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23284     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23285         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23286       DCI.CommitTargetLoweringOpt(TLO);
23287   }
23288   return SDValue();
23289 }
23290
23291 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23292   SDValue Op = N->getOperand(0);
23293   if (Op.getOpcode() == ISD::BITCAST)
23294     Op = Op.getOperand(0);
23295   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23296   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23297       VT.getVectorElementType().getSizeInBits() ==
23298       OpVT.getVectorElementType().getSizeInBits()) {
23299     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23300   }
23301   return SDValue();
23302 }
23303
23304 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23305                                                const X86Subtarget *Subtarget) {
23306   EVT VT = N->getValueType(0);
23307   if (!VT.isVector())
23308     return SDValue();
23309
23310   SDValue N0 = N->getOperand(0);
23311   SDValue N1 = N->getOperand(1);
23312   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23313   SDLoc dl(N);
23314
23315   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23316   // both SSE and AVX2 since there is no sign-extended shift right
23317   // operation on a vector with 64-bit elements.
23318   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23319   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23320   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23321       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23322     SDValue N00 = N0.getOperand(0);
23323
23324     // EXTLOAD has a better solution on AVX2,
23325     // it may be replaced with X86ISD::VSEXT node.
23326     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23327       if (!ISD::isNormalLoad(N00.getNode()))
23328         return SDValue();
23329
23330     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23331         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23332                                   N00, N1);
23333       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23334     }
23335   }
23336   return SDValue();
23337 }
23338
23339 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23340                                   TargetLowering::DAGCombinerInfo &DCI,
23341                                   const X86Subtarget *Subtarget) {
23342   SDValue N0 = N->getOperand(0);
23343   EVT VT = N->getValueType(0);
23344
23345   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23346   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23347   // This exposes the sext to the sdivrem lowering, so that it directly extends
23348   // from AH (which we otherwise need to do contortions to access).
23349   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23350       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23351     SDLoc dl(N);
23352     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23353     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23354                             N0.getOperand(0), N0.getOperand(1));
23355     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23356     return R.getValue(1);
23357   }
23358
23359   if (!DCI.isBeforeLegalizeOps())
23360     return SDValue();
23361
23362   if (!Subtarget->hasFp256())
23363     return SDValue();
23364
23365   if (VT.isVector() && VT.getSizeInBits() == 256) {
23366     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23367     if (R.getNode())
23368       return R;
23369   }
23370
23371   return SDValue();
23372 }
23373
23374 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23375                                  const X86Subtarget* Subtarget) {
23376   SDLoc dl(N);
23377   EVT VT = N->getValueType(0);
23378
23379   // Let legalize expand this if it isn't a legal type yet.
23380   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23381     return SDValue();
23382
23383   EVT ScalarVT = VT.getScalarType();
23384   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23385       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23386     return SDValue();
23387
23388   SDValue A = N->getOperand(0);
23389   SDValue B = N->getOperand(1);
23390   SDValue C = N->getOperand(2);
23391
23392   bool NegA = (A.getOpcode() == ISD::FNEG);
23393   bool NegB = (B.getOpcode() == ISD::FNEG);
23394   bool NegC = (C.getOpcode() == ISD::FNEG);
23395
23396   // Negative multiplication when NegA xor NegB
23397   bool NegMul = (NegA != NegB);
23398   if (NegA)
23399     A = A.getOperand(0);
23400   if (NegB)
23401     B = B.getOperand(0);
23402   if (NegC)
23403     C = C.getOperand(0);
23404
23405   unsigned Opcode;
23406   if (!NegMul)
23407     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23408   else
23409     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23410
23411   return DAG.getNode(Opcode, dl, VT, A, B, C);
23412 }
23413
23414 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23415                                   TargetLowering::DAGCombinerInfo &DCI,
23416                                   const X86Subtarget *Subtarget) {
23417   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23418   //           (and (i32 x86isd::setcc_carry), 1)
23419   // This eliminates the zext. This transformation is necessary because
23420   // ISD::SETCC is always legalized to i8.
23421   SDLoc dl(N);
23422   SDValue N0 = N->getOperand(0);
23423   EVT VT = N->getValueType(0);
23424
23425   if (N0.getOpcode() == ISD::AND &&
23426       N0.hasOneUse() &&
23427       N0.getOperand(0).hasOneUse()) {
23428     SDValue N00 = N0.getOperand(0);
23429     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23430       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23431       if (!C || C->getZExtValue() != 1)
23432         return SDValue();
23433       return DAG.getNode(ISD::AND, dl, VT,
23434                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23435                                      N00.getOperand(0), N00.getOperand(1)),
23436                          DAG.getConstant(1, VT));
23437     }
23438   }
23439
23440   if (N0.getOpcode() == ISD::TRUNCATE &&
23441       N0.hasOneUse() &&
23442       N0.getOperand(0).hasOneUse()) {
23443     SDValue N00 = N0.getOperand(0);
23444     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23445       return DAG.getNode(ISD::AND, dl, VT,
23446                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23447                                      N00.getOperand(0), N00.getOperand(1)),
23448                          DAG.getConstant(1, VT));
23449     }
23450   }
23451   if (VT.is256BitVector()) {
23452     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23453     if (R.getNode())
23454       return R;
23455   }
23456
23457   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23458   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23459   // This exposes the zext to the udivrem lowering, so that it directly extends
23460   // from AH (which we otherwise need to do contortions to access).
23461   if (N0.getOpcode() == ISD::UDIVREM &&
23462       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23463       (VT == MVT::i32 || VT == MVT::i64)) {
23464     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23465     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23466                             N0.getOperand(0), N0.getOperand(1));
23467     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23468     return R.getValue(1);
23469   }
23470
23471   return SDValue();
23472 }
23473
23474 // Optimize x == -y --> x+y == 0
23475 //          x != -y --> x+y != 0
23476 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23477                                       const X86Subtarget* Subtarget) {
23478   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23479   SDValue LHS = N->getOperand(0);
23480   SDValue RHS = N->getOperand(1);
23481   EVT VT = N->getValueType(0);
23482   SDLoc DL(N);
23483
23484   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23485     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23486       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23487         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), LHS.getValueType(), RHS,
23488                                    LHS.getOperand(1));
23489         return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23490                             DAG.getConstant(0, addV.getValueType()), CC);
23491       }
23492   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23493     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23494       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23495         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), RHS.getValueType(), LHS,
23496                                    RHS.getOperand(1));
23497         return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23498                             DAG.getConstant(0, addV.getValueType()), CC);
23499       }
23500
23501   if (VT.getScalarType() == MVT::i1 &&
23502       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23503     bool IsSEXT0 =
23504         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23505         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23506     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23507
23508     if (!IsSEXT0 || !IsVZero1) {
23509       // Swap the operands and update the condition code.
23510       std::swap(LHS, RHS);
23511       CC = ISD::getSetCCSwappedOperands(CC);
23512
23513       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23514                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23515       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23516     }
23517
23518     if (IsSEXT0 && IsVZero1) {
23519       assert(VT == LHS.getOperand(0).getValueType() &&
23520              "Uexpected operand type");
23521       if (CC == ISD::SETGT)
23522         return DAG.getConstant(0, VT);
23523       if (CC == ISD::SETLE)
23524         return DAG.getConstant(1, VT);
23525       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23526         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23527
23528       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23529              "Unexpected condition code!");
23530       return LHS.getOperand(0);
23531     }
23532   }
23533
23534   return SDValue();
23535 }
23536
23537 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23538                                          SelectionDAG &DAG) {
23539   SDLoc dl(Load);
23540   MVT VT = Load->getSimpleValueType(0);
23541   MVT EVT = VT.getVectorElementType();
23542   SDValue Addr = Load->getOperand(1);
23543   SDValue NewAddr = DAG.getNode(
23544       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23545       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
23546
23547   SDValue NewLoad =
23548       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23549                   DAG.getMachineFunction().getMachineMemOperand(
23550                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23551   return NewLoad;
23552 }
23553
23554 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23555                                       const X86Subtarget *Subtarget) {
23556   SDLoc dl(N);
23557   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23558   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23559          "X86insertps is only defined for v4x32");
23560
23561   SDValue Ld = N->getOperand(1);
23562   if (MayFoldLoad(Ld)) {
23563     // Extract the countS bits from the immediate so we can get the proper
23564     // address when narrowing the vector load to a specific element.
23565     // When the second source op is a memory address, insertps doesn't use
23566     // countS and just gets an f32 from that address.
23567     unsigned DestIndex =
23568         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23569
23570     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23571
23572     // Create this as a scalar to vector to match the instruction pattern.
23573     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23574     // countS bits are ignored when loading from memory on insertps, which
23575     // means we don't need to explicitly set them to 0.
23576     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23577                        LoadScalarToVector, N->getOperand(2));
23578   }
23579   return SDValue();
23580 }
23581
23582 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23583   SDValue V0 = N->getOperand(0);
23584   SDValue V1 = N->getOperand(1);
23585   SDLoc DL(N);
23586   EVT VT = N->getValueType(0);
23587
23588   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23589   // operands and changing the mask to 1. This saves us a bunch of
23590   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23591   // x86InstrInfo knows how to commute this back after instruction selection
23592   // if it would help register allocation.
23593
23594   // TODO: If optimizing for size or a processor that doesn't suffer from
23595   // partial register update stalls, this should be transformed into a MOVSD
23596   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23597
23598   if (VT == MVT::v2f64)
23599     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23600       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23601         SDValue NewMask = DAG.getConstant(1, MVT::i8);
23602         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23603       }
23604
23605   return SDValue();
23606 }
23607
23608 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23609 // as "sbb reg,reg", since it can be extended without zext and produces
23610 // an all-ones bit which is more useful than 0/1 in some cases.
23611 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23612                                MVT VT) {
23613   if (VT == MVT::i8)
23614     return DAG.getNode(ISD::AND, DL, VT,
23615                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23616                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23617                        DAG.getConstant(1, VT));
23618   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23619   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23620                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23621                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23622 }
23623
23624 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23625 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23626                                    TargetLowering::DAGCombinerInfo &DCI,
23627                                    const X86Subtarget *Subtarget) {
23628   SDLoc DL(N);
23629   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23630   SDValue EFLAGS = N->getOperand(1);
23631
23632   if (CC == X86::COND_A) {
23633     // Try to convert COND_A into COND_B in an attempt to facilitate
23634     // materializing "setb reg".
23635     //
23636     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23637     // cannot take an immediate as its first operand.
23638     //
23639     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23640         EFLAGS.getValueType().isInteger() &&
23641         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23642       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23643                                    EFLAGS.getNode()->getVTList(),
23644                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23645       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23646       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23647     }
23648   }
23649
23650   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23651   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23652   // cases.
23653   if (CC == X86::COND_B)
23654     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23655
23656   SDValue Flags;
23657
23658   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23659   if (Flags.getNode()) {
23660     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23661     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23662   }
23663
23664   return SDValue();
23665 }
23666
23667 // Optimize branch condition evaluation.
23668 //
23669 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23670                                     TargetLowering::DAGCombinerInfo &DCI,
23671                                     const X86Subtarget *Subtarget) {
23672   SDLoc DL(N);
23673   SDValue Chain = N->getOperand(0);
23674   SDValue Dest = N->getOperand(1);
23675   SDValue EFLAGS = N->getOperand(3);
23676   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23677
23678   SDValue Flags;
23679
23680   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23681   if (Flags.getNode()) {
23682     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23683     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23684                        Flags);
23685   }
23686
23687   return SDValue();
23688 }
23689
23690 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23691                                                          SelectionDAG &DAG) {
23692   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23693   // optimize away operation when it's from a constant.
23694   //
23695   // The general transformation is:
23696   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23697   //       AND(VECTOR_CMP(x,y), constant2)
23698   //    constant2 = UNARYOP(constant)
23699
23700   // Early exit if this isn't a vector operation, the operand of the
23701   // unary operation isn't a bitwise AND, or if the sizes of the operations
23702   // aren't the same.
23703   EVT VT = N->getValueType(0);
23704   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23705       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23706       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23707     return SDValue();
23708
23709   // Now check that the other operand of the AND is a constant. We could
23710   // make the transformation for non-constant splats as well, but it's unclear
23711   // that would be a benefit as it would not eliminate any operations, just
23712   // perform one more step in scalar code before moving to the vector unit.
23713   if (BuildVectorSDNode *BV =
23714           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23715     // Bail out if the vector isn't a constant.
23716     if (!BV->isConstant())
23717       return SDValue();
23718
23719     // Everything checks out. Build up the new and improved node.
23720     SDLoc DL(N);
23721     EVT IntVT = BV->getValueType(0);
23722     // Create a new constant of the appropriate type for the transformed
23723     // DAG.
23724     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23725     // The AND node needs bitcasts to/from an integer vector type around it.
23726     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23727     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23728                                  N->getOperand(0)->getOperand(0), MaskConst);
23729     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23730     return Res;
23731   }
23732
23733   return SDValue();
23734 }
23735
23736 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23737                                         const X86Subtarget *Subtarget) {
23738   // First try to optimize away the conversion entirely when it's
23739   // conditionally from a constant. Vectors only.
23740   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23741   if (Res != SDValue())
23742     return Res;
23743
23744   // Now move on to more general possibilities.
23745   SDValue Op0 = N->getOperand(0);
23746   EVT InVT = Op0->getValueType(0);
23747
23748   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23749   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23750     SDLoc dl(N);
23751     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23752     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23753     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23754   }
23755
23756   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23757   // a 32-bit target where SSE doesn't support i64->FP operations.
23758   if (Op0.getOpcode() == ISD::LOAD) {
23759     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23760     EVT VT = Ld->getValueType(0);
23761     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23762         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23763         !Subtarget->is64Bit() && VT == MVT::i64) {
23764       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
23765           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
23766       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23767       return FILDChain;
23768     }
23769   }
23770   return SDValue();
23771 }
23772
23773 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23774 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23775                                  X86TargetLowering::DAGCombinerInfo &DCI) {
23776   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23777   // the result is either zero or one (depending on the input carry bit).
23778   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23779   if (X86::isZeroNode(N->getOperand(0)) &&
23780       X86::isZeroNode(N->getOperand(1)) &&
23781       // We don't have a good way to replace an EFLAGS use, so only do this when
23782       // dead right now.
23783       SDValue(N, 1).use_empty()) {
23784     SDLoc DL(N);
23785     EVT VT = N->getValueType(0);
23786     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23787     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23788                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23789                                            DAG.getConstant(X86::COND_B,MVT::i8),
23790                                            N->getOperand(2)),
23791                                DAG.getConstant(1, VT));
23792     return DCI.CombineTo(N, Res1, CarryOut);
23793   }
23794
23795   return SDValue();
23796 }
23797
23798 // fold (add Y, (sete  X, 0)) -> adc  0, Y
23799 //      (add Y, (setne X, 0)) -> sbb -1, Y
23800 //      (sub (sete  X, 0), Y) -> sbb  0, Y
23801 //      (sub (setne X, 0), Y) -> adc -1, Y
23802 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23803   SDLoc DL(N);
23804
23805   // Look through ZExts.
23806   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23807   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23808     return SDValue();
23809
23810   SDValue SetCC = Ext.getOperand(0);
23811   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23812     return SDValue();
23813
23814   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23815   if (CC != X86::COND_E && CC != X86::COND_NE)
23816     return SDValue();
23817
23818   SDValue Cmp = SetCC.getOperand(1);
23819   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23820       !X86::isZeroNode(Cmp.getOperand(1)) ||
23821       !Cmp.getOperand(0).getValueType().isInteger())
23822     return SDValue();
23823
23824   SDValue CmpOp0 = Cmp.getOperand(0);
23825   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23826                                DAG.getConstant(1, CmpOp0.getValueType()));
23827
23828   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23829   if (CC == X86::COND_NE)
23830     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23831                        DL, OtherVal.getValueType(), OtherVal,
23832                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23833   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23834                      DL, OtherVal.getValueType(), OtherVal,
23835                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23836 }
23837
23838 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23839 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23840                                  const X86Subtarget *Subtarget) {
23841   EVT VT = N->getValueType(0);
23842   SDValue Op0 = N->getOperand(0);
23843   SDValue Op1 = N->getOperand(1);
23844
23845   // Try to synthesize horizontal adds from adds of shuffles.
23846   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23847        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23848       isHorizontalBinOp(Op0, Op1, true))
23849     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23850
23851   return OptimizeConditionalInDecrement(N, DAG);
23852 }
23853
23854 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23855                                  const X86Subtarget *Subtarget) {
23856   SDValue Op0 = N->getOperand(0);
23857   SDValue Op1 = N->getOperand(1);
23858
23859   // X86 can't encode an immediate LHS of a sub. See if we can push the
23860   // negation into a preceding instruction.
23861   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23862     // If the RHS of the sub is a XOR with one use and a constant, invert the
23863     // immediate. Then add one to the LHS of the sub so we can turn
23864     // X-Y -> X+~Y+1, saving one register.
23865     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23866         isa<ConstantSDNode>(Op1.getOperand(1))) {
23867       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23868       EVT VT = Op0.getValueType();
23869       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23870                                    Op1.getOperand(0),
23871                                    DAG.getConstant(~XorC, VT));
23872       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23873                          DAG.getConstant(C->getAPIntValue()+1, VT));
23874     }
23875   }
23876
23877   // Try to synthesize horizontal adds from adds of shuffles.
23878   EVT VT = N->getValueType(0);
23879   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23880        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23881       isHorizontalBinOp(Op0, Op1, true))
23882     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23883
23884   return OptimizeConditionalInDecrement(N, DAG);
23885 }
23886
23887 /// performVZEXTCombine - Performs build vector combines
23888 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23889                                    TargetLowering::DAGCombinerInfo &DCI,
23890                                    const X86Subtarget *Subtarget) {
23891   SDLoc DL(N);
23892   MVT VT = N->getSimpleValueType(0);
23893   SDValue Op = N->getOperand(0);
23894   MVT OpVT = Op.getSimpleValueType();
23895   MVT OpEltVT = OpVT.getVectorElementType();
23896   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
23897
23898   // (vzext (bitcast (vzext (x)) -> (vzext x)
23899   SDValue V = Op;
23900   while (V.getOpcode() == ISD::BITCAST)
23901     V = V.getOperand(0);
23902
23903   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
23904     MVT InnerVT = V.getSimpleValueType();
23905     MVT InnerEltVT = InnerVT.getVectorElementType();
23906
23907     // If the element sizes match exactly, we can just do one larger vzext. This
23908     // is always an exact type match as vzext operates on integer types.
23909     if (OpEltVT == InnerEltVT) {
23910       assert(OpVT == InnerVT && "Types must match for vzext!");
23911       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
23912     }
23913
23914     // The only other way we can combine them is if only a single element of the
23915     // inner vzext is used in the input to the outer vzext.
23916     if (InnerEltVT.getSizeInBits() < InputBits)
23917       return SDValue();
23918
23919     // In this case, the inner vzext is completely dead because we're going to
23920     // only look at bits inside of the low element. Just do the outer vzext on
23921     // a bitcast of the input to the inner.
23922     return DAG.getNode(X86ISD::VZEXT, DL, VT,
23923                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
23924   }
23925
23926   // Check if we can bypass extracting and re-inserting an element of an input
23927   // vector. Essentialy:
23928   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
23929   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
23930       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
23931       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
23932     SDValue ExtractedV = V.getOperand(0);
23933     SDValue OrigV = ExtractedV.getOperand(0);
23934     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
23935       if (ExtractIdx->getZExtValue() == 0) {
23936         MVT OrigVT = OrigV.getSimpleValueType();
23937         // Extract a subvector if necessary...
23938         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
23939           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
23940           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
23941                                     OrigVT.getVectorNumElements() / Ratio);
23942           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
23943                               DAG.getIntPtrConstant(0));
23944         }
23945         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
23946         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
23947       }
23948   }
23949
23950   return SDValue();
23951 }
23952
23953 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23954                                              DAGCombinerInfo &DCI) const {
23955   SelectionDAG &DAG = DCI.DAG;
23956   switch (N->getOpcode()) {
23957   default: break;
23958   case ISD::EXTRACT_VECTOR_ELT:
23959     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23960   case ISD::VSELECT:
23961   case ISD::SELECT:
23962   case X86ISD::SHRUNKBLEND:
23963     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23964   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
23965   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23966   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
23967   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
23968   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
23969   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
23970   case ISD::SHL:
23971   case ISD::SRA:
23972   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
23973   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
23974   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
23975   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
23976   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
23977   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
23978   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
23979   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
23980   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
23981   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
23982   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
23983   case X86ISD::FXOR:
23984   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
23985   case X86ISD::FMIN:
23986   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
23987   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
23988   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
23989   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
23990   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
23991   case ISD::ANY_EXTEND:
23992   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
23993   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
23994   case ISD::SIGN_EXTEND_INREG:
23995     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23996   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23997   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
23998   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23999   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24000   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24001   case X86ISD::SHUFP:       // Handle all target specific shuffles
24002   case X86ISD::PALIGNR:
24003   case X86ISD::UNPCKH:
24004   case X86ISD::UNPCKL:
24005   case X86ISD::MOVHLPS:
24006   case X86ISD::MOVLHPS:
24007   case X86ISD::PSHUFB:
24008   case X86ISD::PSHUFD:
24009   case X86ISD::PSHUFHW:
24010   case X86ISD::PSHUFLW:
24011   case X86ISD::MOVSS:
24012   case X86ISD::MOVSD:
24013   case X86ISD::VPERMILPI:
24014   case X86ISD::VPERM2X128:
24015   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24016   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24017   case ISD::INTRINSIC_WO_CHAIN:
24018     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24019   case X86ISD::INSERTPS: {
24020     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24021       return PerformINSERTPSCombine(N, DAG, Subtarget);
24022     break;
24023   }
24024   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24025   }
24026
24027   return SDValue();
24028 }
24029
24030 /// isTypeDesirableForOp - Return true if the target has native support for
24031 /// the specified value type and it is 'desirable' to use the type for the
24032 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24033 /// instruction encodings are longer and some i16 instructions are slow.
24034 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24035   if (!isTypeLegal(VT))
24036     return false;
24037   if (VT != MVT::i16)
24038     return true;
24039
24040   switch (Opc) {
24041   default:
24042     return true;
24043   case ISD::LOAD:
24044   case ISD::SIGN_EXTEND:
24045   case ISD::ZERO_EXTEND:
24046   case ISD::ANY_EXTEND:
24047   case ISD::SHL:
24048   case ISD::SRL:
24049   case ISD::SUB:
24050   case ISD::ADD:
24051   case ISD::MUL:
24052   case ISD::AND:
24053   case ISD::OR:
24054   case ISD::XOR:
24055     return false;
24056   }
24057 }
24058
24059 /// IsDesirableToPromoteOp - This method query the target whether it is
24060 /// beneficial for dag combiner to promote the specified node. If true, it
24061 /// should return the desired promotion type by reference.
24062 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24063   EVT VT = Op.getValueType();
24064   if (VT != MVT::i16)
24065     return false;
24066
24067   bool Promote = false;
24068   bool Commute = false;
24069   switch (Op.getOpcode()) {
24070   default: break;
24071   case ISD::LOAD: {
24072     LoadSDNode *LD = cast<LoadSDNode>(Op);
24073     // If the non-extending load has a single use and it's not live out, then it
24074     // might be folded.
24075     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24076                                                      Op.hasOneUse()*/) {
24077       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24078              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24079         // The only case where we'd want to promote LOAD (rather then it being
24080         // promoted as an operand is when it's only use is liveout.
24081         if (UI->getOpcode() != ISD::CopyToReg)
24082           return false;
24083       }
24084     }
24085     Promote = true;
24086     break;
24087   }
24088   case ISD::SIGN_EXTEND:
24089   case ISD::ZERO_EXTEND:
24090   case ISD::ANY_EXTEND:
24091     Promote = true;
24092     break;
24093   case ISD::SHL:
24094   case ISD::SRL: {
24095     SDValue N0 = Op.getOperand(0);
24096     // Look out for (store (shl (load), x)).
24097     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24098       return false;
24099     Promote = true;
24100     break;
24101   }
24102   case ISD::ADD:
24103   case ISD::MUL:
24104   case ISD::AND:
24105   case ISD::OR:
24106   case ISD::XOR:
24107     Commute = true;
24108     // fallthrough
24109   case ISD::SUB: {
24110     SDValue N0 = Op.getOperand(0);
24111     SDValue N1 = Op.getOperand(1);
24112     if (!Commute && MayFoldLoad(N1))
24113       return false;
24114     // Avoid disabling potential load folding opportunities.
24115     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24116       return false;
24117     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24118       return false;
24119     Promote = true;
24120   }
24121   }
24122
24123   PVT = MVT::i32;
24124   return Promote;
24125 }
24126
24127 //===----------------------------------------------------------------------===//
24128 //                           X86 Inline Assembly Support
24129 //===----------------------------------------------------------------------===//
24130
24131 // Helper to match a string separated by whitespace.
24132 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24133   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24134
24135   for (StringRef Piece : Pieces) {
24136     if (!S.startswith(Piece)) // Check if the piece matches.
24137       return false;
24138
24139     S = S.substr(Piece.size());
24140     StringRef::size_type Pos = S.find_first_not_of(" \t");
24141     if (Pos == 0) // We matched a prefix.
24142       return false;
24143
24144     S = S.substr(Pos);
24145   }
24146
24147   return S.empty();
24148 }
24149
24150 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24151
24152   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24153     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24154         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24155         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24156
24157       if (AsmPieces.size() == 3)
24158         return true;
24159       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24160         return true;
24161     }
24162   }
24163   return false;
24164 }
24165
24166 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24167   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24168
24169   std::string AsmStr = IA->getAsmString();
24170
24171   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24172   if (!Ty || Ty->getBitWidth() % 16 != 0)
24173     return false;
24174
24175   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24176   SmallVector<StringRef, 4> AsmPieces;
24177   SplitString(AsmStr, AsmPieces, ";\n");
24178
24179   switch (AsmPieces.size()) {
24180   default: return false;
24181   case 1:
24182     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24183     // we will turn this bswap into something that will be lowered to logical
24184     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24185     // lower so don't worry about this.
24186     // bswap $0
24187     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24188         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24189         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24190         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24191         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24192         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24193       // No need to check constraints, nothing other than the equivalent of
24194       // "=r,0" would be valid here.
24195       return IntrinsicLowering::LowerToByteSwap(CI);
24196     }
24197
24198     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24199     if (CI->getType()->isIntegerTy(16) &&
24200         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24201         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24202          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24203       AsmPieces.clear();
24204       const std::string &ConstraintsStr = IA->getConstraintString();
24205       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24206       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24207       if (clobbersFlagRegisters(AsmPieces))
24208         return IntrinsicLowering::LowerToByteSwap(CI);
24209     }
24210     break;
24211   case 3:
24212     if (CI->getType()->isIntegerTy(32) &&
24213         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24214         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24215         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24216         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24217       AsmPieces.clear();
24218       const std::string &ConstraintsStr = IA->getConstraintString();
24219       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24220       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24221       if (clobbersFlagRegisters(AsmPieces))
24222         return IntrinsicLowering::LowerToByteSwap(CI);
24223     }
24224
24225     if (CI->getType()->isIntegerTy(64)) {
24226       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24227       if (Constraints.size() >= 2 &&
24228           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24229           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24230         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24231         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24232             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24233             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24234           return IntrinsicLowering::LowerToByteSwap(CI);
24235       }
24236     }
24237     break;
24238   }
24239   return false;
24240 }
24241
24242 /// getConstraintType - Given a constraint letter, return the type of
24243 /// constraint it is for this target.
24244 X86TargetLowering::ConstraintType
24245 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24246   if (Constraint.size() == 1) {
24247     switch (Constraint[0]) {
24248     case 'R':
24249     case 'q':
24250     case 'Q':
24251     case 'f':
24252     case 't':
24253     case 'u':
24254     case 'y':
24255     case 'x':
24256     case 'Y':
24257     case 'l':
24258       return C_RegisterClass;
24259     case 'a':
24260     case 'b':
24261     case 'c':
24262     case 'd':
24263     case 'S':
24264     case 'D':
24265     case 'A':
24266       return C_Register;
24267     case 'I':
24268     case 'J':
24269     case 'K':
24270     case 'L':
24271     case 'M':
24272     case 'N':
24273     case 'G':
24274     case 'C':
24275     case 'e':
24276     case 'Z':
24277       return C_Other;
24278     default:
24279       break;
24280     }
24281   }
24282   return TargetLowering::getConstraintType(Constraint);
24283 }
24284
24285 /// Examine constraint type and operand type and determine a weight value.
24286 /// This object must already have been set up with the operand type
24287 /// and the current alternative constraint selected.
24288 TargetLowering::ConstraintWeight
24289   X86TargetLowering::getSingleConstraintMatchWeight(
24290     AsmOperandInfo &info, const char *constraint) const {
24291   ConstraintWeight weight = CW_Invalid;
24292   Value *CallOperandVal = info.CallOperandVal;
24293     // If we don't have a value, we can't do a match,
24294     // but allow it at the lowest weight.
24295   if (!CallOperandVal)
24296     return CW_Default;
24297   Type *type = CallOperandVal->getType();
24298   // Look at the constraint type.
24299   switch (*constraint) {
24300   default:
24301     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24302   case 'R':
24303   case 'q':
24304   case 'Q':
24305   case 'a':
24306   case 'b':
24307   case 'c':
24308   case 'd':
24309   case 'S':
24310   case 'D':
24311   case 'A':
24312     if (CallOperandVal->getType()->isIntegerTy())
24313       weight = CW_SpecificReg;
24314     break;
24315   case 'f':
24316   case 't':
24317   case 'u':
24318     if (type->isFloatingPointTy())
24319       weight = CW_SpecificReg;
24320     break;
24321   case 'y':
24322     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24323       weight = CW_SpecificReg;
24324     break;
24325   case 'x':
24326   case 'Y':
24327     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24328         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24329       weight = CW_Register;
24330     break;
24331   case 'I':
24332     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24333       if (C->getZExtValue() <= 31)
24334         weight = CW_Constant;
24335     }
24336     break;
24337   case 'J':
24338     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24339       if (C->getZExtValue() <= 63)
24340         weight = CW_Constant;
24341     }
24342     break;
24343   case 'K':
24344     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24345       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24346         weight = CW_Constant;
24347     }
24348     break;
24349   case 'L':
24350     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24351       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24352         weight = CW_Constant;
24353     }
24354     break;
24355   case 'M':
24356     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24357       if (C->getZExtValue() <= 3)
24358         weight = CW_Constant;
24359     }
24360     break;
24361   case 'N':
24362     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24363       if (C->getZExtValue() <= 0xff)
24364         weight = CW_Constant;
24365     }
24366     break;
24367   case 'G':
24368   case 'C':
24369     if (isa<ConstantFP>(CallOperandVal)) {
24370       weight = CW_Constant;
24371     }
24372     break;
24373   case 'e':
24374     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24375       if ((C->getSExtValue() >= -0x80000000LL) &&
24376           (C->getSExtValue() <= 0x7fffffffLL))
24377         weight = CW_Constant;
24378     }
24379     break;
24380   case 'Z':
24381     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24382       if (C->getZExtValue() <= 0xffffffff)
24383         weight = CW_Constant;
24384     }
24385     break;
24386   }
24387   return weight;
24388 }
24389
24390 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24391 /// with another that has more specific requirements based on the type of the
24392 /// corresponding operand.
24393 const char *X86TargetLowering::
24394 LowerXConstraint(EVT ConstraintVT) const {
24395   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24396   // 'f' like normal targets.
24397   if (ConstraintVT.isFloatingPoint()) {
24398     if (Subtarget->hasSSE2())
24399       return "Y";
24400     if (Subtarget->hasSSE1())
24401       return "x";
24402   }
24403
24404   return TargetLowering::LowerXConstraint(ConstraintVT);
24405 }
24406
24407 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24408 /// vector.  If it is invalid, don't add anything to Ops.
24409 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24410                                                      std::string &Constraint,
24411                                                      std::vector<SDValue>&Ops,
24412                                                      SelectionDAG &DAG) const {
24413   SDValue Result;
24414
24415   // Only support length 1 constraints for now.
24416   if (Constraint.length() > 1) return;
24417
24418   char ConstraintLetter = Constraint[0];
24419   switch (ConstraintLetter) {
24420   default: break;
24421   case 'I':
24422     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24423       if (C->getZExtValue() <= 31) {
24424         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24425         break;
24426       }
24427     }
24428     return;
24429   case 'J':
24430     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24431       if (C->getZExtValue() <= 63) {
24432         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24433         break;
24434       }
24435     }
24436     return;
24437   case 'K':
24438     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24439       if (isInt<8>(C->getSExtValue())) {
24440         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24441         break;
24442       }
24443     }
24444     return;
24445   case 'L':
24446     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24447       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24448           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24449         Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
24450         break;
24451       }
24452     }
24453     return;
24454   case 'M':
24455     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24456       if (C->getZExtValue() <= 3) {
24457         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24458         break;
24459       }
24460     }
24461     return;
24462   case 'N':
24463     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24464       if (C->getZExtValue() <= 255) {
24465         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24466         break;
24467       }
24468     }
24469     return;
24470   case 'O':
24471     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24472       if (C->getZExtValue() <= 127) {
24473         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24474         break;
24475       }
24476     }
24477     return;
24478   case 'e': {
24479     // 32-bit signed value
24480     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24481       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24482                                            C->getSExtValue())) {
24483         // Widen to 64 bits here to get it sign extended.
24484         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
24485         break;
24486       }
24487     // FIXME gcc accepts some relocatable values here too, but only in certain
24488     // memory models; it's complicated.
24489     }
24490     return;
24491   }
24492   case 'Z': {
24493     // 32-bit unsigned value
24494     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24495       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24496                                            C->getZExtValue())) {
24497         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24498         break;
24499       }
24500     }
24501     // FIXME gcc accepts some relocatable values here too, but only in certain
24502     // memory models; it's complicated.
24503     return;
24504   }
24505   case 'i': {
24506     // Literal immediates are always ok.
24507     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24508       // Widen to 64 bits here to get it sign extended.
24509       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
24510       break;
24511     }
24512
24513     // In any sort of PIC mode addresses need to be computed at runtime by
24514     // adding in a register or some sort of table lookup.  These can't
24515     // be used as immediates.
24516     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24517       return;
24518
24519     // If we are in non-pic codegen mode, we allow the address of a global (with
24520     // an optional displacement) to be used with 'i'.
24521     GlobalAddressSDNode *GA = nullptr;
24522     int64_t Offset = 0;
24523
24524     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24525     while (1) {
24526       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24527         Offset += GA->getOffset();
24528         break;
24529       } else if (Op.getOpcode() == ISD::ADD) {
24530         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24531           Offset += C->getZExtValue();
24532           Op = Op.getOperand(0);
24533           continue;
24534         }
24535       } else if (Op.getOpcode() == ISD::SUB) {
24536         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24537           Offset += -C->getZExtValue();
24538           Op = Op.getOperand(0);
24539           continue;
24540         }
24541       }
24542
24543       // Otherwise, this isn't something we can handle, reject it.
24544       return;
24545     }
24546
24547     const GlobalValue *GV = GA->getGlobal();
24548     // If we require an extra load to get this address, as in PIC mode, we
24549     // can't accept it.
24550     if (isGlobalStubReference(
24551             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24552       return;
24553
24554     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24555                                         GA->getValueType(0), Offset);
24556     break;
24557   }
24558   }
24559
24560   if (Result.getNode()) {
24561     Ops.push_back(Result);
24562     return;
24563   }
24564   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24565 }
24566
24567 std::pair<unsigned, const TargetRegisterClass *>
24568 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24569                                                 const std::string &Constraint,
24570                                                 MVT VT) const {
24571   // First, see if this is a constraint that directly corresponds to an LLVM
24572   // register class.
24573   if (Constraint.size() == 1) {
24574     // GCC Constraint Letters
24575     switch (Constraint[0]) {
24576     default: break;
24577       // TODO: Slight differences here in allocation order and leaving
24578       // RIP in the class. Do they matter any more here than they do
24579       // in the normal allocation?
24580     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24581       if (Subtarget->is64Bit()) {
24582         if (VT == MVT::i32 || VT == MVT::f32)
24583           return std::make_pair(0U, &X86::GR32RegClass);
24584         if (VT == MVT::i16)
24585           return std::make_pair(0U, &X86::GR16RegClass);
24586         if (VT == MVT::i8 || VT == MVT::i1)
24587           return std::make_pair(0U, &X86::GR8RegClass);
24588         if (VT == MVT::i64 || VT == MVT::f64)
24589           return std::make_pair(0U, &X86::GR64RegClass);
24590         break;
24591       }
24592       // 32-bit fallthrough
24593     case 'Q':   // Q_REGS
24594       if (VT == MVT::i32 || VT == MVT::f32)
24595         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24596       if (VT == MVT::i16)
24597         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24598       if (VT == MVT::i8 || VT == MVT::i1)
24599         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24600       if (VT == MVT::i64)
24601         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24602       break;
24603     case 'r':   // GENERAL_REGS
24604     case 'l':   // INDEX_REGS
24605       if (VT == MVT::i8 || VT == MVT::i1)
24606         return std::make_pair(0U, &X86::GR8RegClass);
24607       if (VT == MVT::i16)
24608         return std::make_pair(0U, &X86::GR16RegClass);
24609       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24610         return std::make_pair(0U, &X86::GR32RegClass);
24611       return std::make_pair(0U, &X86::GR64RegClass);
24612     case 'R':   // LEGACY_REGS
24613       if (VT == MVT::i8 || VT == MVT::i1)
24614         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24615       if (VT == MVT::i16)
24616         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24617       if (VT == MVT::i32 || !Subtarget->is64Bit())
24618         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24619       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24620     case 'f':  // FP Stack registers.
24621       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24622       // value to the correct fpstack register class.
24623       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24624         return std::make_pair(0U, &X86::RFP32RegClass);
24625       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24626         return std::make_pair(0U, &X86::RFP64RegClass);
24627       return std::make_pair(0U, &X86::RFP80RegClass);
24628     case 'y':   // MMX_REGS if MMX allowed.
24629       if (!Subtarget->hasMMX()) break;
24630       return std::make_pair(0U, &X86::VR64RegClass);
24631     case 'Y':   // SSE_REGS if SSE2 allowed
24632       if (!Subtarget->hasSSE2()) break;
24633       // FALL THROUGH.
24634     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24635       if (!Subtarget->hasSSE1()) break;
24636
24637       switch (VT.SimpleTy) {
24638       default: break;
24639       // Scalar SSE types.
24640       case MVT::f32:
24641       case MVT::i32:
24642         return std::make_pair(0U, &X86::FR32RegClass);
24643       case MVT::f64:
24644       case MVT::i64:
24645         return std::make_pair(0U, &X86::FR64RegClass);
24646       // Vector types.
24647       case MVT::v16i8:
24648       case MVT::v8i16:
24649       case MVT::v4i32:
24650       case MVT::v2i64:
24651       case MVT::v4f32:
24652       case MVT::v2f64:
24653         return std::make_pair(0U, &X86::VR128RegClass);
24654       // AVX types.
24655       case MVT::v32i8:
24656       case MVT::v16i16:
24657       case MVT::v8i32:
24658       case MVT::v4i64:
24659       case MVT::v8f32:
24660       case MVT::v4f64:
24661         return std::make_pair(0U, &X86::VR256RegClass);
24662       case MVT::v8f64:
24663       case MVT::v16f32:
24664       case MVT::v16i32:
24665       case MVT::v8i64:
24666         return std::make_pair(0U, &X86::VR512RegClass);
24667       }
24668       break;
24669     }
24670   }
24671
24672   // Use the default implementation in TargetLowering to convert the register
24673   // constraint into a member of a register class.
24674   std::pair<unsigned, const TargetRegisterClass*> Res;
24675   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24676
24677   // Not found as a standard register?
24678   if (!Res.second) {
24679     // Map st(0) -> st(7) -> ST0
24680     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24681         tolower(Constraint[1]) == 's' &&
24682         tolower(Constraint[2]) == 't' &&
24683         Constraint[3] == '(' &&
24684         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24685         Constraint[5] == ')' &&
24686         Constraint[6] == '}') {
24687
24688       Res.first = X86::FP0+Constraint[4]-'0';
24689       Res.second = &X86::RFP80RegClass;
24690       return Res;
24691     }
24692
24693     // GCC allows "st(0)" to be called just plain "st".
24694     if (StringRef("{st}").equals_lower(Constraint)) {
24695       Res.first = X86::FP0;
24696       Res.second = &X86::RFP80RegClass;
24697       return Res;
24698     }
24699
24700     // flags -> EFLAGS
24701     if (StringRef("{flags}").equals_lower(Constraint)) {
24702       Res.first = X86::EFLAGS;
24703       Res.second = &X86::CCRRegClass;
24704       return Res;
24705     }
24706
24707     // 'A' means EAX + EDX.
24708     if (Constraint == "A") {
24709       Res.first = X86::EAX;
24710       Res.second = &X86::GR32_ADRegClass;
24711       return Res;
24712     }
24713     return Res;
24714   }
24715
24716   // Otherwise, check to see if this is a register class of the wrong value
24717   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24718   // turn into {ax},{dx}.
24719   if (Res.second->hasType(VT))
24720     return Res;   // Correct type already, nothing to do.
24721
24722   // All of the single-register GCC register classes map their values onto
24723   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
24724   // really want an 8-bit or 32-bit register, map to the appropriate register
24725   // class and return the appropriate register.
24726   if (Res.second == &X86::GR16RegClass) {
24727     if (VT == MVT::i8 || VT == MVT::i1) {
24728       unsigned DestReg = 0;
24729       switch (Res.first) {
24730       default: break;
24731       case X86::AX: DestReg = X86::AL; break;
24732       case X86::DX: DestReg = X86::DL; break;
24733       case X86::CX: DestReg = X86::CL; break;
24734       case X86::BX: DestReg = X86::BL; break;
24735       }
24736       if (DestReg) {
24737         Res.first = DestReg;
24738         Res.second = &X86::GR8RegClass;
24739       }
24740     } else if (VT == MVT::i32 || VT == MVT::f32) {
24741       unsigned DestReg = 0;
24742       switch (Res.first) {
24743       default: break;
24744       case X86::AX: DestReg = X86::EAX; break;
24745       case X86::DX: DestReg = X86::EDX; break;
24746       case X86::CX: DestReg = X86::ECX; break;
24747       case X86::BX: DestReg = X86::EBX; break;
24748       case X86::SI: DestReg = X86::ESI; break;
24749       case X86::DI: DestReg = X86::EDI; break;
24750       case X86::BP: DestReg = X86::EBP; break;
24751       case X86::SP: DestReg = X86::ESP; break;
24752       }
24753       if (DestReg) {
24754         Res.first = DestReg;
24755         Res.second = &X86::GR32RegClass;
24756       }
24757     } else if (VT == MVT::i64 || VT == MVT::f64) {
24758       unsigned DestReg = 0;
24759       switch (Res.first) {
24760       default: break;
24761       case X86::AX: DestReg = X86::RAX; break;
24762       case X86::DX: DestReg = X86::RDX; break;
24763       case X86::CX: DestReg = X86::RCX; break;
24764       case X86::BX: DestReg = X86::RBX; break;
24765       case X86::SI: DestReg = X86::RSI; break;
24766       case X86::DI: DestReg = X86::RDI; break;
24767       case X86::BP: DestReg = X86::RBP; break;
24768       case X86::SP: DestReg = X86::RSP; break;
24769       }
24770       if (DestReg) {
24771         Res.first = DestReg;
24772         Res.second = &X86::GR64RegClass;
24773       }
24774     }
24775   } else if (Res.second == &X86::FR32RegClass ||
24776              Res.second == &X86::FR64RegClass ||
24777              Res.second == &X86::VR128RegClass ||
24778              Res.second == &X86::VR256RegClass ||
24779              Res.second == &X86::FR32XRegClass ||
24780              Res.second == &X86::FR64XRegClass ||
24781              Res.second == &X86::VR128XRegClass ||
24782              Res.second == &X86::VR256XRegClass ||
24783              Res.second == &X86::VR512RegClass) {
24784     // Handle references to XMM physical registers that got mapped into the
24785     // wrong class.  This can happen with constraints like {xmm0} where the
24786     // target independent register mapper will just pick the first match it can
24787     // find, ignoring the required type.
24788
24789     if (VT == MVT::f32 || VT == MVT::i32)
24790       Res.second = &X86::FR32RegClass;
24791     else if (VT == MVT::f64 || VT == MVT::i64)
24792       Res.second = &X86::FR64RegClass;
24793     else if (X86::VR128RegClass.hasType(VT))
24794       Res.second = &X86::VR128RegClass;
24795     else if (X86::VR256RegClass.hasType(VT))
24796       Res.second = &X86::VR256RegClass;
24797     else if (X86::VR512RegClass.hasType(VT))
24798       Res.second = &X86::VR512RegClass;
24799   }
24800
24801   return Res;
24802 }
24803
24804 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24805                                             Type *Ty) const {
24806   // Scaling factors are not free at all.
24807   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24808   // will take 2 allocations in the out of order engine instead of 1
24809   // for plain addressing mode, i.e. inst (reg1).
24810   // E.g.,
24811   // vaddps (%rsi,%drx), %ymm0, %ymm1
24812   // Requires two allocations (one for the load, one for the computation)
24813   // whereas:
24814   // vaddps (%rsi), %ymm0, %ymm1
24815   // Requires just 1 allocation, i.e., freeing allocations for other operations
24816   // and having less micro operations to execute.
24817   //
24818   // For some X86 architectures, this is even worse because for instance for
24819   // stores, the complex addressing mode forces the instruction to use the
24820   // "load" ports instead of the dedicated "store" port.
24821   // E.g., on Haswell:
24822   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24823   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24824   if (isLegalAddressingMode(AM, Ty))
24825     // Scale represents reg2 * scale, thus account for 1
24826     // as soon as we use a second register.
24827     return AM.Scale != 0;
24828   return -1;
24829 }
24830
24831 bool X86TargetLowering::isTargetFTOL() const {
24832   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
24833 }