109047751791be80a6644935a70ebfa8a84ad375
[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 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71                                      const X86Subtarget &STI)
72     : TargetLowering(TM), Subtarget(&STI) {
73   X86ScalarSSEf64 = Subtarget->hasSSE2();
74   X86ScalarSSEf32 = Subtarget->hasSSE1();
75   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
76
77   // Set up the TargetLowering object.
78   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
79
80   // X86 is weird. It always uses i8 for shift amounts and setcc results.
81   setBooleanContents(ZeroOrOneBooleanContent);
82   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
84
85   // For 64-bit, since we have so many registers, use the ILP scheduler.
86   // For 32-bit, use the register pressure specific scheduling.
87   // For Atom, always use ILP scheduling.
88   if (Subtarget->isAtom())
89     setSchedulingPreference(Sched::ILP);
90   else if (Subtarget->is64Bit())
91     setSchedulingPreference(Sched::ILP);
92   else
93     setSchedulingPreference(Sched::RegPressure);
94   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
96
97   // Bypass expensive divides on Atom when compiling with O2.
98   if (TM.getOptLevel() >= CodeGenOpt::Default) {
99     if (Subtarget->hasSlowDivide32())
100       addBypassSlowDiv(32, 8);
101     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102       addBypassSlowDiv(64, 16);
103   }
104
105   if (Subtarget->isTargetKnownWindowsMSVC()) {
106     // Setup Windows compiler runtime calls.
107     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109     setLibcallName(RTLIB::SREM_I64, "_allrem");
110     setLibcallName(RTLIB::UREM_I64, "_aullrem");
111     setLibcallName(RTLIB::MUL_I64, "_allmul");
112     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
117
118     // The _ftol2 runtime function has an unusual calling conv, which
119     // is modeled by a special pseudo-instruction.
120     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
121     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
122     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
123     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
124   }
125
126   if (Subtarget->isTargetDarwin()) {
127     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
128     setUseUnderscoreSetJmp(false);
129     setUseUnderscoreLongJmp(false);
130   } else if (Subtarget->isTargetWindowsGNU()) {
131     // MS runtime is weird: it exports _setjmp, but longjmp!
132     setUseUnderscoreSetJmp(true);
133     setUseUnderscoreLongJmp(false);
134   } else {
135     setUseUnderscoreSetJmp(true);
136     setUseUnderscoreLongJmp(true);
137   }
138
139   // Set up the register classes.
140   addRegisterClass(MVT::i8, &X86::GR8RegClass);
141   addRegisterClass(MVT::i16, &X86::GR16RegClass);
142   addRegisterClass(MVT::i32, &X86::GR32RegClass);
143   if (Subtarget->is64Bit())
144     addRegisterClass(MVT::i64, &X86::GR64RegClass);
145
146   for (MVT VT : MVT::integer_valuetypes())
147     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
148
149   // We don't accept any truncstore of integer registers.
150   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
151   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
152   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
153   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
154   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
155   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
156
157   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
158
159   // SETOEQ and SETUNE require checking two conditions.
160   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
161   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
162   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
163   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
164   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
165   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
166
167   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
168   // operation.
169   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
170   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
171   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
172
173   if (Subtarget->is64Bit()) {
174     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
175     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
176   } else if (!Subtarget->useSoftFloat()) {
177     // We have an algorithm for SSE2->double, and we turn this into a
178     // 64-bit FILD followed by conditional FADD for other targets.
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
180     // We have an algorithm for SSE2, and we turn this into a 64-bit
181     // FILD for other targets.
182     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
183   }
184
185   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
186   // this operation.
187   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
188   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
189
190   if (!Subtarget->useSoftFloat()) {
191     // SSE has no i16 to fp conversion, only i32
192     if (X86ScalarSSEf32) {
193       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
194       // f32 and f64 cases are Legal, f80 case is not
195       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
196     } else {
197       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
198       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
199     }
200   } else {
201     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
202     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
203   }
204
205   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
206   // are Legal, f80 is custom lowered.
207   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
208   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
209
210   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
211   // this operation.
212   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
213   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
214
215   if (X86ScalarSSEf32) {
216     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
217     // f32 and f64 cases are Legal, f80 case is not
218     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
219   } else {
220     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
221     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
222   }
223
224   // Handle FP_TO_UINT by promoting the destination to a larger signed
225   // conversion.
226   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
227   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
228   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
229
230   if (Subtarget->is64Bit()) {
231     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
232     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
233   } else if (!Subtarget->useSoftFloat()) {
234     // Since AVX is a superset of SSE3, only check for SSE here.
235     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
236       // Expand FP_TO_UINT into a select.
237       // FIXME: We would like to use a Custom expander here eventually to do
238       // the optimal thing for SSE vs. the default expansion in the legalizer.
239       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
240     else
241       // With SSE3 we can use fisttpll to convert to a signed i64; without
242       // SSE, we're stuck with a fistpll.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
244   }
245
246   if (isTargetFTOL()) {
247     // Use the _ftol2 runtime function, which has a pseudo-instruction
248     // to handle its weird calling convention.
249     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
250   }
251
252   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
253   if (!X86ScalarSSEf64) {
254     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
255     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
256     if (Subtarget->is64Bit()) {
257       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
258       // Without SSE, i64->f64 goes through memory.
259       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
260     }
261   }
262
263   // Scalar integer divide and remainder are lowered to use operations that
264   // produce two results, to match the available instructions. This exposes
265   // the two-result form to trivial CSE, which is able to combine x/y and x%y
266   // into a single instruction.
267   //
268   // Scalar integer multiply-high is also lowered to use two-result
269   // operations, to match the available instructions. However, plain multiply
270   // (low) operations are left as Legal, as there are single-result
271   // instructions for this in x86. Using the two-result multiply instructions
272   // when both high and low results are needed must be arranged by dagcombine.
273   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
274     MVT VT = IntVTs[i];
275     setOperationAction(ISD::MULHS, VT, Expand);
276     setOperationAction(ISD::MULHU, VT, Expand);
277     setOperationAction(ISD::SDIV, VT, Expand);
278     setOperationAction(ISD::UDIV, VT, Expand);
279     setOperationAction(ISD::SREM, VT, Expand);
280     setOperationAction(ISD::UREM, VT, Expand);
281
282     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
283     setOperationAction(ISD::ADDC, VT, Custom);
284     setOperationAction(ISD::ADDE, VT, Custom);
285     setOperationAction(ISD::SUBC, VT, Custom);
286     setOperationAction(ISD::SUBE, VT, Custom);
287   }
288
289   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
290   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
291   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
292   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
293   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
294   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
295   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
298   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
299   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
300   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
301   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
305   if (Subtarget->is64Bit())
306     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
307   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
308   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
309   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
310   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
311   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
312   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
313   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
314   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
315
316   // Promote the i8 variants and force them on up to i32 which has a shorter
317   // encoding.
318   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
319   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
320   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
321   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
322   if (Subtarget->hasBMI()) {
323     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
324     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
325     if (Subtarget->is64Bit())
326       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
327   } else {
328     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
329     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
330     if (Subtarget->is64Bit())
331       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
332   }
333
334   if (Subtarget->hasLZCNT()) {
335     // When promoting the i8 variants, force them to i32 for a shorter
336     // encoding.
337     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
338     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
339     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
340     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
341     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
342     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
343     if (Subtarget->is64Bit())
344       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
345   } else {
346     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
347     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
348     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
350     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
352     if (Subtarget->is64Bit()) {
353       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
354       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
355     }
356   }
357
358   // Special handling for half-precision floating point conversions.
359   // If we don't have F16C support, then lower half float conversions
360   // into library calls.
361   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
362     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
363     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
364   }
365
366   // There's never any support for operations beyond MVT::f32.
367   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
368   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
369   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
370   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
371
372   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
373   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
374   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
375   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
376   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
377   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
378
379   if (Subtarget->hasPOPCNT()) {
380     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
381   } else {
382     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
383     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
384     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
385     if (Subtarget->is64Bit())
386       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
387   }
388
389   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
390
391   if (!Subtarget->hasMOVBE())
392     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
393
394   // These should be promoted to a larger select which is supported.
395   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
396   // X86 wants to expand cmov itself.
397   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
398   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
399   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
400   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
401   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
402   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
403   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
404   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
405   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
406   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
407   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
408   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
409   if (Subtarget->is64Bit()) {
410     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
411     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
412   }
413   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
414   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
415   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
416   // support continuation, user-level threading, and etc.. As a result, no
417   // other SjLj exception interfaces are implemented and please don't build
418   // your own exception handling based on them.
419   // LLVM/Clang supports zero-cost DWARF exception handling.
420   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
421   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
422
423   // Darwin ABI issue.
424   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
425   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
426   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
427   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
428   if (Subtarget->is64Bit())
429     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
430   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
431   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
432   if (Subtarget->is64Bit()) {
433     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
434     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
435     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
436     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
437     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
438   }
439   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
440   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
441   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
442   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
443   if (Subtarget->is64Bit()) {
444     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
445     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
446     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
447   }
448
449   if (Subtarget->hasSSE1())
450     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
451
452   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
453
454   // Expand certain atomics
455   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
456     MVT VT = IntVTs[i];
457     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
458     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
459     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
460   }
461
462   if (Subtarget->hasCmpxchg16b()) {
463     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
464   }
465
466   // FIXME - use subtarget debug flags
467   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
468       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
469     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
470   }
471
472   if (Subtarget->is64Bit()) {
473     setExceptionPointerRegister(X86::RAX);
474     setExceptionSelectorRegister(X86::RDX);
475   } else {
476     setExceptionPointerRegister(X86::EAX);
477     setExceptionSelectorRegister(X86::EDX);
478   }
479   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
480   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
481
482   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
483   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
484
485   setOperationAction(ISD::TRAP, MVT::Other, Legal);
486   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
487
488   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
489   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
490   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
491   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
492     // TargetInfo::X86_64ABIBuiltinVaList
493     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
494     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
495   } else {
496     // TargetInfo::CharPtrBuiltinVaList
497     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
498     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
499   }
500
501   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
502   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
503
504   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
505
506   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
507   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
508   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
509
510   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
511     // f32 and f64 use SSE.
512     // Set up the FP register classes.
513     addRegisterClass(MVT::f32, &X86::FR32RegClass);
514     addRegisterClass(MVT::f64, &X86::FR64RegClass);
515
516     // Use ANDPD to simulate FABS.
517     setOperationAction(ISD::FABS , MVT::f64, Custom);
518     setOperationAction(ISD::FABS , MVT::f32, Custom);
519
520     // Use XORP to simulate FNEG.
521     setOperationAction(ISD::FNEG , MVT::f64, Custom);
522     setOperationAction(ISD::FNEG , MVT::f32, Custom);
523
524     // Use ANDPD and ORPD to simulate FCOPYSIGN.
525     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
526     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
527
528     // Lower this to FGETSIGNx86 plus an AND.
529     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
530     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
531
532     // We don't support sin/cos/fmod
533     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
534     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
535     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
536     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
537     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
538     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
539
540     // Expand FP immediates into loads from the stack, except for the special
541     // cases we handle.
542     addLegalFPImmediate(APFloat(+0.0)); // xorpd
543     addLegalFPImmediate(APFloat(+0.0f)); // xorps
544   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
545     // Use SSE for f32, x87 for f64.
546     // Set up the FP register classes.
547     addRegisterClass(MVT::f32, &X86::FR32RegClass);
548     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
549
550     // Use ANDPS to simulate FABS.
551     setOperationAction(ISD::FABS , MVT::f32, Custom);
552
553     // Use XORP to simulate FNEG.
554     setOperationAction(ISD::FNEG , MVT::f32, Custom);
555
556     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
557
558     // Use ANDPS and ORPS to simulate FCOPYSIGN.
559     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
560     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
561
562     // We don't support sin/cos/fmod
563     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
564     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
565     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
566
567     // Special cases we handle for FP constants.
568     addLegalFPImmediate(APFloat(+0.0f)); // xorps
569     addLegalFPImmediate(APFloat(+0.0)); // FLD0
570     addLegalFPImmediate(APFloat(+1.0)); // FLD1
571     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
572     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
573
574     if (!TM.Options.UnsafeFPMath) {
575       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
576       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
577       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
578     }
579   } else if (!Subtarget->useSoftFloat()) {
580     // f32 and f64 in x87.
581     // Set up the FP register classes.
582     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
583     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
584
585     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
586     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
587     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
588     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
589
590     if (!TM.Options.UnsafeFPMath) {
591       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
592       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
593       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
594       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
595       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
596       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
597     }
598     addLegalFPImmediate(APFloat(+0.0)); // FLD0
599     addLegalFPImmediate(APFloat(+1.0)); // FLD1
600     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
601     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
602     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
606   }
607
608   // We don't support FMA.
609   setOperationAction(ISD::FMA, MVT::f64, Expand);
610   setOperationAction(ISD::FMA, MVT::f32, Expand);
611
612   // Long double always uses X87.
613   if (!Subtarget->useSoftFloat()) {
614     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
615     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
616     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
617     {
618       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
619       addLegalFPImmediate(TmpFlt);  // FLD0
620       TmpFlt.changeSign();
621       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
622
623       bool ignored;
624       APFloat TmpFlt2(+1.0);
625       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
626                       &ignored);
627       addLegalFPImmediate(TmpFlt2);  // FLD1
628       TmpFlt2.changeSign();
629       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
630     }
631
632     if (!TM.Options.UnsafeFPMath) {
633       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
634       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
635       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
636     }
637
638     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
639     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
640     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
641     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
642     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
643     setOperationAction(ISD::FMA, MVT::f80, Expand);
644   }
645
646   // Always use a library call for pow.
647   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
648   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
649   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
650
651   setOperationAction(ISD::FLOG, MVT::f80, Expand);
652   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
653   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
654   setOperationAction(ISD::FEXP, MVT::f80, Expand);
655   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
656   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
657   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
658
659   // First set operation action for all vector types to either promote
660   // (for widening) or expand (for scalarization). Then we will selectively
661   // turn on ones that can be effectively codegen'd.
662   for (MVT VT : MVT::vector_valuetypes()) {
663     setOperationAction(ISD::ADD , VT, Expand);
664     setOperationAction(ISD::SUB , VT, Expand);
665     setOperationAction(ISD::FADD, VT, Expand);
666     setOperationAction(ISD::FNEG, VT, Expand);
667     setOperationAction(ISD::FSUB, VT, Expand);
668     setOperationAction(ISD::MUL , VT, Expand);
669     setOperationAction(ISD::FMUL, VT, Expand);
670     setOperationAction(ISD::SDIV, VT, Expand);
671     setOperationAction(ISD::UDIV, VT, Expand);
672     setOperationAction(ISD::FDIV, VT, Expand);
673     setOperationAction(ISD::SREM, VT, Expand);
674     setOperationAction(ISD::UREM, VT, Expand);
675     setOperationAction(ISD::LOAD, VT, Expand);
676     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
677     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
678     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
679     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
680     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
681     setOperationAction(ISD::FABS, VT, Expand);
682     setOperationAction(ISD::FSIN, VT, Expand);
683     setOperationAction(ISD::FSINCOS, VT, Expand);
684     setOperationAction(ISD::FCOS, VT, Expand);
685     setOperationAction(ISD::FSINCOS, VT, Expand);
686     setOperationAction(ISD::FREM, VT, Expand);
687     setOperationAction(ISD::FMA,  VT, Expand);
688     setOperationAction(ISD::FPOWI, VT, Expand);
689     setOperationAction(ISD::FSQRT, VT, Expand);
690     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
691     setOperationAction(ISD::FFLOOR, VT, Expand);
692     setOperationAction(ISD::FCEIL, VT, Expand);
693     setOperationAction(ISD::FTRUNC, VT, Expand);
694     setOperationAction(ISD::FRINT, VT, Expand);
695     setOperationAction(ISD::FNEARBYINT, VT, Expand);
696     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
697     setOperationAction(ISD::MULHS, VT, Expand);
698     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
699     setOperationAction(ISD::MULHU, VT, Expand);
700     setOperationAction(ISD::SDIVREM, VT, Expand);
701     setOperationAction(ISD::UDIVREM, VT, Expand);
702     setOperationAction(ISD::FPOW, VT, Expand);
703     setOperationAction(ISD::CTPOP, VT, Expand);
704     setOperationAction(ISD::CTTZ, VT, Expand);
705     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
706     setOperationAction(ISD::CTLZ, VT, Expand);
707     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
708     setOperationAction(ISD::SHL, VT, Expand);
709     setOperationAction(ISD::SRA, VT, Expand);
710     setOperationAction(ISD::SRL, VT, Expand);
711     setOperationAction(ISD::ROTL, VT, Expand);
712     setOperationAction(ISD::ROTR, VT, Expand);
713     setOperationAction(ISD::BSWAP, VT, Expand);
714     setOperationAction(ISD::SETCC, VT, Expand);
715     setOperationAction(ISD::FLOG, VT, Expand);
716     setOperationAction(ISD::FLOG2, VT, Expand);
717     setOperationAction(ISD::FLOG10, VT, Expand);
718     setOperationAction(ISD::FEXP, VT, Expand);
719     setOperationAction(ISD::FEXP2, VT, Expand);
720     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
721     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
722     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
723     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
724     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
725     setOperationAction(ISD::TRUNCATE, VT, Expand);
726     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
727     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
728     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
729     setOperationAction(ISD::VSELECT, VT, Expand);
730     setOperationAction(ISD::SELECT_CC, VT, Expand);
731     for (MVT InnerVT : MVT::vector_valuetypes()) {
732       setTruncStoreAction(InnerVT, VT, Expand);
733
734       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
735       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
736
737       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
738       // types, we have to deal with them whether we ask for Expansion or not.
739       // Setting Expand causes its own optimisation problems though, so leave
740       // them legal.
741       if (VT.getVectorElementType() == MVT::i1)
742         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
743
744       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
745       // split/scalarized right now.
746       if (VT.getVectorElementType() == MVT::f16)
747         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
748     }
749   }
750
751   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
752   // with -msoft-float, disable use of MMX as well.
753   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
754     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
755     // No operations on x86mmx supported, everything uses intrinsics.
756   }
757
758   // MMX-sized vectors (other than x86mmx) are expected to be expanded
759   // into smaller operations.
760   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
761     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
762     setOperationAction(ISD::AND,                MMXTy,      Expand);
763     setOperationAction(ISD::OR,                 MMXTy,      Expand);
764     setOperationAction(ISD::XOR,                MMXTy,      Expand);
765     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
766     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
767     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
768   }
769   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
770
771   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
772     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
773
774     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
775     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
776     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
777     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
778     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
779     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
780     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
781     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
782     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
783     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
784     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
785     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
786     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
787     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
788   }
789
790   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
791     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
792
793     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
794     // registers cannot be used even for integer operations.
795     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
796     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
797     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
798     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
799
800     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
801     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
802     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
803     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
804     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
805     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
806     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
807     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
808     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
809     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
810     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
811     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
812     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
813     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
814     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
815     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
816     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
817     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
818     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
819     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
820     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
821     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
822     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
823
824     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
825     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
826     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
827     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
828
829     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
830     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
831     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
832     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
833
834     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
835     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
836     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
837     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
838     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
839
840     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
841     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
842     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
843     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
844
845     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
846     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
847       MVT VT = (MVT::SimpleValueType)i;
848       // Do not attempt to custom lower non-power-of-2 vectors
849       if (!isPowerOf2_32(VT.getVectorNumElements()))
850         continue;
851       // Do not attempt to custom lower non-128-bit vectors
852       if (!VT.is128BitVector())
853         continue;
854       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
855       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
856       setOperationAction(ISD::VSELECT,            VT, Custom);
857       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
858     }
859
860     // We support custom legalizing of sext and anyext loads for specific
861     // memory vector types which we can load as a scalar (or sequence of
862     // scalars) and extend in-register to a legal 128-bit vector type. For sext
863     // loads these must work with a single scalar load.
864     for (MVT VT : MVT::integer_vector_valuetypes()) {
865       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
866       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
867       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
868       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
869       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
870       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
871       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
874     }
875
876     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
877     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
878     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
879     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
880     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
881     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
882     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
883     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
884
885     if (Subtarget->is64Bit()) {
886       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
887       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
888     }
889
890     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
891     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
892       MVT VT = (MVT::SimpleValueType)i;
893
894       // Do not attempt to promote non-128-bit vectors
895       if (!VT.is128BitVector())
896         continue;
897
898       setOperationAction(ISD::AND,    VT, Promote);
899       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
900       setOperationAction(ISD::OR,     VT, Promote);
901       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
902       setOperationAction(ISD::XOR,    VT, Promote);
903       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
904       setOperationAction(ISD::LOAD,   VT, Promote);
905       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
906       setOperationAction(ISD::SELECT, VT, Promote);
907       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
908     }
909
910     // Custom lower v2i64 and v2f64 selects.
911     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
912     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
913     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
914     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
915
916     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
917     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
918
919     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
920
921     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
922     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
923     // As there is no 64-bit GPR available, we need build a special custom
924     // sequence to convert from v2i32 to v2f32.
925     if (!Subtarget->is64Bit())
926       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
927
928     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
929     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
930
931     for (MVT VT : MVT::fp_vector_valuetypes())
932       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
933
934     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
935     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
936     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
937   }
938
939   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
940     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
941       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
942       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
943       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
944       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
945       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
946     }
947
948     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
949     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
950     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
951     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
952     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
953     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
954     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
955     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
956
957     // FIXME: Do we need to handle scalar-to-vector here?
958     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
959
960     // We directly match byte blends in the backend as they match the VSELECT
961     // condition form.
962     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
963
964     // SSE41 brings specific instructions for doing vector sign extend even in
965     // cases where we don't have SRA.
966     for (MVT VT : MVT::integer_vector_valuetypes()) {
967       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
968       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
969       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
970     }
971
972     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
973     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
974     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
975     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
976     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
979
980     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
981     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
982     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
983     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
986
987     // i8 and i16 vectors are custom because the source register and source
988     // source memory operand types are not the same width.  f32 vectors are
989     // custom since the immediate controlling the insert encodes additional
990     // information.
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
992     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
993     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
994     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
995
996     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
997     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
998     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
999     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1000
1001     // FIXME: these should be Legal, but that's only for the case where
1002     // the index is constant.  For now custom expand to deal with that.
1003     if (Subtarget->is64Bit()) {
1004       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1005       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1006     }
1007   }
1008
1009   if (Subtarget->hasSSE2()) {
1010     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1011     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1012     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1013
1014     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1015     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1016
1017     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1018     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1019
1020     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1021     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1022
1023     // In the customized shift lowering, the legal cases in AVX2 will be
1024     // recognized.
1025     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1026     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1027
1028     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1029     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1030
1031     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1032     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1033   }
1034
1035   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1036     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1037     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1038     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1039     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1040     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1042
1043     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1044     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1045     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1046
1047     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1049     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1050     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1051     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1052     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1053     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1054     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1055     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1056     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1057     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1058     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1059
1060     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1061     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1062     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1063     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1064     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1065     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1066     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1067     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1068     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1069     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1070     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1071     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1072
1073     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1074     // even though v8i16 is a legal type.
1075     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1076     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1077     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1078
1079     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1080     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1081     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1082
1083     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1084     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1085
1086     for (MVT VT : MVT::fp_vector_valuetypes())
1087       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1088
1089     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1090     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1091
1092     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1093     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1094
1095     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1096     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1097
1098     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1099     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1100     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1101     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1102
1103     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1104     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1105     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1106
1107     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1108     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1109     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1110     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1111     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1112     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1113     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1114     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1115     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1116     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1117     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1118     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1119
1120     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1121     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1122     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1123     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1124
1125     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1126       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1127       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1128       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1129       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1130       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1131       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1132     }
1133
1134     if (Subtarget->hasInt256()) {
1135       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1136       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1137       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1138       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1139
1140       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1141       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1142       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1143       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1144
1145       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1146       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1147       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1148       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1149
1150       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1151       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1152       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1153       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1154
1155       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1156       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1157       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1158       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1159       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1160       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1161       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1162       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1163       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1164       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1165       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1166       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1167
1168       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1169       // when we have a 256bit-wide blend with immediate.
1170       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1171
1172       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1173       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1174       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1175       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1176       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1177       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1178       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1179
1180       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1181       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1182       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1183       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1184       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1185       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1186     } else {
1187       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1188       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1189       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1190       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1191
1192       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1193       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1194       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1195       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1196
1197       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1198       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1199       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1200       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1201     }
1202
1203     // In the customized shift lowering, the legal cases in AVX2 will be
1204     // recognized.
1205     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1206     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1207
1208     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1209     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1210
1211     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1212     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1213
1214     // Custom lower several nodes for 256-bit types.
1215     for (MVT VT : MVT::vector_valuetypes()) {
1216       if (VT.getScalarSizeInBits() >= 32) {
1217         setOperationAction(ISD::MLOAD,  VT, Legal);
1218         setOperationAction(ISD::MSTORE, VT, Legal);
1219       }
1220       // Extract subvector is special because the value type
1221       // (result) is 128-bit but the source is 256-bit wide.
1222       if (VT.is128BitVector()) {
1223         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1224       }
1225       // Do not attempt to custom lower other non-256-bit vectors
1226       if (!VT.is256BitVector())
1227         continue;
1228
1229       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1230       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1231       setOperationAction(ISD::VSELECT,            VT, Custom);
1232       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1233       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1234       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1235       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1236       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1237     }
1238
1239     if (Subtarget->hasInt256())
1240       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1241
1242
1243     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1244     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1245       MVT VT = (MVT::SimpleValueType)i;
1246
1247       // Do not attempt to promote non-256-bit vectors
1248       if (!VT.is256BitVector())
1249         continue;
1250
1251       setOperationAction(ISD::AND,    VT, Promote);
1252       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1253       setOperationAction(ISD::OR,     VT, Promote);
1254       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1255       setOperationAction(ISD::XOR,    VT, Promote);
1256       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1257       setOperationAction(ISD::LOAD,   VT, Promote);
1258       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1259       setOperationAction(ISD::SELECT, VT, Promote);
1260       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1261     }
1262   }
1263
1264   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1265     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1266     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1267     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1268     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1269
1270     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1271     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1272     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1273
1274     for (MVT VT : MVT::fp_vector_valuetypes())
1275       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1276
1277     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1278     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1279     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1280     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1281     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1282     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1283     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1284     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1285     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1286     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1287     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1288     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1289
1290     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1291     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1292     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1293     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1294     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1295     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1296     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1297     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1298     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1299     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1300     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1301     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1302     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1303
1304     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1305     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1306     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1307     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1308     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1309     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1310
1311     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1312     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1313     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1314     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1315     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1316     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1317     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1318     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1319
1320     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1321     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1322     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1323     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1324     if (Subtarget->is64Bit()) {
1325       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1326       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1327       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1328       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1329     }
1330     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1331     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1332     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1333     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1334     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1336     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1337     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1338     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1339     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1340     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1341     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1342     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1343     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1344     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1345     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1346
1347     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1348     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1349     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1350     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1351     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1352     if (Subtarget->hasVLX()){
1353       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1354       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1355       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1356       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1357       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1358
1359       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1360       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1361       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1362       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1363       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1364     }
1365     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1366     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1367     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1368     if (Subtarget->hasDQI()) {
1369       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1370       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1371
1372       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1373       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1374       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1375       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1376       if (Subtarget->hasVLX()) {
1377         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1378         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1379         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1380         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1381         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1382         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1383         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1384         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1385       }
1386     }
1387     if (Subtarget->hasVLX()) {
1388       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1389       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1390       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1391       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1392       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1393       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1394       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1395       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1396     }
1397     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1398     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1399     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1400     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1401     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1402     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1403     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1404     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1405     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1406     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1407     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1408     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1409     if (Subtarget->hasDQI()) {
1410       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1411       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1412     }
1413     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1414     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1415     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1416     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1417     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1418     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1419     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1420     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1421     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1422     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1423
1424     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1425     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1426     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1427     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1428     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1429
1430     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1431     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1432
1433     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1434
1435     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1436     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1437     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1438     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1439     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1440     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1441     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1442     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1443     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1444     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1445     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1446
1447     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1448     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1449     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1450     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1451     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1452     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1453     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1454     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1455
1456     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1457     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1458
1459     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1460     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1461
1462     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1463
1464     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1465     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1466
1467     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1468     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1469
1470     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1471     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1472
1473     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1474     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1475     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1476     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1477     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1478     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1479
1480     if (Subtarget->hasCDI()) {
1481       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1482       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1483     }
1484     if (Subtarget->hasDQI()) {
1485       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1486       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1487       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1488     }
1489     // Custom lower several nodes.
1490     for (MVT VT : MVT::vector_valuetypes()) {
1491       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1492       if (EltSize == 1) {
1493         setOperationAction(ISD::AND, VT, Legal);
1494         setOperationAction(ISD::OR,  VT, Legal);
1495         setOperationAction(ISD::XOR,  VT, Legal);
1496       }
1497       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1498         setOperationAction(ISD::MGATHER,  VT, Custom);
1499         setOperationAction(ISD::MSCATTER, VT, Custom);
1500       }
1501       // Extract subvector is special because the value type
1502       // (result) is 256/128-bit but the source is 512-bit wide.
1503       if (VT.is128BitVector() || VT.is256BitVector()) {
1504         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1505       }
1506       if (VT.getVectorElementType() == MVT::i1)
1507         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1508
1509       // Do not attempt to custom lower other non-512-bit vectors
1510       if (!VT.is512BitVector())
1511         continue;
1512
1513       if (EltSize >= 32) {
1514         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1515         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1516         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1517         setOperationAction(ISD::VSELECT,             VT, Legal);
1518         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1519         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1520         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1521         setOperationAction(ISD::MLOAD,               VT, Legal);
1522         setOperationAction(ISD::MSTORE,              VT, Legal);
1523       }
1524     }
1525     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1526       MVT VT = (MVT::SimpleValueType)i;
1527
1528       // Do not attempt to promote non-512-bit vectors.
1529       if (!VT.is512BitVector())
1530         continue;
1531
1532       setOperationAction(ISD::SELECT, VT, Promote);
1533       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1534     }
1535   }// has  AVX-512
1536
1537   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1538     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1539     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1540
1541     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1542     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1543
1544     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1545     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1546     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1547     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1548     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1549     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1550     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1551     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1552     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1553     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1554     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1555     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1556     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1557     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1558     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1559     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1560     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1561     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1562     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1563     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1564     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1565     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1566     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1567     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1568     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1569     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1570     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1571     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1572     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1573     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1574
1575     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1576     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1577     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1578     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1579     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1580     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1581     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1582     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1583
1584     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1585     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1586     if (Subtarget->hasVLX())
1587       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1588
1589     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1590       const MVT VT = (MVT::SimpleValueType)i;
1591
1592       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1593
1594       // Do not attempt to promote non-512-bit vectors.
1595       if (!VT.is512BitVector())
1596         continue;
1597
1598       if (EltSize < 32) {
1599         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1600         setOperationAction(ISD::VSELECT,             VT, Legal);
1601       }
1602     }
1603   }
1604
1605   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1606     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1607     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1608
1609     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1610     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1611     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1612     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1613     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1614     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1615     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1616     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1617     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1618     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1619
1620     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1621     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1622     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1623     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1624     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1625     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1626     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1627     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1628
1629     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1630     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1631     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1632     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1633     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1634     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1635     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1636     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1637   }
1638
1639   // We want to custom lower some of our intrinsics.
1640   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1641   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1642   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1643   if (!Subtarget->is64Bit())
1644     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1645
1646   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1647   // handle type legalization for these operations here.
1648   //
1649   // FIXME: We really should do custom legalization for addition and
1650   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1651   // than generic legalization for 64-bit multiplication-with-overflow, though.
1652   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1653     // Add/Sub/Mul with overflow operations are custom lowered.
1654     MVT VT = IntVTs[i];
1655     setOperationAction(ISD::SADDO, VT, Custom);
1656     setOperationAction(ISD::UADDO, VT, Custom);
1657     setOperationAction(ISD::SSUBO, VT, Custom);
1658     setOperationAction(ISD::USUBO, VT, Custom);
1659     setOperationAction(ISD::SMULO, VT, Custom);
1660     setOperationAction(ISD::UMULO, VT, Custom);
1661   }
1662
1663
1664   if (!Subtarget->is64Bit()) {
1665     // These libcalls are not available in 32-bit.
1666     setLibcallName(RTLIB::SHL_I128, nullptr);
1667     setLibcallName(RTLIB::SRL_I128, nullptr);
1668     setLibcallName(RTLIB::SRA_I128, nullptr);
1669   }
1670
1671   // Combine sin / cos into one node or libcall if possible.
1672   if (Subtarget->hasSinCos()) {
1673     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1674     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1675     if (Subtarget->isTargetDarwin()) {
1676       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1677       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1678       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1679       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1680     }
1681   }
1682
1683   if (Subtarget->isTargetWin64()) {
1684     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1685     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1686     setOperationAction(ISD::SREM, MVT::i128, Custom);
1687     setOperationAction(ISD::UREM, MVT::i128, Custom);
1688     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1689     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1690   }
1691
1692   // We have target-specific dag combine patterns for the following nodes:
1693   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1694   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1695   setTargetDAGCombine(ISD::BITCAST);
1696   setTargetDAGCombine(ISD::VSELECT);
1697   setTargetDAGCombine(ISD::SELECT);
1698   setTargetDAGCombine(ISD::SHL);
1699   setTargetDAGCombine(ISD::SRA);
1700   setTargetDAGCombine(ISD::SRL);
1701   setTargetDAGCombine(ISD::OR);
1702   setTargetDAGCombine(ISD::AND);
1703   setTargetDAGCombine(ISD::ADD);
1704   setTargetDAGCombine(ISD::FADD);
1705   setTargetDAGCombine(ISD::FSUB);
1706   setTargetDAGCombine(ISD::FMA);
1707   setTargetDAGCombine(ISD::SUB);
1708   setTargetDAGCombine(ISD::LOAD);
1709   setTargetDAGCombine(ISD::MLOAD);
1710   setTargetDAGCombine(ISD::STORE);
1711   setTargetDAGCombine(ISD::MSTORE);
1712   setTargetDAGCombine(ISD::ZERO_EXTEND);
1713   setTargetDAGCombine(ISD::ANY_EXTEND);
1714   setTargetDAGCombine(ISD::SIGN_EXTEND);
1715   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1716   setTargetDAGCombine(ISD::SINT_TO_FP);
1717   setTargetDAGCombine(ISD::UINT_TO_FP);
1718   setTargetDAGCombine(ISD::SETCC);
1719   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1720   setTargetDAGCombine(ISD::BUILD_VECTOR);
1721   setTargetDAGCombine(ISD::MUL);
1722   setTargetDAGCombine(ISD::XOR);
1723
1724   computeRegisterProperties(Subtarget->getRegisterInfo());
1725
1726   // On Darwin, -Os means optimize for size without hurting performance,
1727   // do not reduce the limit.
1728   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1729   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1730   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1731   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1732   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1733   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1734   setPrefLoopAlignment(4); // 2^4 bytes.
1735
1736   // Predictable cmov don't hurt on atom because it's in-order.
1737   PredictableSelectIsExpensive = !Subtarget->isAtom();
1738   EnableExtLdPromotion = true;
1739   setPrefFunctionAlignment(4); // 2^4 bytes.
1740
1741   verifyIntrinsicTables();
1742 }
1743
1744 // This has so far only been implemented for 64-bit MachO.
1745 bool X86TargetLowering::useLoadStackGuardNode() const {
1746   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1747 }
1748
1749 TargetLoweringBase::LegalizeTypeAction
1750 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1751   if (ExperimentalVectorWideningLegalization &&
1752       VT.getVectorNumElements() != 1 &&
1753       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1754     return TypeWidenVector;
1755
1756   return TargetLoweringBase::getPreferredVectorAction(VT);
1757 }
1758
1759 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1760                                           EVT VT) const {
1761   if (!VT.isVector())
1762     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1763
1764   const unsigned NumElts = VT.getVectorNumElements();
1765   const EVT EltVT = VT.getVectorElementType();
1766   if (VT.is512BitVector()) {
1767     if (Subtarget->hasAVX512())
1768       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1769           EltVT == MVT::f32 || EltVT == MVT::f64)
1770         switch(NumElts) {
1771         case  8: return MVT::v8i1;
1772         case 16: return MVT::v16i1;
1773       }
1774     if (Subtarget->hasBWI())
1775       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1776         switch(NumElts) {
1777         case 32: return MVT::v32i1;
1778         case 64: return MVT::v64i1;
1779       }
1780   }
1781
1782   if (VT.is256BitVector() || VT.is128BitVector()) {
1783     if (Subtarget->hasVLX())
1784       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1785           EltVT == MVT::f32 || EltVT == MVT::f64)
1786         switch(NumElts) {
1787         case 2: return MVT::v2i1;
1788         case 4: return MVT::v4i1;
1789         case 8: return MVT::v8i1;
1790       }
1791     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1792       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1793         switch(NumElts) {
1794         case  8: return MVT::v8i1;
1795         case 16: return MVT::v16i1;
1796         case 32: return MVT::v32i1;
1797       }
1798   }
1799
1800   return VT.changeVectorElementTypeToInteger();
1801 }
1802
1803 /// Helper for getByValTypeAlignment to determine
1804 /// the desired ByVal argument alignment.
1805 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1806   if (MaxAlign == 16)
1807     return;
1808   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1809     if (VTy->getBitWidth() == 128)
1810       MaxAlign = 16;
1811   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1812     unsigned EltAlign = 0;
1813     getMaxByValAlign(ATy->getElementType(), EltAlign);
1814     if (EltAlign > MaxAlign)
1815       MaxAlign = EltAlign;
1816   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1817     for (auto *EltTy : STy->elements()) {
1818       unsigned EltAlign = 0;
1819       getMaxByValAlign(EltTy, EltAlign);
1820       if (EltAlign > MaxAlign)
1821         MaxAlign = EltAlign;
1822       if (MaxAlign == 16)
1823         break;
1824     }
1825   }
1826 }
1827
1828 /// Return the desired alignment for ByVal aggregate
1829 /// function arguments in the caller parameter area. For X86, aggregates
1830 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1831 /// are at 4-byte boundaries.
1832 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1833                                                   const DataLayout &DL) const {
1834   if (Subtarget->is64Bit()) {
1835     // Max of 8 and alignment of type.
1836     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1837     if (TyAlign > 8)
1838       return TyAlign;
1839     return 8;
1840   }
1841
1842   unsigned Align = 4;
1843   if (Subtarget->hasSSE1())
1844     getMaxByValAlign(Ty, Align);
1845   return Align;
1846 }
1847
1848 /// Returns the target specific optimal type for load
1849 /// and store operations as a result of memset, memcpy, and memmove
1850 /// lowering. If DstAlign is zero that means it's safe to destination
1851 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1852 /// means there isn't a need to check it against alignment requirement,
1853 /// probably because the source does not need to be loaded. If 'IsMemset' is
1854 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1855 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1856 /// source is constant so it does not need to be loaded.
1857 /// It returns EVT::Other if the type should be determined using generic
1858 /// target-independent logic.
1859 EVT
1860 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1861                                        unsigned DstAlign, unsigned SrcAlign,
1862                                        bool IsMemset, bool ZeroMemset,
1863                                        bool MemcpyStrSrc,
1864                                        MachineFunction &MF) const {
1865   const Function *F = MF.getFunction();
1866   if ((!IsMemset || ZeroMemset) &&
1867       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1868     if (Size >= 16 &&
1869         (Subtarget->isUnalignedMemAccessFast() ||
1870          ((DstAlign == 0 || DstAlign >= 16) &&
1871           (SrcAlign == 0 || SrcAlign >= 16)))) {
1872       if (Size >= 32) {
1873         if (Subtarget->hasInt256())
1874           return MVT::v8i32;
1875         if (Subtarget->hasFp256())
1876           return MVT::v8f32;
1877       }
1878       if (Subtarget->hasSSE2())
1879         return MVT::v4i32;
1880       if (Subtarget->hasSSE1())
1881         return MVT::v4f32;
1882     } else if (!MemcpyStrSrc && Size >= 8 &&
1883                !Subtarget->is64Bit() &&
1884                Subtarget->hasSSE2()) {
1885       // Do not use f64 to lower memcpy if source is string constant. It's
1886       // better to use i32 to avoid the loads.
1887       return MVT::f64;
1888     }
1889   }
1890   if (Subtarget->is64Bit() && Size >= 8)
1891     return MVT::i64;
1892   return MVT::i32;
1893 }
1894
1895 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1896   if (VT == MVT::f32)
1897     return X86ScalarSSEf32;
1898   else if (VT == MVT::f64)
1899     return X86ScalarSSEf64;
1900   return true;
1901 }
1902
1903 bool
1904 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1905                                                   unsigned,
1906                                                   unsigned,
1907                                                   bool *Fast) const {
1908   if (Fast)
1909     *Fast = Subtarget->isUnalignedMemAccessFast();
1910   return true;
1911 }
1912
1913 /// Return the entry encoding for a jump table in the
1914 /// current function.  The returned value is a member of the
1915 /// MachineJumpTableInfo::JTEntryKind enum.
1916 unsigned X86TargetLowering::getJumpTableEncoding() const {
1917   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1918   // symbol.
1919   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1920       Subtarget->isPICStyleGOT())
1921     return MachineJumpTableInfo::EK_Custom32;
1922
1923   // Otherwise, use the normal jump table encoding heuristics.
1924   return TargetLowering::getJumpTableEncoding();
1925 }
1926
1927 bool X86TargetLowering::useSoftFloat() const {
1928   return Subtarget->useSoftFloat();
1929 }
1930
1931 const MCExpr *
1932 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1933                                              const MachineBasicBlock *MBB,
1934                                              unsigned uid,MCContext &Ctx) const{
1935   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1936          Subtarget->isPICStyleGOT());
1937   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1938   // entries.
1939   return MCSymbolRefExpr::create(MBB->getSymbol(),
1940                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1941 }
1942
1943 /// Returns relocation base for the given PIC jumptable.
1944 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1945                                                     SelectionDAG &DAG) const {
1946   if (!Subtarget->is64Bit())
1947     // This doesn't have SDLoc associated with it, but is not really the
1948     // same as a Register.
1949     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1950                        getPointerTy(DAG.getDataLayout()));
1951   return Table;
1952 }
1953
1954 /// This returns the relocation base for the given PIC jumptable,
1955 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1956 const MCExpr *X86TargetLowering::
1957 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1958                              MCContext &Ctx) const {
1959   // X86-64 uses RIP relative addressing based on the jump table label.
1960   if (Subtarget->isPICStyleRIPRel())
1961     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1962
1963   // Otherwise, the reference is relative to the PIC base.
1964   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1965 }
1966
1967 std::pair<const TargetRegisterClass *, uint8_t>
1968 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1969                                            MVT VT) const {
1970   const TargetRegisterClass *RRC = nullptr;
1971   uint8_t Cost = 1;
1972   switch (VT.SimpleTy) {
1973   default:
1974     return TargetLowering::findRepresentativeClass(TRI, VT);
1975   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1976     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1977     break;
1978   case MVT::x86mmx:
1979     RRC = &X86::VR64RegClass;
1980     break;
1981   case MVT::f32: case MVT::f64:
1982   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1983   case MVT::v4f32: case MVT::v2f64:
1984   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1985   case MVT::v4f64:
1986     RRC = &X86::VR128RegClass;
1987     break;
1988   }
1989   return std::make_pair(RRC, Cost);
1990 }
1991
1992 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1993                                                unsigned &Offset) const {
1994   if (!Subtarget->isTargetLinux())
1995     return false;
1996
1997   if (Subtarget->is64Bit()) {
1998     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1999     Offset = 0x28;
2000     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2001       AddressSpace = 256;
2002     else
2003       AddressSpace = 257;
2004   } else {
2005     // %gs:0x14 on i386
2006     Offset = 0x14;
2007     AddressSpace = 256;
2008   }
2009   return true;
2010 }
2011
2012 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2013                                             unsigned DestAS) const {
2014   assert(SrcAS != DestAS && "Expected different address spaces!");
2015
2016   return SrcAS < 256 && DestAS < 256;
2017 }
2018
2019 //===----------------------------------------------------------------------===//
2020 //               Return Value Calling Convention Implementation
2021 //===----------------------------------------------------------------------===//
2022
2023 #include "X86GenCallingConv.inc"
2024
2025 bool
2026 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2027                                   MachineFunction &MF, bool isVarArg,
2028                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2029                         LLVMContext &Context) const {
2030   SmallVector<CCValAssign, 16> RVLocs;
2031   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2032   return CCInfo.CheckReturn(Outs, RetCC_X86);
2033 }
2034
2035 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2036   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2037   return ScratchRegs;
2038 }
2039
2040 SDValue
2041 X86TargetLowering::LowerReturn(SDValue Chain,
2042                                CallingConv::ID CallConv, bool isVarArg,
2043                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2044                                const SmallVectorImpl<SDValue> &OutVals,
2045                                SDLoc dl, SelectionDAG &DAG) const {
2046   MachineFunction &MF = DAG.getMachineFunction();
2047   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2048
2049   SmallVector<CCValAssign, 16> RVLocs;
2050   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2051   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2052
2053   SDValue Flag;
2054   SmallVector<SDValue, 6> RetOps;
2055   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2056   // Operand #1 = Bytes To Pop
2057   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2058                    MVT::i16));
2059
2060   // Copy the result values into the output registers.
2061   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2062     CCValAssign &VA = RVLocs[i];
2063     assert(VA.isRegLoc() && "Can only return in registers!");
2064     SDValue ValToCopy = OutVals[i];
2065     EVT ValVT = ValToCopy.getValueType();
2066
2067     // Promote values to the appropriate types.
2068     if (VA.getLocInfo() == CCValAssign::SExt)
2069       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2070     else if (VA.getLocInfo() == CCValAssign::ZExt)
2071       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2072     else if (VA.getLocInfo() == CCValAssign::AExt) {
2073       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2074         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2075       else
2076         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2077     }
2078     else if (VA.getLocInfo() == CCValAssign::BCvt)
2079       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2080
2081     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2082            "Unexpected FP-extend for return value.");
2083
2084     // If this is x86-64, and we disabled SSE, we can't return FP values,
2085     // or SSE or MMX vectors.
2086     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2087          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2088           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2089       report_fatal_error("SSE register return with SSE disabled");
2090     }
2091     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2092     // llvm-gcc has never done it right and no one has noticed, so this
2093     // should be OK for now.
2094     if (ValVT == MVT::f64 &&
2095         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2096       report_fatal_error("SSE2 register return with SSE2 disabled");
2097
2098     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2099     // the RET instruction and handled by the FP Stackifier.
2100     if (VA.getLocReg() == X86::FP0 ||
2101         VA.getLocReg() == X86::FP1) {
2102       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2103       // change the value to the FP stack register class.
2104       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2105         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2106       RetOps.push_back(ValToCopy);
2107       // Don't emit a copytoreg.
2108       continue;
2109     }
2110
2111     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2112     // which is returned in RAX / RDX.
2113     if (Subtarget->is64Bit()) {
2114       if (ValVT == MVT::x86mmx) {
2115         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2116           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2117           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2118                                   ValToCopy);
2119           // If we don't have SSE2 available, convert to v4f32 so the generated
2120           // register is legal.
2121           if (!Subtarget->hasSSE2())
2122             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2123         }
2124       }
2125     }
2126
2127     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2128     Flag = Chain.getValue(1);
2129     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2130   }
2131
2132   // All x86 ABIs require that for returning structs by value we copy
2133   // the sret argument into %rax/%eax (depending on ABI) for the return.
2134   // We saved the argument into a virtual register in the entry block,
2135   // so now we copy the value out and into %rax/%eax.
2136   //
2137   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2138   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2139   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2140   // either case FuncInfo->setSRetReturnReg() will have been called.
2141   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2142     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2143                                      getPointerTy(MF.getDataLayout()));
2144
2145     unsigned RetValReg
2146         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2147           X86::RAX : X86::EAX;
2148     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2149     Flag = Chain.getValue(1);
2150
2151     // RAX/EAX now acts like a return value.
2152     RetOps.push_back(
2153         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2154   }
2155
2156   RetOps[0] = Chain;  // Update chain.
2157
2158   // Add the flag if we have it.
2159   if (Flag.getNode())
2160     RetOps.push_back(Flag);
2161
2162   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2163 }
2164
2165 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2166   if (N->getNumValues() != 1)
2167     return false;
2168   if (!N->hasNUsesOfValue(1, 0))
2169     return false;
2170
2171   SDValue TCChain = Chain;
2172   SDNode *Copy = *N->use_begin();
2173   if (Copy->getOpcode() == ISD::CopyToReg) {
2174     // If the copy has a glue operand, we conservatively assume it isn't safe to
2175     // perform a tail call.
2176     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2177       return false;
2178     TCChain = Copy->getOperand(0);
2179   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2180     return false;
2181
2182   bool HasRet = false;
2183   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2184        UI != UE; ++UI) {
2185     if (UI->getOpcode() != X86ISD::RET_FLAG)
2186       return false;
2187     // If we are returning more than one value, we can definitely
2188     // not make a tail call see PR19530
2189     if (UI->getNumOperands() > 4)
2190       return false;
2191     if (UI->getNumOperands() == 4 &&
2192         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2193       return false;
2194     HasRet = true;
2195   }
2196
2197   if (!HasRet)
2198     return false;
2199
2200   Chain = TCChain;
2201   return true;
2202 }
2203
2204 EVT
2205 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2206                                             ISD::NodeType ExtendKind) const {
2207   MVT ReturnMVT;
2208   // TODO: Is this also valid on 32-bit?
2209   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2210     ReturnMVT = MVT::i8;
2211   else
2212     ReturnMVT = MVT::i32;
2213
2214   EVT MinVT = getRegisterType(Context, ReturnMVT);
2215   return VT.bitsLT(MinVT) ? MinVT : VT;
2216 }
2217
2218 /// Lower the result values of a call into the
2219 /// appropriate copies out of appropriate physical registers.
2220 ///
2221 SDValue
2222 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2223                                    CallingConv::ID CallConv, bool isVarArg,
2224                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2225                                    SDLoc dl, SelectionDAG &DAG,
2226                                    SmallVectorImpl<SDValue> &InVals) const {
2227
2228   // Assign locations to each value returned by this call.
2229   SmallVector<CCValAssign, 16> RVLocs;
2230   bool Is64Bit = Subtarget->is64Bit();
2231   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2232                  *DAG.getContext());
2233   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2234
2235   // Copy all of the result registers out of their specified physreg.
2236   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2237     CCValAssign &VA = RVLocs[i];
2238     EVT CopyVT = VA.getLocVT();
2239
2240     // If this is x86-64, and we disabled SSE, we can't return FP values
2241     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2242         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2243       report_fatal_error("SSE register return with SSE disabled");
2244     }
2245
2246     // If we prefer to use the value in xmm registers, copy it out as f80 and
2247     // use a truncate to move it from fp stack reg to xmm reg.
2248     bool RoundAfterCopy = false;
2249     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2250         isScalarFPTypeInSSEReg(VA.getValVT())) {
2251       CopyVT = MVT::f80;
2252       RoundAfterCopy = (CopyVT != VA.getLocVT());
2253     }
2254
2255     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2256                                CopyVT, InFlag).getValue(1);
2257     SDValue Val = Chain.getValue(0);
2258
2259     if (RoundAfterCopy)
2260       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2261                         // This truncation won't change the value.
2262                         DAG.getIntPtrConstant(1, dl));
2263
2264     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2265       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2266
2267     InFlag = Chain.getValue(2);
2268     InVals.push_back(Val);
2269   }
2270
2271   return Chain;
2272 }
2273
2274 //===----------------------------------------------------------------------===//
2275 //                C & StdCall & Fast Calling Convention implementation
2276 //===----------------------------------------------------------------------===//
2277 //  StdCall calling convention seems to be standard for many Windows' API
2278 //  routines and around. It differs from C calling convention just a little:
2279 //  callee should clean up the stack, not caller. Symbols should be also
2280 //  decorated in some fancy way :) It doesn't support any vector arguments.
2281 //  For info on fast calling convention see Fast Calling Convention (tail call)
2282 //  implementation LowerX86_32FastCCCallTo.
2283
2284 /// CallIsStructReturn - Determines whether a call uses struct return
2285 /// semantics.
2286 enum StructReturnType {
2287   NotStructReturn,
2288   RegStructReturn,
2289   StackStructReturn
2290 };
2291 static StructReturnType
2292 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2293   if (Outs.empty())
2294     return NotStructReturn;
2295
2296   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2297   if (!Flags.isSRet())
2298     return NotStructReturn;
2299   if (Flags.isInReg())
2300     return RegStructReturn;
2301   return StackStructReturn;
2302 }
2303
2304 /// Determines whether a function uses struct return semantics.
2305 static StructReturnType
2306 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2307   if (Ins.empty())
2308     return NotStructReturn;
2309
2310   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2311   if (!Flags.isSRet())
2312     return NotStructReturn;
2313   if (Flags.isInReg())
2314     return RegStructReturn;
2315   return StackStructReturn;
2316 }
2317
2318 /// Make a copy of an aggregate at address specified by "Src" to address
2319 /// "Dst" with size and alignment information specified by the specific
2320 /// parameter attribute. The copy will be passed as a byval function parameter.
2321 static SDValue
2322 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2323                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2324                           SDLoc dl) {
2325   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2326
2327   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2328                        /*isVolatile*/false, /*AlwaysInline=*/true,
2329                        /*isTailCall*/false,
2330                        MachinePointerInfo(), MachinePointerInfo());
2331 }
2332
2333 /// Return true if the calling convention is one that
2334 /// supports tail call optimization.
2335 static bool IsTailCallConvention(CallingConv::ID CC) {
2336   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2337           CC == CallingConv::HiPE);
2338 }
2339
2340 /// \brief Return true if the calling convention is a C calling convention.
2341 static bool IsCCallConvention(CallingConv::ID CC) {
2342   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2343           CC == CallingConv::X86_64_SysV);
2344 }
2345
2346 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2347   auto Attr =
2348       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2349   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2350     return false;
2351
2352   CallSite CS(CI);
2353   CallingConv::ID CalleeCC = CS.getCallingConv();
2354   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2355     return false;
2356
2357   return true;
2358 }
2359
2360 /// Return true if the function is being made into
2361 /// a tailcall target by changing its ABI.
2362 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2363                                    bool GuaranteedTailCallOpt) {
2364   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2365 }
2366
2367 SDValue
2368 X86TargetLowering::LowerMemArgument(SDValue Chain,
2369                                     CallingConv::ID CallConv,
2370                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2371                                     SDLoc dl, SelectionDAG &DAG,
2372                                     const CCValAssign &VA,
2373                                     MachineFrameInfo *MFI,
2374                                     unsigned i) const {
2375   // Create the nodes corresponding to a load from this parameter slot.
2376   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2377   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2378       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2379   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2380   EVT ValVT;
2381
2382   // If value is passed by pointer we have address passed instead of the value
2383   // itself.
2384   bool ExtendedInMem = VA.isExtInLoc() &&
2385     VA.getValVT().getScalarType() == MVT::i1;
2386
2387   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2388     ValVT = VA.getLocVT();
2389   else
2390     ValVT = VA.getValVT();
2391
2392   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2393   // changed with more analysis.
2394   // In case of tail call optimization mark all arguments mutable. Since they
2395   // could be overwritten by lowering of arguments in case of a tail call.
2396   if (Flags.isByVal()) {
2397     unsigned Bytes = Flags.getByValSize();
2398     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2399     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2400     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2401   } else {
2402     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2403                                     VA.getLocMemOffset(), isImmutable);
2404     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2405     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2406                                MachinePointerInfo::getFixedStack(FI),
2407                                false, false, false, 0);
2408     return ExtendedInMem ?
2409       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2410   }
2411 }
2412
2413 // FIXME: Get this from tablegen.
2414 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2415                                                 const X86Subtarget *Subtarget) {
2416   assert(Subtarget->is64Bit());
2417
2418   if (Subtarget->isCallingConvWin64(CallConv)) {
2419     static const MCPhysReg GPR64ArgRegsWin64[] = {
2420       X86::RCX, X86::RDX, X86::R8,  X86::R9
2421     };
2422     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2423   }
2424
2425   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2426     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2427   };
2428   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2429 }
2430
2431 // FIXME: Get this from tablegen.
2432 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2433                                                 CallingConv::ID CallConv,
2434                                                 const X86Subtarget *Subtarget) {
2435   assert(Subtarget->is64Bit());
2436   if (Subtarget->isCallingConvWin64(CallConv)) {
2437     // The XMM registers which might contain var arg parameters are shadowed
2438     // in their paired GPR.  So we only need to save the GPR to their home
2439     // slots.
2440     // TODO: __vectorcall will change this.
2441     return None;
2442   }
2443
2444   const Function *Fn = MF.getFunction();
2445   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2446   bool isSoftFloat = Subtarget->useSoftFloat();
2447   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2448          "SSE register cannot be used when SSE is disabled!");
2449   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2450     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2451     // registers.
2452     return None;
2453
2454   static const MCPhysReg XMMArgRegs64Bit[] = {
2455     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2456     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2457   };
2458   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2459 }
2460
2461 SDValue
2462 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2463                                         CallingConv::ID CallConv,
2464                                         bool isVarArg,
2465                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2466                                         SDLoc dl,
2467                                         SelectionDAG &DAG,
2468                                         SmallVectorImpl<SDValue> &InVals)
2469                                           const {
2470   MachineFunction &MF = DAG.getMachineFunction();
2471   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2472   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2473
2474   const Function* Fn = MF.getFunction();
2475   if (Fn->hasExternalLinkage() &&
2476       Subtarget->isTargetCygMing() &&
2477       Fn->getName() == "main")
2478     FuncInfo->setForceFramePointer(true);
2479
2480   MachineFrameInfo *MFI = MF.getFrameInfo();
2481   bool Is64Bit = Subtarget->is64Bit();
2482   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2483
2484   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2485          "Var args not supported with calling convention fastcc, ghc or hipe");
2486
2487   // Assign locations to all of the incoming arguments.
2488   SmallVector<CCValAssign, 16> ArgLocs;
2489   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2490
2491   // Allocate shadow area for Win64
2492   if (IsWin64)
2493     CCInfo.AllocateStack(32, 8);
2494
2495   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2496
2497   unsigned LastVal = ~0U;
2498   SDValue ArgValue;
2499   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2500     CCValAssign &VA = ArgLocs[i];
2501     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2502     // places.
2503     assert(VA.getValNo() != LastVal &&
2504            "Don't support value assigned to multiple locs yet");
2505     (void)LastVal;
2506     LastVal = VA.getValNo();
2507
2508     if (VA.isRegLoc()) {
2509       EVT RegVT = VA.getLocVT();
2510       const TargetRegisterClass *RC;
2511       if (RegVT == MVT::i32)
2512         RC = &X86::GR32RegClass;
2513       else if (Is64Bit && RegVT == MVT::i64)
2514         RC = &X86::GR64RegClass;
2515       else if (RegVT == MVT::f32)
2516         RC = &X86::FR32RegClass;
2517       else if (RegVT == MVT::f64)
2518         RC = &X86::FR64RegClass;
2519       else if (RegVT.is512BitVector())
2520         RC = &X86::VR512RegClass;
2521       else if (RegVT.is256BitVector())
2522         RC = &X86::VR256RegClass;
2523       else if (RegVT.is128BitVector())
2524         RC = &X86::VR128RegClass;
2525       else if (RegVT == MVT::x86mmx)
2526         RC = &X86::VR64RegClass;
2527       else if (RegVT == MVT::i1)
2528         RC = &X86::VK1RegClass;
2529       else if (RegVT == MVT::v8i1)
2530         RC = &X86::VK8RegClass;
2531       else if (RegVT == MVT::v16i1)
2532         RC = &X86::VK16RegClass;
2533       else if (RegVT == MVT::v32i1)
2534         RC = &X86::VK32RegClass;
2535       else if (RegVT == MVT::v64i1)
2536         RC = &X86::VK64RegClass;
2537       else
2538         llvm_unreachable("Unknown argument type!");
2539
2540       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2541       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2542
2543       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2544       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2545       // right size.
2546       if (VA.getLocInfo() == CCValAssign::SExt)
2547         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2548                                DAG.getValueType(VA.getValVT()));
2549       else if (VA.getLocInfo() == CCValAssign::ZExt)
2550         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2551                                DAG.getValueType(VA.getValVT()));
2552       else if (VA.getLocInfo() == CCValAssign::BCvt)
2553         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2554
2555       if (VA.isExtInLoc()) {
2556         // Handle MMX values passed in XMM regs.
2557         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2558           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2559         else
2560           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2561       }
2562     } else {
2563       assert(VA.isMemLoc());
2564       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2565     }
2566
2567     // If value is passed via pointer - do a load.
2568     if (VA.getLocInfo() == CCValAssign::Indirect)
2569       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2570                              MachinePointerInfo(), false, false, false, 0);
2571
2572     InVals.push_back(ArgValue);
2573   }
2574
2575   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2576     // All x86 ABIs require that for returning structs by value we copy the
2577     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2578     // the argument into a virtual register so that we can access it from the
2579     // return points.
2580     if (Ins[i].Flags.isSRet()) {
2581       unsigned Reg = FuncInfo->getSRetReturnReg();
2582       if (!Reg) {
2583         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2584         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2585         FuncInfo->setSRetReturnReg(Reg);
2586       }
2587       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2588       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2589       break;
2590     }
2591   }
2592
2593   unsigned StackSize = CCInfo.getNextStackOffset();
2594   // Align stack specially for tail calls.
2595   if (FuncIsMadeTailCallSafe(CallConv,
2596                              MF.getTarget().Options.GuaranteedTailCallOpt))
2597     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2598
2599   // If the function takes variable number of arguments, make a frame index for
2600   // the start of the first vararg value... for expansion of llvm.va_start. We
2601   // can skip this if there are no va_start calls.
2602   if (MFI->hasVAStart() &&
2603       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2604                    CallConv != CallingConv::X86_ThisCall))) {
2605     FuncInfo->setVarArgsFrameIndex(
2606         MFI->CreateFixedObject(1, StackSize, true));
2607   }
2608
2609   MachineModuleInfo &MMI = MF.getMMI();
2610   const Function *WinEHParent = nullptr;
2611   if (MMI.hasWinEHFuncInfo(Fn))
2612     WinEHParent = MMI.getWinEHParent(Fn);
2613   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2614   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2615
2616   // Figure out if XMM registers are in use.
2617   assert(!(Subtarget->useSoftFloat() &&
2618            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2619          "SSE register cannot be used when SSE is disabled!");
2620
2621   // 64-bit calling conventions support varargs and register parameters, so we
2622   // have to do extra work to spill them in the prologue.
2623   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2624     // Find the first unallocated argument registers.
2625     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2626     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2627     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2628     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2629     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2630            "SSE register cannot be used when SSE is disabled!");
2631
2632     // Gather all the live in physical registers.
2633     SmallVector<SDValue, 6> LiveGPRs;
2634     SmallVector<SDValue, 8> LiveXMMRegs;
2635     SDValue ALVal;
2636     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2637       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2638       LiveGPRs.push_back(
2639           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2640     }
2641     if (!ArgXMMs.empty()) {
2642       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2643       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2644       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2645         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2646         LiveXMMRegs.push_back(
2647             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2648       }
2649     }
2650
2651     if (IsWin64) {
2652       // Get to the caller-allocated home save location.  Add 8 to account
2653       // for the return address.
2654       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2655       FuncInfo->setRegSaveFrameIndex(
2656           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2657       // Fixup to set vararg frame on shadow area (4 x i64).
2658       if (NumIntRegs < 4)
2659         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2660     } else {
2661       // For X86-64, if there are vararg parameters that are passed via
2662       // registers, then we must store them to their spots on the stack so
2663       // they may be loaded by deferencing the result of va_next.
2664       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2665       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2666       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2667           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2668     }
2669
2670     // Store the integer parameter registers.
2671     SmallVector<SDValue, 8> MemOps;
2672     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2673                                       getPointerTy(DAG.getDataLayout()));
2674     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2675     for (SDValue Val : LiveGPRs) {
2676       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2677                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2678       SDValue Store =
2679         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2680                      MachinePointerInfo::getFixedStack(
2681                        FuncInfo->getRegSaveFrameIndex(), Offset),
2682                      false, false, 0);
2683       MemOps.push_back(Store);
2684       Offset += 8;
2685     }
2686
2687     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2688       // Now store the XMM (fp + vector) parameter registers.
2689       SmallVector<SDValue, 12> SaveXMMOps;
2690       SaveXMMOps.push_back(Chain);
2691       SaveXMMOps.push_back(ALVal);
2692       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2693                              FuncInfo->getRegSaveFrameIndex(), dl));
2694       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2695                              FuncInfo->getVarArgsFPOffset(), dl));
2696       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2697                         LiveXMMRegs.end());
2698       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2699                                    MVT::Other, SaveXMMOps));
2700     }
2701
2702     if (!MemOps.empty())
2703       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2704   } else if (IsWin64 && IsWinEHOutlined) {
2705     // Get to the caller-allocated home save location.  Add 8 to account
2706     // for the return address.
2707     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2708     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2709         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2710
2711     MMI.getWinEHFuncInfo(Fn)
2712         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2713         FuncInfo->getRegSaveFrameIndex();
2714
2715     // Store the second integer parameter (rdx) into rsp+16 relative to the
2716     // stack pointer at the entry of the function.
2717     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2718                                       getPointerTy(DAG.getDataLayout()));
2719     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2720     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2721     Chain = DAG.getStore(
2722         Val.getValue(1), dl, Val, RSFIN,
2723         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2724         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2725   }
2726
2727   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2728     // Find the largest legal vector type.
2729     MVT VecVT = MVT::Other;
2730     // FIXME: Only some x86_32 calling conventions support AVX512.
2731     if (Subtarget->hasAVX512() &&
2732         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2733                      CallConv == CallingConv::Intel_OCL_BI)))
2734       VecVT = MVT::v16f32;
2735     else if (Subtarget->hasAVX())
2736       VecVT = MVT::v8f32;
2737     else if (Subtarget->hasSSE2())
2738       VecVT = MVT::v4f32;
2739
2740     // We forward some GPRs and some vector types.
2741     SmallVector<MVT, 2> RegParmTypes;
2742     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2743     RegParmTypes.push_back(IntVT);
2744     if (VecVT != MVT::Other)
2745       RegParmTypes.push_back(VecVT);
2746
2747     // Compute the set of forwarded registers. The rest are scratch.
2748     SmallVectorImpl<ForwardedRegister> &Forwards =
2749         FuncInfo->getForwardedMustTailRegParms();
2750     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2751
2752     // Conservatively forward AL on x86_64, since it might be used for varargs.
2753     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2754       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2755       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2756     }
2757
2758     // Copy all forwards from physical to virtual registers.
2759     for (ForwardedRegister &F : Forwards) {
2760       // FIXME: Can we use a less constrained schedule?
2761       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2762       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2763       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2764     }
2765   }
2766
2767   // Some CCs need callee pop.
2768   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2769                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2770     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2771   } else {
2772     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2773     // If this is an sret function, the return should pop the hidden pointer.
2774     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2775         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2776         argsAreStructReturn(Ins) == StackStructReturn)
2777       FuncInfo->setBytesToPopOnReturn(4);
2778   }
2779
2780   if (!Is64Bit) {
2781     // RegSaveFrameIndex is X86-64 only.
2782     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2783     if (CallConv == CallingConv::X86_FastCall ||
2784         CallConv == CallingConv::X86_ThisCall)
2785       // fastcc functions can't have varargs.
2786       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2787   }
2788
2789   FuncInfo->setArgumentStackSize(StackSize);
2790
2791   if (IsWinEHParent) {
2792     if (Is64Bit) {
2793       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2794       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2795       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2796       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2797       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2798                            MachinePointerInfo::getFixedStack(UnwindHelpFI),
2799                            /*isVolatile=*/true,
2800                            /*isNonTemporal=*/false, /*Alignment=*/0);
2801     } else {
2802       // Functions using Win32 EH are considered to have opaque SP adjustments
2803       // to force local variables to be addressed from the frame or base
2804       // pointers.
2805       MFI->setHasOpaqueSPAdjustment(true);
2806     }
2807   }
2808
2809   return Chain;
2810 }
2811
2812 SDValue
2813 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2814                                     SDValue StackPtr, SDValue Arg,
2815                                     SDLoc dl, SelectionDAG &DAG,
2816                                     const CCValAssign &VA,
2817                                     ISD::ArgFlagsTy Flags) const {
2818   unsigned LocMemOffset = VA.getLocMemOffset();
2819   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2820   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2821                        StackPtr, PtrOff);
2822   if (Flags.isByVal())
2823     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2824
2825   return DAG.getStore(Chain, dl, Arg, PtrOff,
2826                       MachinePointerInfo::getStack(LocMemOffset),
2827                       false, false, 0);
2828 }
2829
2830 /// Emit a load of return address if tail call
2831 /// optimization is performed and it is required.
2832 SDValue
2833 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2834                                            SDValue &OutRetAddr, SDValue Chain,
2835                                            bool IsTailCall, bool Is64Bit,
2836                                            int FPDiff, SDLoc dl) const {
2837   // Adjust the Return address stack slot.
2838   EVT VT = getPointerTy(DAG.getDataLayout());
2839   OutRetAddr = getReturnAddressFrameIndex(DAG);
2840
2841   // Load the "old" Return address.
2842   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2843                            false, false, false, 0);
2844   return SDValue(OutRetAddr.getNode(), 1);
2845 }
2846
2847 /// Emit a store of the return address if tail call
2848 /// optimization is performed and it is required (FPDiff!=0).
2849 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2850                                         SDValue Chain, SDValue RetAddrFrIdx,
2851                                         EVT PtrVT, unsigned SlotSize,
2852                                         int FPDiff, SDLoc dl) {
2853   // Store the return address to the appropriate stack slot.
2854   if (!FPDiff) return Chain;
2855   // Calculate the new stack slot for the return address.
2856   int NewReturnAddrFI =
2857     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2858                                          false);
2859   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2860   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2861                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2862                        false, false, 0);
2863   return Chain;
2864 }
2865
2866 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2867 /// operation of specified width.
2868 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2869                        SDValue V2) {
2870   unsigned NumElems = VT.getVectorNumElements();
2871   SmallVector<int, 8> Mask;
2872   Mask.push_back(NumElems);
2873   for (unsigned i = 1; i != NumElems; ++i)
2874     Mask.push_back(i);
2875   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2876 }
2877
2878 SDValue
2879 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2880                              SmallVectorImpl<SDValue> &InVals) const {
2881   SelectionDAG &DAG                     = CLI.DAG;
2882   SDLoc &dl                             = CLI.DL;
2883   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2884   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2885   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2886   SDValue Chain                         = CLI.Chain;
2887   SDValue Callee                        = CLI.Callee;
2888   CallingConv::ID CallConv              = CLI.CallConv;
2889   bool &isTailCall                      = CLI.IsTailCall;
2890   bool isVarArg                         = CLI.IsVarArg;
2891
2892   MachineFunction &MF = DAG.getMachineFunction();
2893   bool Is64Bit        = Subtarget->is64Bit();
2894   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2895   StructReturnType SR = callIsStructReturn(Outs);
2896   bool IsSibcall      = false;
2897   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2898   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2899
2900   if (Attr.getValueAsString() == "true")
2901     isTailCall = false;
2902
2903   if (Subtarget->isPICStyleGOT() &&
2904       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2905     // If we are using a GOT, disable tail calls to external symbols with
2906     // default visibility. Tail calling such a symbol requires using a GOT
2907     // relocation, which forces early binding of the symbol. This breaks code
2908     // that require lazy function symbol resolution. Using musttail or
2909     // GuaranteedTailCallOpt will override this.
2910     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2911     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2912                G->getGlobal()->hasDefaultVisibility()))
2913       isTailCall = false;
2914   }
2915
2916   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2917   if (IsMustTail) {
2918     // Force this to be a tail call.  The verifier rules are enough to ensure
2919     // that we can lower this successfully without moving the return address
2920     // around.
2921     isTailCall = true;
2922   } else if (isTailCall) {
2923     // Check if it's really possible to do a tail call.
2924     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2925                     isVarArg, SR != NotStructReturn,
2926                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2927                     Outs, OutVals, Ins, DAG);
2928
2929     // Sibcalls are automatically detected tailcalls which do not require
2930     // ABI changes.
2931     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2932       IsSibcall = true;
2933
2934     if (isTailCall)
2935       ++NumTailCalls;
2936   }
2937
2938   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2939          "Var args not supported with calling convention fastcc, ghc or hipe");
2940
2941   // Analyze operands of the call, assigning locations to each operand.
2942   SmallVector<CCValAssign, 16> ArgLocs;
2943   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2944
2945   // Allocate shadow area for Win64
2946   if (IsWin64)
2947     CCInfo.AllocateStack(32, 8);
2948
2949   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2950
2951   // Get a count of how many bytes are to be pushed on the stack.
2952   unsigned NumBytes = CCInfo.getNextStackOffset();
2953   if (IsSibcall)
2954     // This is a sibcall. The memory operands are available in caller's
2955     // own caller's stack.
2956     NumBytes = 0;
2957   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2958            IsTailCallConvention(CallConv))
2959     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2960
2961   int FPDiff = 0;
2962   if (isTailCall && !IsSibcall && !IsMustTail) {
2963     // Lower arguments at fp - stackoffset + fpdiff.
2964     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2965
2966     FPDiff = NumBytesCallerPushed - NumBytes;
2967
2968     // Set the delta of movement of the returnaddr stackslot.
2969     // But only set if delta is greater than previous delta.
2970     if (FPDiff < X86Info->getTCReturnAddrDelta())
2971       X86Info->setTCReturnAddrDelta(FPDiff);
2972   }
2973
2974   unsigned NumBytesToPush = NumBytes;
2975   unsigned NumBytesToPop = NumBytes;
2976
2977   // If we have an inalloca argument, all stack space has already been allocated
2978   // for us and be right at the top of the stack.  We don't support multiple
2979   // arguments passed in memory when using inalloca.
2980   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2981     NumBytesToPush = 0;
2982     if (!ArgLocs.back().isMemLoc())
2983       report_fatal_error("cannot use inalloca attribute on a register "
2984                          "parameter");
2985     if (ArgLocs.back().getLocMemOffset() != 0)
2986       report_fatal_error("any parameter with the inalloca attribute must be "
2987                          "the only memory argument");
2988   }
2989
2990   if (!IsSibcall)
2991     Chain = DAG.getCALLSEQ_START(
2992         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2993
2994   SDValue RetAddrFrIdx;
2995   // Load return address for tail calls.
2996   if (isTailCall && FPDiff)
2997     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2998                                     Is64Bit, FPDiff, dl);
2999
3000   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3001   SmallVector<SDValue, 8> MemOpChains;
3002   SDValue StackPtr;
3003
3004   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3005   // of tail call optimization arguments are handle later.
3006   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3007   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3008     // Skip inalloca arguments, they have already been written.
3009     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3010     if (Flags.isInAlloca())
3011       continue;
3012
3013     CCValAssign &VA = ArgLocs[i];
3014     EVT RegVT = VA.getLocVT();
3015     SDValue Arg = OutVals[i];
3016     bool isByVal = Flags.isByVal();
3017
3018     // Promote the value if needed.
3019     switch (VA.getLocInfo()) {
3020     default: llvm_unreachable("Unknown loc info!");
3021     case CCValAssign::Full: break;
3022     case CCValAssign::SExt:
3023       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3024       break;
3025     case CCValAssign::ZExt:
3026       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3027       break;
3028     case CCValAssign::AExt:
3029       if (Arg.getValueType().isVector() &&
3030           Arg.getValueType().getScalarType() == MVT::i1)
3031         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3032       else if (RegVT.is128BitVector()) {
3033         // Special case: passing MMX values in XMM registers.
3034         Arg = DAG.getBitcast(MVT::i64, Arg);
3035         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3036         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3037       } else
3038         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3039       break;
3040     case CCValAssign::BCvt:
3041       Arg = DAG.getBitcast(RegVT, Arg);
3042       break;
3043     case CCValAssign::Indirect: {
3044       // Store the argument.
3045       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3046       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3047       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
3048                            MachinePointerInfo::getFixedStack(FI),
3049                            false, false, 0);
3050       Arg = SpillSlot;
3051       break;
3052     }
3053     }
3054
3055     if (VA.isRegLoc()) {
3056       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3057       if (isVarArg && IsWin64) {
3058         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3059         // shadow reg if callee is a varargs function.
3060         unsigned ShadowReg = 0;
3061         switch (VA.getLocReg()) {
3062         case X86::XMM0: ShadowReg = X86::RCX; break;
3063         case X86::XMM1: ShadowReg = X86::RDX; break;
3064         case X86::XMM2: ShadowReg = X86::R8; break;
3065         case X86::XMM3: ShadowReg = X86::R9; break;
3066         }
3067         if (ShadowReg)
3068           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3069       }
3070     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3071       assert(VA.isMemLoc());
3072       if (!StackPtr.getNode())
3073         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3074                                       getPointerTy(DAG.getDataLayout()));
3075       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3076                                              dl, DAG, VA, Flags));
3077     }
3078   }
3079
3080   if (!MemOpChains.empty())
3081     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3082
3083   if (Subtarget->isPICStyleGOT()) {
3084     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3085     // GOT pointer.
3086     if (!isTailCall) {
3087       RegsToPass.push_back(std::make_pair(
3088           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3089                                           getPointerTy(DAG.getDataLayout()))));
3090     } else {
3091       // If we are tail calling and generating PIC/GOT style code load the
3092       // address of the callee into ECX. The value in ecx is used as target of
3093       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3094       // for tail calls on PIC/GOT architectures. Normally we would just put the
3095       // address of GOT into ebx and then call target@PLT. But for tail calls
3096       // ebx would be restored (since ebx is callee saved) before jumping to the
3097       // target@PLT.
3098
3099       // Note: The actual moving to ECX is done further down.
3100       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3101       if (G && !G->getGlobal()->hasLocalLinkage() &&
3102           G->getGlobal()->hasDefaultVisibility())
3103         Callee = LowerGlobalAddress(Callee, DAG);
3104       else if (isa<ExternalSymbolSDNode>(Callee))
3105         Callee = LowerExternalSymbol(Callee, DAG);
3106     }
3107   }
3108
3109   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3110     // From AMD64 ABI document:
3111     // For calls that may call functions that use varargs or stdargs
3112     // (prototype-less calls or calls to functions containing ellipsis (...) in
3113     // the declaration) %al is used as hidden argument to specify the number
3114     // of SSE registers used. The contents of %al do not need to match exactly
3115     // the number of registers, but must be an ubound on the number of SSE
3116     // registers used and is in the range 0 - 8 inclusive.
3117
3118     // Count the number of XMM registers allocated.
3119     static const MCPhysReg XMMArgRegs[] = {
3120       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3121       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3122     };
3123     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3124     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3125            && "SSE registers cannot be used when SSE is disabled");
3126
3127     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3128                                         DAG.getConstant(NumXMMRegs, dl,
3129                                                         MVT::i8)));
3130   }
3131
3132   if (isVarArg && IsMustTail) {
3133     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3134     for (const auto &F : Forwards) {
3135       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3136       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3137     }
3138   }
3139
3140   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3141   // don't need this because the eligibility check rejects calls that require
3142   // shuffling arguments passed in memory.
3143   if (!IsSibcall && isTailCall) {
3144     // Force all the incoming stack arguments to be loaded from the stack
3145     // before any new outgoing arguments are stored to the stack, because the
3146     // outgoing stack slots may alias the incoming argument stack slots, and
3147     // the alias isn't otherwise explicit. This is slightly more conservative
3148     // than necessary, because it means that each store effectively depends
3149     // on every argument instead of just those arguments it would clobber.
3150     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3151
3152     SmallVector<SDValue, 8> MemOpChains2;
3153     SDValue FIN;
3154     int FI = 0;
3155     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3156       CCValAssign &VA = ArgLocs[i];
3157       if (VA.isRegLoc())
3158         continue;
3159       assert(VA.isMemLoc());
3160       SDValue Arg = OutVals[i];
3161       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3162       // Skip inalloca arguments.  They don't require any work.
3163       if (Flags.isInAlloca())
3164         continue;
3165       // Create frame index.
3166       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3167       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3168       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3169       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3170
3171       if (Flags.isByVal()) {
3172         // Copy relative to framepointer.
3173         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3174         if (!StackPtr.getNode())
3175           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3176                                         getPointerTy(DAG.getDataLayout()));
3177         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3178                              StackPtr, Source);
3179
3180         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3181                                                          ArgChain,
3182                                                          Flags, DAG, dl));
3183       } else {
3184         // Store relative to framepointer.
3185         MemOpChains2.push_back(
3186           DAG.getStore(ArgChain, dl, Arg, FIN,
3187                        MachinePointerInfo::getFixedStack(FI),
3188                        false, false, 0));
3189       }
3190     }
3191
3192     if (!MemOpChains2.empty())
3193       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3194
3195     // Store the return address to the appropriate stack slot.
3196     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3197                                      getPointerTy(DAG.getDataLayout()),
3198                                      RegInfo->getSlotSize(), FPDiff, dl);
3199   }
3200
3201   // Build a sequence of copy-to-reg nodes chained together with token chain
3202   // and flag operands which copy the outgoing args into registers.
3203   SDValue InFlag;
3204   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3205     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3206                              RegsToPass[i].second, InFlag);
3207     InFlag = Chain.getValue(1);
3208   }
3209
3210   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3211     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3212     // In the 64-bit large code model, we have to make all calls
3213     // through a register, since the call instruction's 32-bit
3214     // pc-relative offset may not be large enough to hold the whole
3215     // address.
3216   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3217     // If the callee is a GlobalAddress node (quite common, every direct call
3218     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3219     // it.
3220     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3221
3222     // We should use extra load for direct calls to dllimported functions in
3223     // non-JIT mode.
3224     const GlobalValue *GV = G->getGlobal();
3225     if (!GV->hasDLLImportStorageClass()) {
3226       unsigned char OpFlags = 0;
3227       bool ExtraLoad = false;
3228       unsigned WrapperKind = ISD::DELETED_NODE;
3229
3230       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3231       // external symbols most go through the PLT in PIC mode.  If the symbol
3232       // has hidden or protected visibility, or if it is static or local, then
3233       // we don't need to use the PLT - we can directly call it.
3234       if (Subtarget->isTargetELF() &&
3235           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3236           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3237         OpFlags = X86II::MO_PLT;
3238       } else if (Subtarget->isPICStyleStubAny() &&
3239                  !GV->isStrongDefinitionForLinker() &&
3240                  (!Subtarget->getTargetTriple().isMacOSX() ||
3241                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3242         // PC-relative references to external symbols should go through $stub,
3243         // unless we're building with the leopard linker or later, which
3244         // automatically synthesizes these stubs.
3245         OpFlags = X86II::MO_DARWIN_STUB;
3246       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3247                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3248         // If the function is marked as non-lazy, generate an indirect call
3249         // which loads from the GOT directly. This avoids runtime overhead
3250         // at the cost of eager binding (and one extra byte of encoding).
3251         OpFlags = X86II::MO_GOTPCREL;
3252         WrapperKind = X86ISD::WrapperRIP;
3253         ExtraLoad = true;
3254       }
3255
3256       Callee = DAG.getTargetGlobalAddress(
3257           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3258
3259       // Add a wrapper if needed.
3260       if (WrapperKind != ISD::DELETED_NODE)
3261         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3262                              getPointerTy(DAG.getDataLayout()), Callee);
3263       // Add extra indirection if needed.
3264       if (ExtraLoad)
3265         Callee = DAG.getLoad(
3266             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3267             MachinePointerInfo::getGOT(), false, false, false, 0);
3268     }
3269   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3270     unsigned char OpFlags = 0;
3271
3272     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3273     // external symbols should go through the PLT.
3274     if (Subtarget->isTargetELF() &&
3275         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3276       OpFlags = X86II::MO_PLT;
3277     } else if (Subtarget->isPICStyleStubAny() &&
3278                (!Subtarget->getTargetTriple().isMacOSX() ||
3279                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3280       // PC-relative references to external symbols should go through $stub,
3281       // unless we're building with the leopard linker or later, which
3282       // automatically synthesizes these stubs.
3283       OpFlags = X86II::MO_DARWIN_STUB;
3284     }
3285
3286     Callee = DAG.getTargetExternalSymbol(
3287         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3288   } else if (Subtarget->isTarget64BitILP32() &&
3289              Callee->getValueType(0) == MVT::i32) {
3290     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3291     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3292   }
3293
3294   // Returns a chain & a flag for retval copy to use.
3295   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3296   SmallVector<SDValue, 8> Ops;
3297
3298   if (!IsSibcall && isTailCall) {
3299     Chain = DAG.getCALLSEQ_END(Chain,
3300                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3301                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3302     InFlag = Chain.getValue(1);
3303   }
3304
3305   Ops.push_back(Chain);
3306   Ops.push_back(Callee);
3307
3308   if (isTailCall)
3309     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3310
3311   // Add argument registers to the end of the list so that they are known live
3312   // into the call.
3313   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3314     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3315                                   RegsToPass[i].second.getValueType()));
3316
3317   // Add a register mask operand representing the call-preserved registers.
3318   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3319   assert(Mask && "Missing call preserved mask for calling convention");
3320
3321   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3322   // the function clobbers all registers. If an exception is thrown, the runtime
3323   // will not restore CSRs.
3324   // FIXME: Model this more precisely so that we can register allocate across
3325   // the normal edge and spill and fill across the exceptional edge.
3326   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3327     const Function *CallerFn = MF.getFunction();
3328     EHPersonality Pers =
3329         CallerFn->hasPersonalityFn()
3330             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3331             : EHPersonality::Unknown;
3332     if (isMSVCEHPersonality(Pers))
3333       Mask = RegInfo->getNoPreservedMask();
3334   }
3335
3336   Ops.push_back(DAG.getRegisterMask(Mask));
3337
3338   if (InFlag.getNode())
3339     Ops.push_back(InFlag);
3340
3341   if (isTailCall) {
3342     // We used to do:
3343     //// If this is the first return lowered for this function, add the regs
3344     //// to the liveout set for the function.
3345     // This isn't right, although it's probably harmless on x86; liveouts
3346     // should be computed from returns not tail calls.  Consider a void
3347     // function making a tail call to a function returning int.
3348     MF.getFrameInfo()->setHasTailCall();
3349     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3350   }
3351
3352   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3353   InFlag = Chain.getValue(1);
3354
3355   // Create the CALLSEQ_END node.
3356   unsigned NumBytesForCalleeToPop;
3357   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3358                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3359     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3360   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3361            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3362            SR == StackStructReturn)
3363     // If this is a call to a struct-return function, the callee
3364     // pops the hidden struct pointer, so we have to push it back.
3365     // This is common for Darwin/X86, Linux & Mingw32 targets.
3366     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3367     NumBytesForCalleeToPop = 4;
3368   else
3369     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3370
3371   // Returns a flag for retval copy to use.
3372   if (!IsSibcall) {
3373     Chain = DAG.getCALLSEQ_END(Chain,
3374                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3375                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3376                                                      true),
3377                                InFlag, dl);
3378     InFlag = Chain.getValue(1);
3379   }
3380
3381   // Handle result values, copying them out of physregs into vregs that we
3382   // return.
3383   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3384                          Ins, dl, DAG, InVals);
3385 }
3386
3387 //===----------------------------------------------------------------------===//
3388 //                Fast Calling Convention (tail call) implementation
3389 //===----------------------------------------------------------------------===//
3390
3391 //  Like std call, callee cleans arguments, convention except that ECX is
3392 //  reserved for storing the tail called function address. Only 2 registers are
3393 //  free for argument passing (inreg). Tail call optimization is performed
3394 //  provided:
3395 //                * tailcallopt is enabled
3396 //                * caller/callee are fastcc
3397 //  On X86_64 architecture with GOT-style position independent code only local
3398 //  (within module) calls are supported at the moment.
3399 //  To keep the stack aligned according to platform abi the function
3400 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3401 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3402 //  If a tail called function callee has more arguments than the caller the
3403 //  caller needs to make sure that there is room to move the RETADDR to. This is
3404 //  achieved by reserving an area the size of the argument delta right after the
3405 //  original RETADDR, but before the saved framepointer or the spilled registers
3406 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3407 //  stack layout:
3408 //    arg1
3409 //    arg2
3410 //    RETADDR
3411 //    [ new RETADDR
3412 //      move area ]
3413 //    (possible EBP)
3414 //    ESI
3415 //    EDI
3416 //    local1 ..
3417
3418 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3419 /// requirement.
3420 unsigned
3421 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3422                                                SelectionDAG& DAG) const {
3423   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3424   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3425   unsigned StackAlignment = TFI.getStackAlignment();
3426   uint64_t AlignMask = StackAlignment - 1;
3427   int64_t Offset = StackSize;
3428   unsigned SlotSize = RegInfo->getSlotSize();
3429   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3430     // Number smaller than 12 so just add the difference.
3431     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3432   } else {
3433     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3434     Offset = ((~AlignMask) & Offset) + StackAlignment +
3435       (StackAlignment-SlotSize);
3436   }
3437   return Offset;
3438 }
3439
3440 /// Return true if the given stack call argument is already available in the
3441 /// same position (relatively) of the caller's incoming argument stack.
3442 static
3443 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3444                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3445                          const X86InstrInfo *TII) {
3446   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3447   int FI = INT_MAX;
3448   if (Arg.getOpcode() == ISD::CopyFromReg) {
3449     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3450     if (!TargetRegisterInfo::isVirtualRegister(VR))
3451       return false;
3452     MachineInstr *Def = MRI->getVRegDef(VR);
3453     if (!Def)
3454       return false;
3455     if (!Flags.isByVal()) {
3456       if (!TII->isLoadFromStackSlot(Def, FI))
3457         return false;
3458     } else {
3459       unsigned Opcode = Def->getOpcode();
3460       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3461            Opcode == X86::LEA64_32r) &&
3462           Def->getOperand(1).isFI()) {
3463         FI = Def->getOperand(1).getIndex();
3464         Bytes = Flags.getByValSize();
3465       } else
3466         return false;
3467     }
3468   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3469     if (Flags.isByVal())
3470       // ByVal argument is passed in as a pointer but it's now being
3471       // dereferenced. e.g.
3472       // define @foo(%struct.X* %A) {
3473       //   tail call @bar(%struct.X* byval %A)
3474       // }
3475       return false;
3476     SDValue Ptr = Ld->getBasePtr();
3477     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3478     if (!FINode)
3479       return false;
3480     FI = FINode->getIndex();
3481   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3482     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3483     FI = FINode->getIndex();
3484     Bytes = Flags.getByValSize();
3485   } else
3486     return false;
3487
3488   assert(FI != INT_MAX);
3489   if (!MFI->isFixedObjectIndex(FI))
3490     return false;
3491   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3492 }
3493
3494 /// Check whether the call is eligible for tail call optimization. Targets
3495 /// that want to do tail call optimization should implement this function.
3496 bool
3497 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3498                                                      CallingConv::ID CalleeCC,
3499                                                      bool isVarArg,
3500                                                      bool isCalleeStructRet,
3501                                                      bool isCallerStructRet,
3502                                                      Type *RetTy,
3503                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3504                                     const SmallVectorImpl<SDValue> &OutVals,
3505                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3506                                                      SelectionDAG &DAG) const {
3507   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3508     return false;
3509
3510   // If -tailcallopt is specified, make fastcc functions tail-callable.
3511   const MachineFunction &MF = DAG.getMachineFunction();
3512   const Function *CallerF = MF.getFunction();
3513
3514   // If the function return type is x86_fp80 and the callee return type is not,
3515   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3516   // perform a tailcall optimization here.
3517   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3518     return false;
3519
3520   CallingConv::ID CallerCC = CallerF->getCallingConv();
3521   bool CCMatch = CallerCC == CalleeCC;
3522   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3523   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3524
3525   // Win64 functions have extra shadow space for argument homing. Don't do the
3526   // sibcall if the caller and callee have mismatched expectations for this
3527   // space.
3528   if (IsCalleeWin64 != IsCallerWin64)
3529     return false;
3530
3531   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3532     if (IsTailCallConvention(CalleeCC) && CCMatch)
3533       return true;
3534     return false;
3535   }
3536
3537   // Look for obvious safe cases to perform tail call optimization that do not
3538   // require ABI changes. This is what gcc calls sibcall.
3539
3540   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3541   // emit a special epilogue.
3542   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3543   if (RegInfo->needsStackRealignment(MF))
3544     return false;
3545
3546   // Also avoid sibcall optimization if either caller or callee uses struct
3547   // return semantics.
3548   if (isCalleeStructRet || isCallerStructRet)
3549     return false;
3550
3551   // An stdcall/thiscall caller is expected to clean up its arguments; the
3552   // callee isn't going to do that.
3553   // FIXME: this is more restrictive than needed. We could produce a tailcall
3554   // when the stack adjustment matches. For example, with a thiscall that takes
3555   // only one argument.
3556   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3557                    CallerCC == CallingConv::X86_ThisCall))
3558     return false;
3559
3560   // Do not sibcall optimize vararg calls unless all arguments are passed via
3561   // registers.
3562   if (isVarArg && !Outs.empty()) {
3563
3564     // Optimizing for varargs on Win64 is unlikely to be safe without
3565     // additional testing.
3566     if (IsCalleeWin64 || IsCallerWin64)
3567       return false;
3568
3569     SmallVector<CCValAssign, 16> ArgLocs;
3570     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3571                    *DAG.getContext());
3572
3573     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3574     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3575       if (!ArgLocs[i].isRegLoc())
3576         return false;
3577   }
3578
3579   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3580   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3581   // this into a sibcall.
3582   bool Unused = false;
3583   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3584     if (!Ins[i].Used) {
3585       Unused = true;
3586       break;
3587     }
3588   }
3589   if (Unused) {
3590     SmallVector<CCValAssign, 16> RVLocs;
3591     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3592                    *DAG.getContext());
3593     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3594     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3595       CCValAssign &VA = RVLocs[i];
3596       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3597         return false;
3598     }
3599   }
3600
3601   // If the calling conventions do not match, then we'd better make sure the
3602   // results are returned in the same way as what the caller expects.
3603   if (!CCMatch) {
3604     SmallVector<CCValAssign, 16> RVLocs1;
3605     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3606                     *DAG.getContext());
3607     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3608
3609     SmallVector<CCValAssign, 16> RVLocs2;
3610     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3611                     *DAG.getContext());
3612     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3613
3614     if (RVLocs1.size() != RVLocs2.size())
3615       return false;
3616     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3617       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3618         return false;
3619       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3620         return false;
3621       if (RVLocs1[i].isRegLoc()) {
3622         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3623           return false;
3624       } else {
3625         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3626           return false;
3627       }
3628     }
3629   }
3630
3631   // If the callee takes no arguments then go on to check the results of the
3632   // call.
3633   if (!Outs.empty()) {
3634     // Check if stack adjustment is needed. For now, do not do this if any
3635     // argument is passed on the stack.
3636     SmallVector<CCValAssign, 16> ArgLocs;
3637     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3638                    *DAG.getContext());
3639
3640     // Allocate shadow area for Win64
3641     if (IsCalleeWin64)
3642       CCInfo.AllocateStack(32, 8);
3643
3644     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3645     if (CCInfo.getNextStackOffset()) {
3646       MachineFunction &MF = DAG.getMachineFunction();
3647       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3648         return false;
3649
3650       // Check if the arguments are already laid out in the right way as
3651       // the caller's fixed stack objects.
3652       MachineFrameInfo *MFI = MF.getFrameInfo();
3653       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3654       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3655       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3656         CCValAssign &VA = ArgLocs[i];
3657         SDValue Arg = OutVals[i];
3658         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3659         if (VA.getLocInfo() == CCValAssign::Indirect)
3660           return false;
3661         if (!VA.isRegLoc()) {
3662           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3663                                    MFI, MRI, TII))
3664             return false;
3665         }
3666       }
3667     }
3668
3669     // If the tailcall address may be in a register, then make sure it's
3670     // possible to register allocate for it. In 32-bit, the call address can
3671     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3672     // callee-saved registers are restored. These happen to be the same
3673     // registers used to pass 'inreg' arguments so watch out for those.
3674     if (!Subtarget->is64Bit() &&
3675         ((!isa<GlobalAddressSDNode>(Callee) &&
3676           !isa<ExternalSymbolSDNode>(Callee)) ||
3677          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3678       unsigned NumInRegs = 0;
3679       // In PIC we need an extra register to formulate the address computation
3680       // for the callee.
3681       unsigned MaxInRegs =
3682         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3683
3684       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3685         CCValAssign &VA = ArgLocs[i];
3686         if (!VA.isRegLoc())
3687           continue;
3688         unsigned Reg = VA.getLocReg();
3689         switch (Reg) {
3690         default: break;
3691         case X86::EAX: case X86::EDX: case X86::ECX:
3692           if (++NumInRegs == MaxInRegs)
3693             return false;
3694           break;
3695         }
3696       }
3697     }
3698   }
3699
3700   return true;
3701 }
3702
3703 FastISel *
3704 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3705                                   const TargetLibraryInfo *libInfo) const {
3706   return X86::createFastISel(funcInfo, libInfo);
3707 }
3708
3709 //===----------------------------------------------------------------------===//
3710 //                           Other Lowering Hooks
3711 //===----------------------------------------------------------------------===//
3712
3713 static bool MayFoldLoad(SDValue Op) {
3714   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3715 }
3716
3717 static bool MayFoldIntoStore(SDValue Op) {
3718   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3719 }
3720
3721 static bool isTargetShuffle(unsigned Opcode) {
3722   switch(Opcode) {
3723   default: return false;
3724   case X86ISD::BLENDI:
3725   case X86ISD::PSHUFB:
3726   case X86ISD::PSHUFD:
3727   case X86ISD::PSHUFHW:
3728   case X86ISD::PSHUFLW:
3729   case X86ISD::SHUFP:
3730   case X86ISD::PALIGNR:
3731   case X86ISD::MOVLHPS:
3732   case X86ISD::MOVLHPD:
3733   case X86ISD::MOVHLPS:
3734   case X86ISD::MOVLPS:
3735   case X86ISD::MOVLPD:
3736   case X86ISD::MOVSHDUP:
3737   case X86ISD::MOVSLDUP:
3738   case X86ISD::MOVDDUP:
3739   case X86ISD::MOVSS:
3740   case X86ISD::MOVSD:
3741   case X86ISD::UNPCKL:
3742   case X86ISD::UNPCKH:
3743   case X86ISD::VPERMILPI:
3744   case X86ISD::VPERM2X128:
3745   case X86ISD::VPERMI:
3746     return true;
3747   }
3748 }
3749
3750 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3751                                     SDValue V1, unsigned TargetMask,
3752                                     SelectionDAG &DAG) {
3753   switch(Opc) {
3754   default: llvm_unreachable("Unknown x86 shuffle node");
3755   case X86ISD::PSHUFD:
3756   case X86ISD::PSHUFHW:
3757   case X86ISD::PSHUFLW:
3758   case X86ISD::VPERMILPI:
3759   case X86ISD::VPERMI:
3760     return DAG.getNode(Opc, dl, VT, V1,
3761                        DAG.getConstant(TargetMask, dl, MVT::i8));
3762   }
3763 }
3764
3765 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3766                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3767   switch(Opc) {
3768   default: llvm_unreachable("Unknown x86 shuffle node");
3769   case X86ISD::MOVLHPS:
3770   case X86ISD::MOVLHPD:
3771   case X86ISD::MOVHLPS:
3772   case X86ISD::MOVLPS:
3773   case X86ISD::MOVLPD:
3774   case X86ISD::MOVSS:
3775   case X86ISD::MOVSD:
3776   case X86ISD::UNPCKL:
3777   case X86ISD::UNPCKH:
3778     return DAG.getNode(Opc, dl, VT, V1, V2);
3779   }
3780 }
3781
3782 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3783   MachineFunction &MF = DAG.getMachineFunction();
3784   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3785   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3786   int ReturnAddrIndex = FuncInfo->getRAIndex();
3787
3788   if (ReturnAddrIndex == 0) {
3789     // Set up a frame object for the return address.
3790     unsigned SlotSize = RegInfo->getSlotSize();
3791     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3792                                                            -(int64_t)SlotSize,
3793                                                            false);
3794     FuncInfo->setRAIndex(ReturnAddrIndex);
3795   }
3796
3797   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3798 }
3799
3800 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3801                                        bool hasSymbolicDisplacement) {
3802   // Offset should fit into 32 bit immediate field.
3803   if (!isInt<32>(Offset))
3804     return false;
3805
3806   // If we don't have a symbolic displacement - we don't have any extra
3807   // restrictions.
3808   if (!hasSymbolicDisplacement)
3809     return true;
3810
3811   // FIXME: Some tweaks might be needed for medium code model.
3812   if (M != CodeModel::Small && M != CodeModel::Kernel)
3813     return false;
3814
3815   // For small code model we assume that latest object is 16MB before end of 31
3816   // bits boundary. We may also accept pretty large negative constants knowing
3817   // that all objects are in the positive half of address space.
3818   if (M == CodeModel::Small && Offset < 16*1024*1024)
3819     return true;
3820
3821   // For kernel code model we know that all object resist in the negative half
3822   // of 32bits address space. We may not accept negative offsets, since they may
3823   // be just off and we may accept pretty large positive ones.
3824   if (M == CodeModel::Kernel && Offset >= 0)
3825     return true;
3826
3827   return false;
3828 }
3829
3830 /// Determines whether the callee is required to pop its own arguments.
3831 /// Callee pop is necessary to support tail calls.
3832 bool X86::isCalleePop(CallingConv::ID CallingConv,
3833                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3834   switch (CallingConv) {
3835   default:
3836     return false;
3837   case CallingConv::X86_StdCall:
3838   case CallingConv::X86_FastCall:
3839   case CallingConv::X86_ThisCall:
3840     return !is64Bit;
3841   case CallingConv::Fast:
3842   case CallingConv::GHC:
3843   case CallingConv::HiPE:
3844     if (IsVarArg)
3845       return false;
3846     return TailCallOpt;
3847   }
3848 }
3849
3850 /// \brief Return true if the condition is an unsigned comparison operation.
3851 static bool isX86CCUnsigned(unsigned X86CC) {
3852   switch (X86CC) {
3853   default: llvm_unreachable("Invalid integer condition!");
3854   case X86::COND_E:     return true;
3855   case X86::COND_G:     return false;
3856   case X86::COND_GE:    return false;
3857   case X86::COND_L:     return false;
3858   case X86::COND_LE:    return false;
3859   case X86::COND_NE:    return true;
3860   case X86::COND_B:     return true;
3861   case X86::COND_A:     return true;
3862   case X86::COND_BE:    return true;
3863   case X86::COND_AE:    return true;
3864   }
3865   llvm_unreachable("covered switch fell through?!");
3866 }
3867
3868 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3869 /// condition code, returning the condition code and the LHS/RHS of the
3870 /// comparison to make.
3871 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3872                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3873   if (!isFP) {
3874     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3875       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3876         // X > -1   -> X == 0, jump !sign.
3877         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3878         return X86::COND_NS;
3879       }
3880       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3881         // X < 0   -> X == 0, jump on sign.
3882         return X86::COND_S;
3883       }
3884       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3885         // X < 1   -> X <= 0
3886         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3887         return X86::COND_LE;
3888       }
3889     }
3890
3891     switch (SetCCOpcode) {
3892     default: llvm_unreachable("Invalid integer condition!");
3893     case ISD::SETEQ:  return X86::COND_E;
3894     case ISD::SETGT:  return X86::COND_G;
3895     case ISD::SETGE:  return X86::COND_GE;
3896     case ISD::SETLT:  return X86::COND_L;
3897     case ISD::SETLE:  return X86::COND_LE;
3898     case ISD::SETNE:  return X86::COND_NE;
3899     case ISD::SETULT: return X86::COND_B;
3900     case ISD::SETUGT: return X86::COND_A;
3901     case ISD::SETULE: return X86::COND_BE;
3902     case ISD::SETUGE: return X86::COND_AE;
3903     }
3904   }
3905
3906   // First determine if it is required or is profitable to flip the operands.
3907
3908   // If LHS is a foldable load, but RHS is not, flip the condition.
3909   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3910       !ISD::isNON_EXTLoad(RHS.getNode())) {
3911     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3912     std::swap(LHS, RHS);
3913   }
3914
3915   switch (SetCCOpcode) {
3916   default: break;
3917   case ISD::SETOLT:
3918   case ISD::SETOLE:
3919   case ISD::SETUGT:
3920   case ISD::SETUGE:
3921     std::swap(LHS, RHS);
3922     break;
3923   }
3924
3925   // On a floating point condition, the flags are set as follows:
3926   // ZF  PF  CF   op
3927   //  0 | 0 | 0 | X > Y
3928   //  0 | 0 | 1 | X < Y
3929   //  1 | 0 | 0 | X == Y
3930   //  1 | 1 | 1 | unordered
3931   switch (SetCCOpcode) {
3932   default: llvm_unreachable("Condcode should be pre-legalized away");
3933   case ISD::SETUEQ:
3934   case ISD::SETEQ:   return X86::COND_E;
3935   case ISD::SETOLT:              // flipped
3936   case ISD::SETOGT:
3937   case ISD::SETGT:   return X86::COND_A;
3938   case ISD::SETOLE:              // flipped
3939   case ISD::SETOGE:
3940   case ISD::SETGE:   return X86::COND_AE;
3941   case ISD::SETUGT:              // flipped
3942   case ISD::SETULT:
3943   case ISD::SETLT:   return X86::COND_B;
3944   case ISD::SETUGE:              // flipped
3945   case ISD::SETULE:
3946   case ISD::SETLE:   return X86::COND_BE;
3947   case ISD::SETONE:
3948   case ISD::SETNE:   return X86::COND_NE;
3949   case ISD::SETUO:   return X86::COND_P;
3950   case ISD::SETO:    return X86::COND_NP;
3951   case ISD::SETOEQ:
3952   case ISD::SETUNE:  return X86::COND_INVALID;
3953   }
3954 }
3955
3956 /// Is there a floating point cmov for the specific X86 condition code?
3957 /// Current x86 isa includes the following FP cmov instructions:
3958 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3959 static bool hasFPCMov(unsigned X86CC) {
3960   switch (X86CC) {
3961   default:
3962     return false;
3963   case X86::COND_B:
3964   case X86::COND_BE:
3965   case X86::COND_E:
3966   case X86::COND_P:
3967   case X86::COND_A:
3968   case X86::COND_AE:
3969   case X86::COND_NE:
3970   case X86::COND_NP:
3971     return true;
3972   }
3973 }
3974
3975 /// Returns true if the target can instruction select the
3976 /// specified FP immediate natively. If false, the legalizer will
3977 /// materialize the FP immediate as a load from a constant pool.
3978 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3979   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3980     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3981       return true;
3982   }
3983   return false;
3984 }
3985
3986 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3987                                               ISD::LoadExtType ExtTy,
3988                                               EVT NewVT) const {
3989   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3990   // relocation target a movq or addq instruction: don't let the load shrink.
3991   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3992   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3993     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3994       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3995   return true;
3996 }
3997
3998 /// \brief Returns true if it is beneficial to convert a load of a constant
3999 /// to just the constant itself.
4000 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4001                                                           Type *Ty) const {
4002   assert(Ty->isIntegerTy());
4003
4004   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4005   if (BitSize == 0 || BitSize > 64)
4006     return false;
4007   return true;
4008 }
4009
4010 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4011                                                 unsigned Index) const {
4012   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4013     return false;
4014
4015   return (Index == 0 || Index == ResVT.getVectorNumElements());
4016 }
4017
4018 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4019   // Speculate cttz only if we can directly use TZCNT.
4020   return Subtarget->hasBMI();
4021 }
4022
4023 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4024   // Speculate ctlz only if we can directly use LZCNT.
4025   return Subtarget->hasLZCNT();
4026 }
4027
4028 /// Return true if every element in Mask, beginning
4029 /// from position Pos and ending in Pos+Size is undef.
4030 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4031   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4032     if (0 <= Mask[i])
4033       return false;
4034   return true;
4035 }
4036
4037 /// Return true if Val is undef or if its value falls within the
4038 /// specified range (L, H].
4039 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4040   return (Val < 0) || (Val >= Low && Val < Hi);
4041 }
4042
4043 /// Val is either less than zero (undef) or equal to the specified value.
4044 static bool isUndefOrEqual(int Val, int CmpVal) {
4045   return (Val < 0 || Val == CmpVal);
4046 }
4047
4048 /// Return true if every element in Mask, beginning
4049 /// from position Pos and ending in Pos+Size, falls within the specified
4050 /// sequential range (Low, Low+Size]. or is undef.
4051 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4052                                        unsigned Pos, unsigned Size, int Low) {
4053   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4054     if (!isUndefOrEqual(Mask[i], Low))
4055       return false;
4056   return true;
4057 }
4058
4059 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4060 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4061 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4062   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4063   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4064     return false;
4065
4066   // The index should be aligned on a vecWidth-bit boundary.
4067   uint64_t Index =
4068     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4069
4070   MVT VT = N->getSimpleValueType(0);
4071   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4072   bool Result = (Index * ElSize) % vecWidth == 0;
4073
4074   return Result;
4075 }
4076
4077 /// Return true if the specified INSERT_SUBVECTOR
4078 /// operand specifies a subvector insert that is suitable for input to
4079 /// insertion of 128 or 256-bit subvectors
4080 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4081   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4082   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4083     return false;
4084   // The index should be aligned on a vecWidth-bit boundary.
4085   uint64_t Index =
4086     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4087
4088   MVT VT = N->getSimpleValueType(0);
4089   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4090   bool Result = (Index * ElSize) % vecWidth == 0;
4091
4092   return Result;
4093 }
4094
4095 bool X86::isVINSERT128Index(SDNode *N) {
4096   return isVINSERTIndex(N, 128);
4097 }
4098
4099 bool X86::isVINSERT256Index(SDNode *N) {
4100   return isVINSERTIndex(N, 256);
4101 }
4102
4103 bool X86::isVEXTRACT128Index(SDNode *N) {
4104   return isVEXTRACTIndex(N, 128);
4105 }
4106
4107 bool X86::isVEXTRACT256Index(SDNode *N) {
4108   return isVEXTRACTIndex(N, 256);
4109 }
4110
4111 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4112   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4113   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4114     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4115
4116   uint64_t Index =
4117     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4118
4119   MVT VecVT = N->getOperand(0).getSimpleValueType();
4120   MVT ElVT = VecVT.getVectorElementType();
4121
4122   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4123   return Index / NumElemsPerChunk;
4124 }
4125
4126 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4127   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4128   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4129     llvm_unreachable("Illegal insert subvector for VINSERT");
4130
4131   uint64_t Index =
4132     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4133
4134   MVT VecVT = N->getSimpleValueType(0);
4135   MVT ElVT = VecVT.getVectorElementType();
4136
4137   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4138   return Index / NumElemsPerChunk;
4139 }
4140
4141 /// Return the appropriate immediate to extract the specified
4142 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4143 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4144   return getExtractVEXTRACTImmediate(N, 128);
4145 }
4146
4147 /// Return the appropriate immediate to extract the specified
4148 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4149 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4150   return getExtractVEXTRACTImmediate(N, 256);
4151 }
4152
4153 /// Return the appropriate immediate to insert at the specified
4154 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4155 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4156   return getInsertVINSERTImmediate(N, 128);
4157 }
4158
4159 /// Return the appropriate immediate to insert at the specified
4160 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4161 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4162   return getInsertVINSERTImmediate(N, 256);
4163 }
4164
4165 /// Returns true if Elt is a constant integer zero
4166 static bool isZero(SDValue V) {
4167   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4168   return C && C->isNullValue();
4169 }
4170
4171 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4172 bool X86::isZeroNode(SDValue Elt) {
4173   if (isZero(Elt))
4174     return true;
4175   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4176     return CFP->getValueAPF().isPosZero();
4177   return false;
4178 }
4179
4180 /// Returns a vector of specified type with all zero elements.
4181 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4182                              SelectionDAG &DAG, SDLoc dl) {
4183   assert(VT.isVector() && "Expected a vector type");
4184
4185   // Always build SSE zero vectors as <4 x i32> bitcasted
4186   // to their dest type. This ensures they get CSE'd.
4187   SDValue Vec;
4188   if (VT.is128BitVector()) {  // SSE
4189     if (Subtarget->hasSSE2()) {  // SSE2
4190       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4191       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4192     } else { // SSE1
4193       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4194       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4195     }
4196   } else if (VT.is256BitVector()) { // AVX
4197     if (Subtarget->hasInt256()) { // AVX2
4198       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4199       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4200       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4201     } else {
4202       // 256-bit logic and arithmetic instructions in AVX are all
4203       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4204       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4205       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4206       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4207     }
4208   } else if (VT.is512BitVector()) { // AVX-512
4209       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4210       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4211                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4212       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4213   } else if (VT.getScalarType() == MVT::i1) {
4214
4215     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4216             && "Unexpected vector type");
4217     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4218             && "Unexpected vector type");
4219     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4220     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4221     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4222   } else
4223     llvm_unreachable("Unexpected vector type");
4224
4225   return DAG.getBitcast(VT, Vec);
4226 }
4227
4228 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4229                                 SelectionDAG &DAG, SDLoc dl,
4230                                 unsigned vectorWidth) {
4231   assert((vectorWidth == 128 || vectorWidth == 256) &&
4232          "Unsupported vector width");
4233   EVT VT = Vec.getValueType();
4234   EVT ElVT = VT.getVectorElementType();
4235   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4236   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4237                                   VT.getVectorNumElements()/Factor);
4238
4239   // Extract from UNDEF is UNDEF.
4240   if (Vec.getOpcode() == ISD::UNDEF)
4241     return DAG.getUNDEF(ResultVT);
4242
4243   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4244   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4245
4246   // This is the index of the first element of the vectorWidth-bit chunk
4247   // we want.
4248   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4249                                * ElemsPerChunk);
4250
4251   // If the input is a buildvector just emit a smaller one.
4252   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4253     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4254                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4255                                     ElemsPerChunk));
4256
4257   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4258   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4259 }
4260
4261 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4262 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4263 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4264 /// instructions or a simple subregister reference. Idx is an index in the
4265 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4266 /// lowering EXTRACT_VECTOR_ELT operations easier.
4267 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4268                                    SelectionDAG &DAG, SDLoc dl) {
4269   assert((Vec.getValueType().is256BitVector() ||
4270           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4271   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4272 }
4273
4274 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4275 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4276                                    SelectionDAG &DAG, SDLoc dl) {
4277   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4278   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4279 }
4280
4281 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4282                                unsigned IdxVal, SelectionDAG &DAG,
4283                                SDLoc dl, unsigned vectorWidth) {
4284   assert((vectorWidth == 128 || vectorWidth == 256) &&
4285          "Unsupported vector width");
4286   // Inserting UNDEF is Result
4287   if (Vec.getOpcode() == ISD::UNDEF)
4288     return Result;
4289   EVT VT = Vec.getValueType();
4290   EVT ElVT = VT.getVectorElementType();
4291   EVT ResultVT = Result.getValueType();
4292
4293   // Insert the relevant vectorWidth bits.
4294   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4295
4296   // This is the index of the first element of the vectorWidth-bit chunk
4297   // we want.
4298   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4299                                * ElemsPerChunk);
4300
4301   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4302   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4303 }
4304
4305 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4306 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4307 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4308 /// simple superregister reference.  Idx is an index in the 128 bits
4309 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4310 /// lowering INSERT_VECTOR_ELT operations easier.
4311 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4312                                   SelectionDAG &DAG, SDLoc dl) {
4313   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4314
4315   // For insertion into the zero index (low half) of a 256-bit vector, it is
4316   // more efficient to generate a blend with immediate instead of an insert*128.
4317   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4318   // extend the subvector to the size of the result vector. Make sure that
4319   // we are not recursing on that node by checking for undef here.
4320   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4321       Result.getOpcode() != ISD::UNDEF) {
4322     EVT ResultVT = Result.getValueType();
4323     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4324     SDValue Undef = DAG.getUNDEF(ResultVT);
4325     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4326                                  Vec, ZeroIndex);
4327
4328     // The blend instruction, and therefore its mask, depend on the data type.
4329     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4330     if (ScalarType.isFloatingPoint()) {
4331       // Choose either vblendps (float) or vblendpd (double).
4332       unsigned ScalarSize = ScalarType.getSizeInBits();
4333       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4334       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4335       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4336       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4337     }
4338
4339     const X86Subtarget &Subtarget =
4340     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4341
4342     // AVX2 is needed for 256-bit integer blend support.
4343     // Integers must be cast to 32-bit because there is only vpblendd;
4344     // vpblendw can't be used for this because it has a handicapped mask.
4345
4346     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4347     // is still more efficient than using the wrong domain vinsertf128 that
4348     // will be created by InsertSubVector().
4349     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4350
4351     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4352     Vec256 = DAG.getBitcast(CastVT, Vec256);
4353     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4354     return DAG.getBitcast(ResultVT, Vec256);
4355   }
4356
4357   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4358 }
4359
4360 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4361                                   SelectionDAG &DAG, SDLoc dl) {
4362   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4363   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4364 }
4365
4366 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4367 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4368 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4369 /// large BUILD_VECTORS.
4370 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4371                                    unsigned NumElems, SelectionDAG &DAG,
4372                                    SDLoc dl) {
4373   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4374   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4375 }
4376
4377 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4378                                    unsigned NumElems, SelectionDAG &DAG,
4379                                    SDLoc dl) {
4380   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4381   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4382 }
4383
4384 /// Returns a vector of specified type with all bits set.
4385 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4386 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4387 /// Then bitcast to their original type, ensuring they get CSE'd.
4388 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4389                              SDLoc dl) {
4390   assert(VT.isVector() && "Expected a vector type");
4391
4392   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4393   SDValue Vec;
4394   if (VT.is256BitVector()) {
4395     if (HasInt256) { // AVX2
4396       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4397       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4398     } else { // AVX
4399       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4400       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4401     }
4402   } else if (VT.is128BitVector()) {
4403     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4404   } else
4405     llvm_unreachable("Unexpected vector type");
4406
4407   return DAG.getBitcast(VT, Vec);
4408 }
4409
4410 /// Returns a vector_shuffle node for an unpackl operation.
4411 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4412                           SDValue V2) {
4413   unsigned NumElems = VT.getVectorNumElements();
4414   SmallVector<int, 8> Mask;
4415   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4416     Mask.push_back(i);
4417     Mask.push_back(i + NumElems);
4418   }
4419   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4420 }
4421
4422 /// Returns a vector_shuffle node for an unpackh operation.
4423 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4424                           SDValue V2) {
4425   unsigned NumElems = VT.getVectorNumElements();
4426   SmallVector<int, 8> Mask;
4427   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4428     Mask.push_back(i + Half);
4429     Mask.push_back(i + NumElems + Half);
4430   }
4431   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4432 }
4433
4434 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4435 /// This produces a shuffle where the low element of V2 is swizzled into the
4436 /// zero/undef vector, landing at element Idx.
4437 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4438 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4439                                            bool IsZero,
4440                                            const X86Subtarget *Subtarget,
4441                                            SelectionDAG &DAG) {
4442   MVT VT = V2.getSimpleValueType();
4443   SDValue V1 = IsZero
4444     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4445   unsigned NumElems = VT.getVectorNumElements();
4446   SmallVector<int, 16> MaskVec;
4447   for (unsigned i = 0; i != NumElems; ++i)
4448     // If this is the insertion idx, put the low elt of V2 here.
4449     MaskVec.push_back(i == Idx ? NumElems : i);
4450   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4451 }
4452
4453 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4454 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4455 /// uses one source. Note that this will set IsUnary for shuffles which use a
4456 /// single input multiple times, and in those cases it will
4457 /// adjust the mask to only have indices within that single input.
4458 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4459 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4460                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4461   unsigned NumElems = VT.getVectorNumElements();
4462   SDValue ImmN;
4463
4464   IsUnary = false;
4465   bool IsFakeUnary = false;
4466   switch(N->getOpcode()) {
4467   case X86ISD::BLENDI:
4468     ImmN = N->getOperand(N->getNumOperands()-1);
4469     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4470     break;
4471   case X86ISD::SHUFP:
4472     ImmN = N->getOperand(N->getNumOperands()-1);
4473     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4474     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4475     break;
4476   case X86ISD::UNPCKH:
4477     DecodeUNPCKHMask(VT, Mask);
4478     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4479     break;
4480   case X86ISD::UNPCKL:
4481     DecodeUNPCKLMask(VT, Mask);
4482     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4483     break;
4484   case X86ISD::MOVHLPS:
4485     DecodeMOVHLPSMask(NumElems, Mask);
4486     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4487     break;
4488   case X86ISD::MOVLHPS:
4489     DecodeMOVLHPSMask(NumElems, Mask);
4490     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4491     break;
4492   case X86ISD::PALIGNR:
4493     ImmN = N->getOperand(N->getNumOperands()-1);
4494     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4495     break;
4496   case X86ISD::PSHUFD:
4497   case X86ISD::VPERMILPI:
4498     ImmN = N->getOperand(N->getNumOperands()-1);
4499     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4500     IsUnary = true;
4501     break;
4502   case X86ISD::PSHUFHW:
4503     ImmN = N->getOperand(N->getNumOperands()-1);
4504     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4505     IsUnary = true;
4506     break;
4507   case X86ISD::PSHUFLW:
4508     ImmN = N->getOperand(N->getNumOperands()-1);
4509     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4510     IsUnary = true;
4511     break;
4512   case X86ISD::PSHUFB: {
4513     IsUnary = true;
4514     SDValue MaskNode = N->getOperand(1);
4515     while (MaskNode->getOpcode() == ISD::BITCAST)
4516       MaskNode = MaskNode->getOperand(0);
4517
4518     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4519       // If we have a build-vector, then things are easy.
4520       EVT VT = MaskNode.getValueType();
4521       assert(VT.isVector() &&
4522              "Can't produce a non-vector with a build_vector!");
4523       if (!VT.isInteger())
4524         return false;
4525
4526       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4527
4528       SmallVector<uint64_t, 32> RawMask;
4529       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4530         SDValue Op = MaskNode->getOperand(i);
4531         if (Op->getOpcode() == ISD::UNDEF) {
4532           RawMask.push_back((uint64_t)SM_SentinelUndef);
4533           continue;
4534         }
4535         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4536         if (!CN)
4537           return false;
4538         APInt MaskElement = CN->getAPIntValue();
4539
4540         // We now have to decode the element which could be any integer size and
4541         // extract each byte of it.
4542         for (int j = 0; j < NumBytesPerElement; ++j) {
4543           // Note that this is x86 and so always little endian: the low byte is
4544           // the first byte of the mask.
4545           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4546           MaskElement = MaskElement.lshr(8);
4547         }
4548       }
4549       DecodePSHUFBMask(RawMask, Mask);
4550       break;
4551     }
4552
4553     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4554     if (!MaskLoad)
4555       return false;
4556
4557     SDValue Ptr = MaskLoad->getBasePtr();
4558     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4559         Ptr->getOpcode() == X86ISD::WrapperRIP)
4560       Ptr = Ptr->getOperand(0);
4561
4562     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4563     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4564       return false;
4565
4566     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4567       DecodePSHUFBMask(C, Mask);
4568       if (Mask.empty())
4569         return false;
4570       break;
4571     }
4572
4573     return false;
4574   }
4575   case X86ISD::VPERMI:
4576     ImmN = N->getOperand(N->getNumOperands()-1);
4577     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4578     IsUnary = true;
4579     break;
4580   case X86ISD::MOVSS:
4581   case X86ISD::MOVSD:
4582     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4583     break;
4584   case X86ISD::VPERM2X128:
4585     ImmN = N->getOperand(N->getNumOperands()-1);
4586     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4587     if (Mask.empty()) return false;
4588     // Mask only contains negative index if an element is zero.
4589     if (std::any_of(Mask.begin(), Mask.end(),
4590                     [](int M){ return M == SM_SentinelZero; }))
4591       return false;
4592     break;
4593   case X86ISD::MOVSLDUP:
4594     DecodeMOVSLDUPMask(VT, Mask);
4595     IsUnary = true;
4596     break;
4597   case X86ISD::MOVSHDUP:
4598     DecodeMOVSHDUPMask(VT, Mask);
4599     IsUnary = true;
4600     break;
4601   case X86ISD::MOVDDUP:
4602     DecodeMOVDDUPMask(VT, Mask);
4603     IsUnary = true;
4604     break;
4605   case X86ISD::MOVLHPD:
4606   case X86ISD::MOVLPD:
4607   case X86ISD::MOVLPS:
4608     // Not yet implemented
4609     return false;
4610   default: llvm_unreachable("unknown target shuffle node");
4611   }
4612
4613   // If we have a fake unary shuffle, the shuffle mask is spread across two
4614   // inputs that are actually the same node. Re-map the mask to always point
4615   // into the first input.
4616   if (IsFakeUnary)
4617     for (int &M : Mask)
4618       if (M >= (int)Mask.size())
4619         M -= Mask.size();
4620
4621   return true;
4622 }
4623
4624 /// Returns the scalar element that will make up the ith
4625 /// element of the result of the vector shuffle.
4626 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4627                                    unsigned Depth) {
4628   if (Depth == 6)
4629     return SDValue();  // Limit search depth.
4630
4631   SDValue V = SDValue(N, 0);
4632   EVT VT = V.getValueType();
4633   unsigned Opcode = V.getOpcode();
4634
4635   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4636   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4637     int Elt = SV->getMaskElt(Index);
4638
4639     if (Elt < 0)
4640       return DAG.getUNDEF(VT.getVectorElementType());
4641
4642     unsigned NumElems = VT.getVectorNumElements();
4643     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4644                                          : SV->getOperand(1);
4645     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4646   }
4647
4648   // Recurse into target specific vector shuffles to find scalars.
4649   if (isTargetShuffle(Opcode)) {
4650     MVT ShufVT = V.getSimpleValueType();
4651     unsigned NumElems = ShufVT.getVectorNumElements();
4652     SmallVector<int, 16> ShuffleMask;
4653     bool IsUnary;
4654
4655     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4656       return SDValue();
4657
4658     int Elt = ShuffleMask[Index];
4659     if (Elt < 0)
4660       return DAG.getUNDEF(ShufVT.getVectorElementType());
4661
4662     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4663                                          : N->getOperand(1);
4664     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4665                                Depth+1);
4666   }
4667
4668   // Actual nodes that may contain scalar elements
4669   if (Opcode == ISD::BITCAST) {
4670     V = V.getOperand(0);
4671     EVT SrcVT = V.getValueType();
4672     unsigned NumElems = VT.getVectorNumElements();
4673
4674     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4675       return SDValue();
4676   }
4677
4678   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4679     return (Index == 0) ? V.getOperand(0)
4680                         : DAG.getUNDEF(VT.getVectorElementType());
4681
4682   if (V.getOpcode() == ISD::BUILD_VECTOR)
4683     return V.getOperand(Index);
4684
4685   return SDValue();
4686 }
4687
4688 /// Custom lower build_vector of v16i8.
4689 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4690                                        unsigned NumNonZero, unsigned NumZero,
4691                                        SelectionDAG &DAG,
4692                                        const X86Subtarget* Subtarget,
4693                                        const TargetLowering &TLI) {
4694   if (NumNonZero > 8)
4695     return SDValue();
4696
4697   SDLoc dl(Op);
4698   SDValue V;
4699   bool First = true;
4700
4701   // SSE4.1 - use PINSRB to insert each byte directly.
4702   if (Subtarget->hasSSE41()) {
4703     for (unsigned i = 0; i < 16; ++i) {
4704       bool isNonZero = (NonZeros & (1 << i)) != 0;
4705       if (isNonZero) {
4706         if (First) {
4707           if (NumZero)
4708             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4709           else
4710             V = DAG.getUNDEF(MVT::v16i8);
4711           First = false;
4712         }
4713         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4714                         MVT::v16i8, V, Op.getOperand(i),
4715                         DAG.getIntPtrConstant(i, dl));
4716       }
4717     }
4718
4719     return V;
4720   }
4721
4722   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4723   for (unsigned i = 0; i < 16; ++i) {
4724     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4725     if (ThisIsNonZero && First) {
4726       if (NumZero)
4727         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4728       else
4729         V = DAG.getUNDEF(MVT::v8i16);
4730       First = false;
4731     }
4732
4733     if ((i & 1) != 0) {
4734       SDValue ThisElt, LastElt;
4735       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4736       if (LastIsNonZero) {
4737         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4738                               MVT::i16, Op.getOperand(i-1));
4739       }
4740       if (ThisIsNonZero) {
4741         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4742         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4743                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4744         if (LastIsNonZero)
4745           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4746       } else
4747         ThisElt = LastElt;
4748
4749       if (ThisElt.getNode())
4750         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4751                         DAG.getIntPtrConstant(i/2, dl));
4752     }
4753   }
4754
4755   return DAG.getBitcast(MVT::v16i8, V);
4756 }
4757
4758 /// Custom lower build_vector of v8i16.
4759 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4760                                      unsigned NumNonZero, unsigned NumZero,
4761                                      SelectionDAG &DAG,
4762                                      const X86Subtarget* Subtarget,
4763                                      const TargetLowering &TLI) {
4764   if (NumNonZero > 4)
4765     return SDValue();
4766
4767   SDLoc dl(Op);
4768   SDValue V;
4769   bool First = true;
4770   for (unsigned i = 0; i < 8; ++i) {
4771     bool isNonZero = (NonZeros & (1 << i)) != 0;
4772     if (isNonZero) {
4773       if (First) {
4774         if (NumZero)
4775           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4776         else
4777           V = DAG.getUNDEF(MVT::v8i16);
4778         First = false;
4779       }
4780       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4781                       MVT::v8i16, V, Op.getOperand(i),
4782                       DAG.getIntPtrConstant(i, dl));
4783     }
4784   }
4785
4786   return V;
4787 }
4788
4789 /// Custom lower build_vector of v4i32 or v4f32.
4790 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4791                                      const X86Subtarget *Subtarget,
4792                                      const TargetLowering &TLI) {
4793   // Find all zeroable elements.
4794   std::bitset<4> Zeroable;
4795   for (int i=0; i < 4; ++i) {
4796     SDValue Elt = Op->getOperand(i);
4797     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4798   }
4799   assert(Zeroable.size() - Zeroable.count() > 1 &&
4800          "We expect at least two non-zero elements!");
4801
4802   // We only know how to deal with build_vector nodes where elements are either
4803   // zeroable or extract_vector_elt with constant index.
4804   SDValue FirstNonZero;
4805   unsigned FirstNonZeroIdx;
4806   for (unsigned i=0; i < 4; ++i) {
4807     if (Zeroable[i])
4808       continue;
4809     SDValue Elt = Op->getOperand(i);
4810     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4811         !isa<ConstantSDNode>(Elt.getOperand(1)))
4812       return SDValue();
4813     // Make sure that this node is extracting from a 128-bit vector.
4814     MVT VT = Elt.getOperand(0).getSimpleValueType();
4815     if (!VT.is128BitVector())
4816       return SDValue();
4817     if (!FirstNonZero.getNode()) {
4818       FirstNonZero = Elt;
4819       FirstNonZeroIdx = i;
4820     }
4821   }
4822
4823   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4824   SDValue V1 = FirstNonZero.getOperand(0);
4825   MVT VT = V1.getSimpleValueType();
4826
4827   // See if this build_vector can be lowered as a blend with zero.
4828   SDValue Elt;
4829   unsigned EltMaskIdx, EltIdx;
4830   int Mask[4];
4831   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4832     if (Zeroable[EltIdx]) {
4833       // The zero vector will be on the right hand side.
4834       Mask[EltIdx] = EltIdx+4;
4835       continue;
4836     }
4837
4838     Elt = Op->getOperand(EltIdx);
4839     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4840     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4841     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4842       break;
4843     Mask[EltIdx] = EltIdx;
4844   }
4845
4846   if (EltIdx == 4) {
4847     // Let the shuffle legalizer deal with blend operations.
4848     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4849     if (V1.getSimpleValueType() != VT)
4850       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4851     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4852   }
4853
4854   // See if we can lower this build_vector to a INSERTPS.
4855   if (!Subtarget->hasSSE41())
4856     return SDValue();
4857
4858   SDValue V2 = Elt.getOperand(0);
4859   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4860     V1 = SDValue();
4861
4862   bool CanFold = true;
4863   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4864     if (Zeroable[i])
4865       continue;
4866
4867     SDValue Current = Op->getOperand(i);
4868     SDValue SrcVector = Current->getOperand(0);
4869     if (!V1.getNode())
4870       V1 = SrcVector;
4871     CanFold = SrcVector == V1 &&
4872       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4873   }
4874
4875   if (!CanFold)
4876     return SDValue();
4877
4878   assert(V1.getNode() && "Expected at least two non-zero elements!");
4879   if (V1.getSimpleValueType() != MVT::v4f32)
4880     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4881   if (V2.getSimpleValueType() != MVT::v4f32)
4882     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4883
4884   // Ok, we can emit an INSERTPS instruction.
4885   unsigned ZMask = Zeroable.to_ulong();
4886
4887   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4888   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4889   SDLoc DL(Op);
4890   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4891                                DAG.getIntPtrConstant(InsertPSMask, DL));
4892   return DAG.getBitcast(VT, Result);
4893 }
4894
4895 /// Return a vector logical shift node.
4896 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4897                          unsigned NumBits, SelectionDAG &DAG,
4898                          const TargetLowering &TLI, SDLoc dl) {
4899   assert(VT.is128BitVector() && "Unknown type for VShift");
4900   MVT ShVT = MVT::v2i64;
4901   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4902   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4903   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4904   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4905   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4906   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4907 }
4908
4909 static SDValue
4910 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4911
4912   // Check if the scalar load can be widened into a vector load. And if
4913   // the address is "base + cst" see if the cst can be "absorbed" into
4914   // the shuffle mask.
4915   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4916     SDValue Ptr = LD->getBasePtr();
4917     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4918       return SDValue();
4919     EVT PVT = LD->getValueType(0);
4920     if (PVT != MVT::i32 && PVT != MVT::f32)
4921       return SDValue();
4922
4923     int FI = -1;
4924     int64_t Offset = 0;
4925     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4926       FI = FINode->getIndex();
4927       Offset = 0;
4928     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4929                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4930       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4931       Offset = Ptr.getConstantOperandVal(1);
4932       Ptr = Ptr.getOperand(0);
4933     } else {
4934       return SDValue();
4935     }
4936
4937     // FIXME: 256-bit vector instructions don't require a strict alignment,
4938     // improve this code to support it better.
4939     unsigned RequiredAlign = VT.getSizeInBits()/8;
4940     SDValue Chain = LD->getChain();
4941     // Make sure the stack object alignment is at least 16 or 32.
4942     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4943     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4944       if (MFI->isFixedObjectIndex(FI)) {
4945         // Can't change the alignment. FIXME: It's possible to compute
4946         // the exact stack offset and reference FI + adjust offset instead.
4947         // If someone *really* cares about this. That's the way to implement it.
4948         return SDValue();
4949       } else {
4950         MFI->setObjectAlignment(FI, RequiredAlign);
4951       }
4952     }
4953
4954     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4955     // Ptr + (Offset & ~15).
4956     if (Offset < 0)
4957       return SDValue();
4958     if ((Offset % RequiredAlign) & 3)
4959       return SDValue();
4960     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4961     if (StartOffset) {
4962       SDLoc DL(Ptr);
4963       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4964                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4965     }
4966
4967     int EltNo = (Offset - StartOffset) >> 2;
4968     unsigned NumElems = VT.getVectorNumElements();
4969
4970     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4971     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4972                              LD->getPointerInfo().getWithOffset(StartOffset),
4973                              false, false, false, 0);
4974
4975     SmallVector<int, 8> Mask(NumElems, EltNo);
4976
4977     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4978   }
4979
4980   return SDValue();
4981 }
4982
4983 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4984 /// elements can be replaced by a single large load which has the same value as
4985 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4986 ///
4987 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4988 ///
4989 /// FIXME: we'd also like to handle the case where the last elements are zero
4990 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4991 /// There's even a handy isZeroNode for that purpose.
4992 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4993                                         SDLoc &DL, SelectionDAG &DAG,
4994                                         bool isAfterLegalize) {
4995   unsigned NumElems = Elts.size();
4996
4997   LoadSDNode *LDBase = nullptr;
4998   unsigned LastLoadedElt = -1U;
4999
5000   // For each element in the initializer, see if we've found a load or an undef.
5001   // If we don't find an initial load element, or later load elements are
5002   // non-consecutive, bail out.
5003   for (unsigned i = 0; i < NumElems; ++i) {
5004     SDValue Elt = Elts[i];
5005     // Look through a bitcast.
5006     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5007       Elt = Elt.getOperand(0);
5008     if (!Elt.getNode() ||
5009         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5010       return SDValue();
5011     if (!LDBase) {
5012       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5013         return SDValue();
5014       LDBase = cast<LoadSDNode>(Elt.getNode());
5015       LastLoadedElt = i;
5016       continue;
5017     }
5018     if (Elt.getOpcode() == ISD::UNDEF)
5019       continue;
5020
5021     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5022     EVT LdVT = Elt.getValueType();
5023     // Each loaded element must be the correct fractional portion of the
5024     // requested vector load.
5025     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5026       return SDValue();
5027     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5028       return SDValue();
5029     LastLoadedElt = i;
5030   }
5031
5032   // If we have found an entire vector of loads and undefs, then return a large
5033   // load of the entire vector width starting at the base pointer.  If we found
5034   // consecutive loads for the low half, generate a vzext_load node.
5035   if (LastLoadedElt == NumElems - 1) {
5036     assert(LDBase && "Did not find base load for merging consecutive loads");
5037     EVT EltVT = LDBase->getValueType(0);
5038     // Ensure that the input vector size for the merged loads matches the
5039     // cumulative size of the input elements.
5040     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5041       return SDValue();
5042
5043     if (isAfterLegalize &&
5044         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5045       return SDValue();
5046
5047     SDValue NewLd = SDValue();
5048
5049     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5050                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5051                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5052                         LDBase->getAlignment());
5053
5054     if (LDBase->hasAnyUseOfValue(1)) {
5055       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5056                                      SDValue(LDBase, 1),
5057                                      SDValue(NewLd.getNode(), 1));
5058       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5059       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5060                              SDValue(NewLd.getNode(), 1));
5061     }
5062
5063     return NewLd;
5064   }
5065
5066   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5067   //of a v4i32 / v4f32. It's probably worth generalizing.
5068   EVT EltVT = VT.getVectorElementType();
5069   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5070       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5071     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5072     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5073     SDValue ResNode =
5074         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5075                                 LDBase->getPointerInfo(),
5076                                 LDBase->getAlignment(),
5077                                 false/*isVolatile*/, true/*ReadMem*/,
5078                                 false/*WriteMem*/);
5079
5080     // Make sure the newly-created LOAD is in the same position as LDBase in
5081     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5082     // update uses of LDBase's output chain to use the TokenFactor.
5083     if (LDBase->hasAnyUseOfValue(1)) {
5084       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5085                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5086       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5087       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5088                              SDValue(ResNode.getNode(), 1));
5089     }
5090
5091     return DAG.getBitcast(VT, ResNode);
5092   }
5093   return SDValue();
5094 }
5095
5096 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5097 /// to generate a splat value for the following cases:
5098 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5099 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5100 /// a scalar load, or a constant.
5101 /// The VBROADCAST node is returned when a pattern is found,
5102 /// or SDValue() otherwise.
5103 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5104                                     SelectionDAG &DAG) {
5105   // VBROADCAST requires AVX.
5106   // TODO: Splats could be generated for non-AVX CPUs using SSE
5107   // instructions, but there's less potential gain for only 128-bit vectors.
5108   if (!Subtarget->hasAVX())
5109     return SDValue();
5110
5111   MVT VT = Op.getSimpleValueType();
5112   SDLoc dl(Op);
5113
5114   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5115          "Unsupported vector type for broadcast.");
5116
5117   SDValue Ld;
5118   bool ConstSplatVal;
5119
5120   switch (Op.getOpcode()) {
5121     default:
5122       // Unknown pattern found.
5123       return SDValue();
5124
5125     case ISD::BUILD_VECTOR: {
5126       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5127       BitVector UndefElements;
5128       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5129
5130       // We need a splat of a single value to use broadcast, and it doesn't
5131       // make any sense if the value is only in one element of the vector.
5132       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5133         return SDValue();
5134
5135       Ld = Splat;
5136       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5137                        Ld.getOpcode() == ISD::ConstantFP);
5138
5139       // Make sure that all of the users of a non-constant load are from the
5140       // BUILD_VECTOR node.
5141       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5142         return SDValue();
5143       break;
5144     }
5145
5146     case ISD::VECTOR_SHUFFLE: {
5147       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5148
5149       // Shuffles must have a splat mask where the first element is
5150       // broadcasted.
5151       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5152         return SDValue();
5153
5154       SDValue Sc = Op.getOperand(0);
5155       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5156           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5157
5158         if (!Subtarget->hasInt256())
5159           return SDValue();
5160
5161         // Use the register form of the broadcast instruction available on AVX2.
5162         if (VT.getSizeInBits() >= 256)
5163           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5164         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5165       }
5166
5167       Ld = Sc.getOperand(0);
5168       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5169                        Ld.getOpcode() == ISD::ConstantFP);
5170
5171       // The scalar_to_vector node and the suspected
5172       // load node must have exactly one user.
5173       // Constants may have multiple users.
5174
5175       // AVX-512 has register version of the broadcast
5176       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5177         Ld.getValueType().getSizeInBits() >= 32;
5178       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5179           !hasRegVer))
5180         return SDValue();
5181       break;
5182     }
5183   }
5184
5185   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5186   bool IsGE256 = (VT.getSizeInBits() >= 256);
5187
5188   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5189   // instruction to save 8 or more bytes of constant pool data.
5190   // TODO: If multiple splats are generated to load the same constant,
5191   // it may be detrimental to overall size. There needs to be a way to detect
5192   // that condition to know if this is truly a size win.
5193   const Function *F = DAG.getMachineFunction().getFunction();
5194   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5195
5196   // Handle broadcasting a single constant scalar from the constant pool
5197   // into a vector.
5198   // On Sandybridge (no AVX2), it is still better to load a constant vector
5199   // from the constant pool and not to broadcast it from a scalar.
5200   // But override that restriction when optimizing for size.
5201   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5202   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5203     EVT CVT = Ld.getValueType();
5204     assert(!CVT.isVector() && "Must not broadcast a vector type");
5205
5206     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5207     // For size optimization, also splat v2f64 and v2i64, and for size opt
5208     // with AVX2, also splat i8 and i16.
5209     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5210     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5211         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5212       const Constant *C = nullptr;
5213       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5214         C = CI->getConstantIntValue();
5215       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5216         C = CF->getConstantFPValue();
5217
5218       assert(C && "Invalid constant type");
5219
5220       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5221       SDValue CP =
5222           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5223       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5224       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5225                        MachinePointerInfo::getConstantPool(),
5226                        false, false, false, Alignment);
5227
5228       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5229     }
5230   }
5231
5232   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5233
5234   // Handle AVX2 in-register broadcasts.
5235   if (!IsLoad && Subtarget->hasInt256() &&
5236       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5237     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5238
5239   // The scalar source must be a normal load.
5240   if (!IsLoad)
5241     return SDValue();
5242
5243   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5244       (Subtarget->hasVLX() && ScalarSize == 64))
5245     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5246
5247   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5248   // double since there is no vbroadcastsd xmm
5249   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5250     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5251       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5252   }
5253
5254   // Unsupported broadcast.
5255   return SDValue();
5256 }
5257
5258 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5259 /// underlying vector and index.
5260 ///
5261 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5262 /// index.
5263 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5264                                          SDValue ExtIdx) {
5265   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5266   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5267     return Idx;
5268
5269   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5270   // lowered this:
5271   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5272   // to:
5273   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5274   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5275   //                           undef)
5276   //                       Constant<0>)
5277   // In this case the vector is the extract_subvector expression and the index
5278   // is 2, as specified by the shuffle.
5279   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5280   SDValue ShuffleVec = SVOp->getOperand(0);
5281   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5282   assert(ShuffleVecVT.getVectorElementType() ==
5283          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5284
5285   int ShuffleIdx = SVOp->getMaskElt(Idx);
5286   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5287     ExtractedFromVec = ShuffleVec;
5288     return ShuffleIdx;
5289   }
5290   return Idx;
5291 }
5292
5293 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5294   MVT VT = Op.getSimpleValueType();
5295
5296   // Skip if insert_vec_elt is not supported.
5297   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5298   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5299     return SDValue();
5300
5301   SDLoc DL(Op);
5302   unsigned NumElems = Op.getNumOperands();
5303
5304   SDValue VecIn1;
5305   SDValue VecIn2;
5306   SmallVector<unsigned, 4> InsertIndices;
5307   SmallVector<int, 8> Mask(NumElems, -1);
5308
5309   for (unsigned i = 0; i != NumElems; ++i) {
5310     unsigned Opc = Op.getOperand(i).getOpcode();
5311
5312     if (Opc == ISD::UNDEF)
5313       continue;
5314
5315     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5316       // Quit if more than 1 elements need inserting.
5317       if (InsertIndices.size() > 1)
5318         return SDValue();
5319
5320       InsertIndices.push_back(i);
5321       continue;
5322     }
5323
5324     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5325     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5326     // Quit if non-constant index.
5327     if (!isa<ConstantSDNode>(ExtIdx))
5328       return SDValue();
5329     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5330
5331     // Quit if extracted from vector of different type.
5332     if (ExtractedFromVec.getValueType() != VT)
5333       return SDValue();
5334
5335     if (!VecIn1.getNode())
5336       VecIn1 = ExtractedFromVec;
5337     else if (VecIn1 != ExtractedFromVec) {
5338       if (!VecIn2.getNode())
5339         VecIn2 = ExtractedFromVec;
5340       else if (VecIn2 != ExtractedFromVec)
5341         // Quit if more than 2 vectors to shuffle
5342         return SDValue();
5343     }
5344
5345     if (ExtractedFromVec == VecIn1)
5346       Mask[i] = Idx;
5347     else if (ExtractedFromVec == VecIn2)
5348       Mask[i] = Idx + NumElems;
5349   }
5350
5351   if (!VecIn1.getNode())
5352     return SDValue();
5353
5354   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5355   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5356   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5357     unsigned Idx = InsertIndices[i];
5358     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5359                      DAG.getIntPtrConstant(Idx, DL));
5360   }
5361
5362   return NV;
5363 }
5364
5365 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5366   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5367          Op.getScalarValueSizeInBits() == 1 &&
5368          "Can not convert non-constant vector");
5369   uint64_t Immediate = 0;
5370   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5371     SDValue In = Op.getOperand(idx);
5372     if (In.getOpcode() != ISD::UNDEF)
5373       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5374   }
5375   SDLoc dl(Op);
5376   MVT VT =
5377    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5378   return DAG.getConstant(Immediate, dl, VT);
5379 }
5380 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5381 SDValue
5382 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5383
5384   MVT VT = Op.getSimpleValueType();
5385   assert((VT.getVectorElementType() == MVT::i1) &&
5386          "Unexpected type in LowerBUILD_VECTORvXi1!");
5387
5388   SDLoc dl(Op);
5389   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5390     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5391     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5392     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5393   }
5394
5395   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5396     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5397     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5398     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5399   }
5400
5401   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5402     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5403     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5404       return DAG.getBitcast(VT, Imm);
5405     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5406     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5407                         DAG.getIntPtrConstant(0, dl));
5408   }
5409
5410   // Vector has one or more non-const elements
5411   uint64_t Immediate = 0;
5412   SmallVector<unsigned, 16> NonConstIdx;
5413   bool IsSplat = true;
5414   bool HasConstElts = false;
5415   int SplatIdx = -1;
5416   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5417     SDValue In = Op.getOperand(idx);
5418     if (In.getOpcode() == ISD::UNDEF)
5419       continue;
5420     if (!isa<ConstantSDNode>(In))
5421       NonConstIdx.push_back(idx);
5422     else {
5423       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5424       HasConstElts = true;
5425     }
5426     if (SplatIdx == -1)
5427       SplatIdx = idx;
5428     else if (In != Op.getOperand(SplatIdx))
5429       IsSplat = false;
5430   }
5431
5432   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5433   if (IsSplat)
5434     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5435                        DAG.getConstant(1, dl, VT),
5436                        DAG.getConstant(0, dl, VT));
5437
5438   // insert elements one by one
5439   SDValue DstVec;
5440   SDValue Imm;
5441   if (Immediate) {
5442     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5443     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5444   }
5445   else if (HasConstElts)
5446     Imm = DAG.getConstant(0, dl, VT);
5447   else
5448     Imm = DAG.getUNDEF(VT);
5449   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5450     DstVec = DAG.getBitcast(VT, Imm);
5451   else {
5452     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5453     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5454                          DAG.getIntPtrConstant(0, dl));
5455   }
5456
5457   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5458     unsigned InsertIdx = NonConstIdx[i];
5459     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5460                          Op.getOperand(InsertIdx),
5461                          DAG.getIntPtrConstant(InsertIdx, dl));
5462   }
5463   return DstVec;
5464 }
5465
5466 /// \brief Return true if \p N implements a horizontal binop and return the
5467 /// operands for the horizontal binop into V0 and V1.
5468 ///
5469 /// This is a helper function of LowerToHorizontalOp().
5470 /// This function checks that the build_vector \p N in input implements a
5471 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5472 /// operation to match.
5473 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5474 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5475 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5476 /// arithmetic sub.
5477 ///
5478 /// This function only analyzes elements of \p N whose indices are
5479 /// in range [BaseIdx, LastIdx).
5480 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5481                               SelectionDAG &DAG,
5482                               unsigned BaseIdx, unsigned LastIdx,
5483                               SDValue &V0, SDValue &V1) {
5484   EVT VT = N->getValueType(0);
5485
5486   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5487   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5488          "Invalid Vector in input!");
5489
5490   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5491   bool CanFold = true;
5492   unsigned ExpectedVExtractIdx = BaseIdx;
5493   unsigned NumElts = LastIdx - BaseIdx;
5494   V0 = DAG.getUNDEF(VT);
5495   V1 = DAG.getUNDEF(VT);
5496
5497   // Check if N implements a horizontal binop.
5498   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5499     SDValue Op = N->getOperand(i + BaseIdx);
5500
5501     // Skip UNDEFs.
5502     if (Op->getOpcode() == ISD::UNDEF) {
5503       // Update the expected vector extract index.
5504       if (i * 2 == NumElts)
5505         ExpectedVExtractIdx = BaseIdx;
5506       ExpectedVExtractIdx += 2;
5507       continue;
5508     }
5509
5510     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5511
5512     if (!CanFold)
5513       break;
5514
5515     SDValue Op0 = Op.getOperand(0);
5516     SDValue Op1 = Op.getOperand(1);
5517
5518     // Try to match the following pattern:
5519     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5520     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5521         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5522         Op0.getOperand(0) == Op1.getOperand(0) &&
5523         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5524         isa<ConstantSDNode>(Op1.getOperand(1)));
5525     if (!CanFold)
5526       break;
5527
5528     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5529     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5530
5531     if (i * 2 < NumElts) {
5532       if (V0.getOpcode() == ISD::UNDEF) {
5533         V0 = Op0.getOperand(0);
5534         if (V0.getValueType() != VT)
5535           return false;
5536       }
5537     } else {
5538       if (V1.getOpcode() == ISD::UNDEF) {
5539         V1 = Op0.getOperand(0);
5540         if (V1.getValueType() != VT)
5541           return false;
5542       }
5543       if (i * 2 == NumElts)
5544         ExpectedVExtractIdx = BaseIdx;
5545     }
5546
5547     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5548     if (I0 == ExpectedVExtractIdx)
5549       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5550     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5551       // Try to match the following dag sequence:
5552       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5553       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5554     } else
5555       CanFold = false;
5556
5557     ExpectedVExtractIdx += 2;
5558   }
5559
5560   return CanFold;
5561 }
5562
5563 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5564 /// a concat_vector.
5565 ///
5566 /// This is a helper function of LowerToHorizontalOp().
5567 /// This function expects two 256-bit vectors called V0 and V1.
5568 /// At first, each vector is split into two separate 128-bit vectors.
5569 /// Then, the resulting 128-bit vectors are used to implement two
5570 /// horizontal binary operations.
5571 ///
5572 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5573 ///
5574 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5575 /// the two new horizontal binop.
5576 /// When Mode is set, the first horizontal binop dag node would take as input
5577 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5578 /// horizontal binop dag node would take as input the lower 128-bit of V1
5579 /// and the upper 128-bit of V1.
5580 ///   Example:
5581 ///     HADD V0_LO, V0_HI
5582 ///     HADD V1_LO, V1_HI
5583 ///
5584 /// Otherwise, the first horizontal binop dag node takes as input the lower
5585 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5586 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5587 ///   Example:
5588 ///     HADD V0_LO, V1_LO
5589 ///     HADD V0_HI, V1_HI
5590 ///
5591 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5592 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5593 /// the upper 128-bits of the result.
5594 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5595                                      SDLoc DL, SelectionDAG &DAG,
5596                                      unsigned X86Opcode, bool Mode,
5597                                      bool isUndefLO, bool isUndefHI) {
5598   EVT VT = V0.getValueType();
5599   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5600          "Invalid nodes in input!");
5601
5602   unsigned NumElts = VT.getVectorNumElements();
5603   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5604   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5605   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5606   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5607   EVT NewVT = V0_LO.getValueType();
5608
5609   SDValue LO = DAG.getUNDEF(NewVT);
5610   SDValue HI = DAG.getUNDEF(NewVT);
5611
5612   if (Mode) {
5613     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5614     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5615       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5616     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5617       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5618   } else {
5619     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5620     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5621                        V1_LO->getOpcode() != ISD::UNDEF))
5622       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5623
5624     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5625                        V1_HI->getOpcode() != ISD::UNDEF))
5626       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5627   }
5628
5629   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5630 }
5631
5632 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5633 /// node.
5634 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5635                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5636   EVT VT = BV->getValueType(0);
5637   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5638       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5639     return SDValue();
5640
5641   SDLoc DL(BV);
5642   unsigned NumElts = VT.getVectorNumElements();
5643   SDValue InVec0 = DAG.getUNDEF(VT);
5644   SDValue InVec1 = DAG.getUNDEF(VT);
5645
5646   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5647           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5648
5649   // Odd-numbered elements in the input build vector are obtained from
5650   // adding two integer/float elements.
5651   // Even-numbered elements in the input build vector are obtained from
5652   // subtracting two integer/float elements.
5653   unsigned ExpectedOpcode = ISD::FSUB;
5654   unsigned NextExpectedOpcode = ISD::FADD;
5655   bool AddFound = false;
5656   bool SubFound = false;
5657
5658   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5659     SDValue Op = BV->getOperand(i);
5660
5661     // Skip 'undef' values.
5662     unsigned Opcode = Op.getOpcode();
5663     if (Opcode == ISD::UNDEF) {
5664       std::swap(ExpectedOpcode, NextExpectedOpcode);
5665       continue;
5666     }
5667
5668     // Early exit if we found an unexpected opcode.
5669     if (Opcode != ExpectedOpcode)
5670       return SDValue();
5671
5672     SDValue Op0 = Op.getOperand(0);
5673     SDValue Op1 = Op.getOperand(1);
5674
5675     // Try to match the following pattern:
5676     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5677     // Early exit if we cannot match that sequence.
5678     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5679         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5680         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5681         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5682         Op0.getOperand(1) != Op1.getOperand(1))
5683       return SDValue();
5684
5685     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5686     if (I0 != i)
5687       return SDValue();
5688
5689     // We found a valid add/sub node. Update the information accordingly.
5690     if (i & 1)
5691       AddFound = true;
5692     else
5693       SubFound = true;
5694
5695     // Update InVec0 and InVec1.
5696     if (InVec0.getOpcode() == ISD::UNDEF) {
5697       InVec0 = Op0.getOperand(0);
5698       if (InVec0.getValueType() != VT)
5699         return SDValue();
5700     }
5701     if (InVec1.getOpcode() == ISD::UNDEF) {
5702       InVec1 = Op1.getOperand(0);
5703       if (InVec1.getValueType() != VT)
5704         return SDValue();
5705     }
5706
5707     // Make sure that operands in input to each add/sub node always
5708     // come from a same pair of vectors.
5709     if (InVec0 != Op0.getOperand(0)) {
5710       if (ExpectedOpcode == ISD::FSUB)
5711         return SDValue();
5712
5713       // FADD is commutable. Try to commute the operands
5714       // and then test again.
5715       std::swap(Op0, Op1);
5716       if (InVec0 != Op0.getOperand(0))
5717         return SDValue();
5718     }
5719
5720     if (InVec1 != Op1.getOperand(0))
5721       return SDValue();
5722
5723     // Update the pair of expected opcodes.
5724     std::swap(ExpectedOpcode, NextExpectedOpcode);
5725   }
5726
5727   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5728   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5729       InVec1.getOpcode() != ISD::UNDEF)
5730     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5731
5732   return SDValue();
5733 }
5734
5735 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5736 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5737                                    const X86Subtarget *Subtarget,
5738                                    SelectionDAG &DAG) {
5739   EVT VT = BV->getValueType(0);
5740   unsigned NumElts = VT.getVectorNumElements();
5741   unsigned NumUndefsLO = 0;
5742   unsigned NumUndefsHI = 0;
5743   unsigned Half = NumElts/2;
5744
5745   // Count the number of UNDEF operands in the build_vector in input.
5746   for (unsigned i = 0, e = Half; i != e; ++i)
5747     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5748       NumUndefsLO++;
5749
5750   for (unsigned i = Half, e = NumElts; i != e; ++i)
5751     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5752       NumUndefsHI++;
5753
5754   // Early exit if this is either a build_vector of all UNDEFs or all the
5755   // operands but one are UNDEF.
5756   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5757     return SDValue();
5758
5759   SDLoc DL(BV);
5760   SDValue InVec0, InVec1;
5761   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5762     // Try to match an SSE3 float HADD/HSUB.
5763     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5764       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5765
5766     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5767       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5768   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5769     // Try to match an SSSE3 integer HADD/HSUB.
5770     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5771       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5772
5773     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5774       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5775   }
5776
5777   if (!Subtarget->hasAVX())
5778     return SDValue();
5779
5780   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5781     // Try to match an AVX horizontal add/sub of packed single/double
5782     // precision floating point values from 256-bit vectors.
5783     SDValue InVec2, InVec3;
5784     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5785         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5786         ((InVec0.getOpcode() == ISD::UNDEF ||
5787           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5788         ((InVec1.getOpcode() == ISD::UNDEF ||
5789           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5790       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5791
5792     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5793         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5794         ((InVec0.getOpcode() == ISD::UNDEF ||
5795           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5796         ((InVec1.getOpcode() == ISD::UNDEF ||
5797           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5798       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5799   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5800     // Try to match an AVX2 horizontal add/sub of signed integers.
5801     SDValue InVec2, InVec3;
5802     unsigned X86Opcode;
5803     bool CanFold = true;
5804
5805     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5806         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5807         ((InVec0.getOpcode() == ISD::UNDEF ||
5808           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5809         ((InVec1.getOpcode() == ISD::UNDEF ||
5810           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5811       X86Opcode = X86ISD::HADD;
5812     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5813         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5814         ((InVec0.getOpcode() == ISD::UNDEF ||
5815           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5816         ((InVec1.getOpcode() == ISD::UNDEF ||
5817           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5818       X86Opcode = X86ISD::HSUB;
5819     else
5820       CanFold = false;
5821
5822     if (CanFold) {
5823       // Fold this build_vector into a single horizontal add/sub.
5824       // Do this only if the target has AVX2.
5825       if (Subtarget->hasAVX2())
5826         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5827
5828       // Do not try to expand this build_vector into a pair of horizontal
5829       // add/sub if we can emit a pair of scalar add/sub.
5830       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5831         return SDValue();
5832
5833       // Convert this build_vector into a pair of horizontal binop followed by
5834       // a concat vector.
5835       bool isUndefLO = NumUndefsLO == Half;
5836       bool isUndefHI = NumUndefsHI == Half;
5837       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5838                                    isUndefLO, isUndefHI);
5839     }
5840   }
5841
5842   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5843        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5844     unsigned X86Opcode;
5845     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5846       X86Opcode = X86ISD::HADD;
5847     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5848       X86Opcode = X86ISD::HSUB;
5849     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5850       X86Opcode = X86ISD::FHADD;
5851     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5852       X86Opcode = X86ISD::FHSUB;
5853     else
5854       return SDValue();
5855
5856     // Don't try to expand this build_vector into a pair of horizontal add/sub
5857     // if we can simply emit a pair of scalar add/sub.
5858     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5859       return SDValue();
5860
5861     // Convert this build_vector into two horizontal add/sub followed by
5862     // a concat vector.
5863     bool isUndefLO = NumUndefsLO == Half;
5864     bool isUndefHI = NumUndefsHI == Half;
5865     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5866                                  isUndefLO, isUndefHI);
5867   }
5868
5869   return SDValue();
5870 }
5871
5872 SDValue
5873 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5874   SDLoc dl(Op);
5875
5876   MVT VT = Op.getSimpleValueType();
5877   MVT ExtVT = VT.getVectorElementType();
5878   unsigned NumElems = Op.getNumOperands();
5879
5880   // Generate vectors for predicate vectors.
5881   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5882     return LowerBUILD_VECTORvXi1(Op, DAG);
5883
5884   // Vectors containing all zeros can be matched by pxor and xorps later
5885   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5886     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5887     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5888     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5889       return Op;
5890
5891     return getZeroVector(VT, Subtarget, DAG, dl);
5892   }
5893
5894   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5895   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5896   // vpcmpeqd on 256-bit vectors.
5897   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5898     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5899       return Op;
5900
5901     if (!VT.is512BitVector())
5902       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5903   }
5904
5905   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5906   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5907     return AddSub;
5908   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5909     return HorizontalOp;
5910   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5911     return Broadcast;
5912
5913   unsigned EVTBits = ExtVT.getSizeInBits();
5914
5915   unsigned NumZero  = 0;
5916   unsigned NumNonZero = 0;
5917   unsigned NonZeros = 0;
5918   bool IsAllConstants = true;
5919   SmallSet<SDValue, 8> Values;
5920   for (unsigned i = 0; i < NumElems; ++i) {
5921     SDValue Elt = Op.getOperand(i);
5922     if (Elt.getOpcode() == ISD::UNDEF)
5923       continue;
5924     Values.insert(Elt);
5925     if (Elt.getOpcode() != ISD::Constant &&
5926         Elt.getOpcode() != ISD::ConstantFP)
5927       IsAllConstants = false;
5928     if (X86::isZeroNode(Elt))
5929       NumZero++;
5930     else {
5931       NonZeros |= (1 << i);
5932       NumNonZero++;
5933     }
5934   }
5935
5936   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5937   if (NumNonZero == 0)
5938     return DAG.getUNDEF(VT);
5939
5940   // Special case for single non-zero, non-undef, element.
5941   if (NumNonZero == 1) {
5942     unsigned Idx = countTrailingZeros(NonZeros);
5943     SDValue Item = Op.getOperand(Idx);
5944
5945     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5946     // the value are obviously zero, truncate the value to i32 and do the
5947     // insertion that way.  Only do this if the value is non-constant or if the
5948     // value is a constant being inserted into element 0.  It is cheaper to do
5949     // a constant pool load than it is to do a movd + shuffle.
5950     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5951         (!IsAllConstants || Idx == 0)) {
5952       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5953         // Handle SSE only.
5954         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5955         EVT VecVT = MVT::v4i32;
5956
5957         // Truncate the value (which may itself be a constant) to i32, and
5958         // convert it to a vector with movd (S2V+shuffle to zero extend).
5959         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5960         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5961         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5962                                       Item, Idx * 2, true, Subtarget, DAG));
5963       }
5964     }
5965
5966     // If we have a constant or non-constant insertion into the low element of
5967     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5968     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5969     // depending on what the source datatype is.
5970     if (Idx == 0) {
5971       if (NumZero == 0)
5972         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5973
5974       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5975           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5976         if (VT.is512BitVector()) {
5977           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5978           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5979                              Item, DAG.getIntPtrConstant(0, dl));
5980         }
5981         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5982                "Expected an SSE value type!");
5983         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5984         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5985         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5986       }
5987
5988       // We can't directly insert an i8 or i16 into a vector, so zero extend
5989       // it to i32 first.
5990       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5991         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5992         if (VT.is256BitVector()) {
5993           if (Subtarget->hasAVX()) {
5994             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5995             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5996           } else {
5997             // Without AVX, we need to extend to a 128-bit vector and then
5998             // insert into the 256-bit vector.
5999             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6000             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6001             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6002           }
6003         } else {
6004           assert(VT.is128BitVector() && "Expected an SSE value type!");
6005           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6006           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6007         }
6008         return DAG.getBitcast(VT, Item);
6009       }
6010     }
6011
6012     // Is it a vector logical left shift?
6013     if (NumElems == 2 && Idx == 1 &&
6014         X86::isZeroNode(Op.getOperand(0)) &&
6015         !X86::isZeroNode(Op.getOperand(1))) {
6016       unsigned NumBits = VT.getSizeInBits();
6017       return getVShift(true, VT,
6018                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6019                                    VT, Op.getOperand(1)),
6020                        NumBits/2, DAG, *this, dl);
6021     }
6022
6023     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6024       return SDValue();
6025
6026     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6027     // is a non-constant being inserted into an element other than the low one,
6028     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6029     // movd/movss) to move this into the low element, then shuffle it into
6030     // place.
6031     if (EVTBits == 32) {
6032       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6033       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6034     }
6035   }
6036
6037   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6038   if (Values.size() == 1) {
6039     if (EVTBits == 32) {
6040       // Instead of a shuffle like this:
6041       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6042       // Check if it's possible to issue this instead.
6043       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6044       unsigned Idx = countTrailingZeros(NonZeros);
6045       SDValue Item = Op.getOperand(Idx);
6046       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6047         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6048     }
6049     return SDValue();
6050   }
6051
6052   // A vector full of immediates; various special cases are already
6053   // handled, so this is best done with a single constant-pool load.
6054   if (IsAllConstants)
6055     return SDValue();
6056
6057   // For AVX-length vectors, see if we can use a vector load to get all of the
6058   // elements, otherwise build the individual 128-bit pieces and use
6059   // shuffles to put them in place.
6060   if (VT.is256BitVector() || VT.is512BitVector()) {
6061     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6062
6063     // Check for a build vector of consecutive loads.
6064     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6065       return LD;
6066
6067     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6068
6069     // Build both the lower and upper subvector.
6070     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6071                                 makeArrayRef(&V[0], NumElems/2));
6072     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6073                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6074
6075     // Recreate the wider vector with the lower and upper part.
6076     if (VT.is256BitVector())
6077       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6078     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6079   }
6080
6081   // Let legalizer expand 2-wide build_vectors.
6082   if (EVTBits == 64) {
6083     if (NumNonZero == 1) {
6084       // One half is zero or undef.
6085       unsigned Idx = countTrailingZeros(NonZeros);
6086       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6087                                  Op.getOperand(Idx));
6088       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6089     }
6090     return SDValue();
6091   }
6092
6093   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6094   if (EVTBits == 8 && NumElems == 16)
6095     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6096                                         Subtarget, *this))
6097       return V;
6098
6099   if (EVTBits == 16 && NumElems == 8)
6100     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6101                                       Subtarget, *this))
6102       return V;
6103
6104   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6105   if (EVTBits == 32 && NumElems == 4)
6106     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6107       return V;
6108
6109   // If element VT is == 32 bits, turn it into a number of shuffles.
6110   SmallVector<SDValue, 8> V(NumElems);
6111   if (NumElems == 4 && NumZero > 0) {
6112     for (unsigned i = 0; i < 4; ++i) {
6113       bool isZero = !(NonZeros & (1 << i));
6114       if (isZero)
6115         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6116       else
6117         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6118     }
6119
6120     for (unsigned i = 0; i < 2; ++i) {
6121       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6122         default: break;
6123         case 0:
6124           V[i] = V[i*2];  // Must be a zero vector.
6125           break;
6126         case 1:
6127           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6128           break;
6129         case 2:
6130           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6131           break;
6132         case 3:
6133           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6134           break;
6135       }
6136     }
6137
6138     bool Reverse1 = (NonZeros & 0x3) == 2;
6139     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6140     int MaskVec[] = {
6141       Reverse1 ? 1 : 0,
6142       Reverse1 ? 0 : 1,
6143       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6144       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6145     };
6146     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6147   }
6148
6149   if (Values.size() > 1 && VT.is128BitVector()) {
6150     // Check for a build vector of consecutive loads.
6151     for (unsigned i = 0; i < NumElems; ++i)
6152       V[i] = Op.getOperand(i);
6153
6154     // Check for elements which are consecutive loads.
6155     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6156       return LD;
6157
6158     // Check for a build vector from mostly shuffle plus few inserting.
6159     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6160       return Sh;
6161
6162     // For SSE 4.1, use insertps to put the high elements into the low element.
6163     if (Subtarget->hasSSE41()) {
6164       SDValue Result;
6165       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6166         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6167       else
6168         Result = DAG.getUNDEF(VT);
6169
6170       for (unsigned i = 1; i < NumElems; ++i) {
6171         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6172         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6173                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6174       }
6175       return Result;
6176     }
6177
6178     // Otherwise, expand into a number of unpckl*, start by extending each of
6179     // our (non-undef) elements to the full vector width with the element in the
6180     // bottom slot of the vector (which generates no code for SSE).
6181     for (unsigned i = 0; i < NumElems; ++i) {
6182       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6183         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6184       else
6185         V[i] = DAG.getUNDEF(VT);
6186     }
6187
6188     // Next, we iteratively mix elements, e.g. for v4f32:
6189     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6190     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6191     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6192     unsigned EltStride = NumElems >> 1;
6193     while (EltStride != 0) {
6194       for (unsigned i = 0; i < EltStride; ++i) {
6195         // If V[i+EltStride] is undef and this is the first round of mixing,
6196         // then it is safe to just drop this shuffle: V[i] is already in the
6197         // right place, the one element (since it's the first round) being
6198         // inserted as undef can be dropped.  This isn't safe for successive
6199         // rounds because they will permute elements within both vectors.
6200         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6201             EltStride == NumElems/2)
6202           continue;
6203
6204         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6205       }
6206       EltStride >>= 1;
6207     }
6208     return V[0];
6209   }
6210   return SDValue();
6211 }
6212
6213 // 256-bit AVX can use the vinsertf128 instruction
6214 // to create 256-bit vectors from two other 128-bit ones.
6215 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6216   SDLoc dl(Op);
6217   MVT ResVT = Op.getSimpleValueType();
6218
6219   assert((ResVT.is256BitVector() ||
6220           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6221
6222   SDValue V1 = Op.getOperand(0);
6223   SDValue V2 = Op.getOperand(1);
6224   unsigned NumElems = ResVT.getVectorNumElements();
6225   if (ResVT.is256BitVector())
6226     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6227
6228   if (Op.getNumOperands() == 4) {
6229     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6230                                 ResVT.getVectorNumElements()/2);
6231     SDValue V3 = Op.getOperand(2);
6232     SDValue V4 = Op.getOperand(3);
6233     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6234       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6235   }
6236   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6237 }
6238
6239 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6240                                        const X86Subtarget *Subtarget,
6241                                        SelectionDAG & DAG) {
6242   SDLoc dl(Op);
6243   MVT ResVT = Op.getSimpleValueType();
6244   unsigned NumOfOperands = Op.getNumOperands();
6245
6246   assert(isPowerOf2_32(NumOfOperands) &&
6247          "Unexpected number of operands in CONCAT_VECTORS");
6248
6249   if (NumOfOperands > 2) {
6250     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6251                                   ResVT.getVectorNumElements()/2);
6252     SmallVector<SDValue, 2> Ops;
6253     for (unsigned i = 0; i < NumOfOperands/2; i++)
6254       Ops.push_back(Op.getOperand(i));
6255     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6256     Ops.clear();
6257     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6258       Ops.push_back(Op.getOperand(i));
6259     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6260     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6261   }
6262
6263   SDValue V1 = Op.getOperand(0);
6264   SDValue V2 = Op.getOperand(1);
6265   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6266   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6267
6268   if (IsZeroV1 && IsZeroV2)
6269     return getZeroVector(ResVT, Subtarget, DAG, dl);
6270
6271   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6272   SDValue Undef = DAG.getUNDEF(ResVT);
6273   unsigned NumElems = ResVT.getVectorNumElements();
6274   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6275
6276   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6277   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6278   if (IsZeroV1)
6279     return V2;
6280
6281   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6282   // Zero the upper bits of V1
6283   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6284   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6285   if (IsZeroV2)
6286     return V1;
6287   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6288 }
6289
6290 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6291                                    const X86Subtarget *Subtarget,
6292                                    SelectionDAG &DAG) {
6293   MVT VT = Op.getSimpleValueType();
6294   if (VT.getVectorElementType() == MVT::i1)
6295     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6296
6297   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6298          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6299           Op.getNumOperands() == 4)));
6300
6301   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6302   // from two other 128-bit ones.
6303
6304   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6305   return LowerAVXCONCAT_VECTORS(Op, DAG);
6306 }
6307
6308
6309 //===----------------------------------------------------------------------===//
6310 // Vector shuffle lowering
6311 //
6312 // This is an experimental code path for lowering vector shuffles on x86. It is
6313 // designed to handle arbitrary vector shuffles and blends, gracefully
6314 // degrading performance as necessary. It works hard to recognize idiomatic
6315 // shuffles and lower them to optimal instruction patterns without leaving
6316 // a framework that allows reasonably efficient handling of all vector shuffle
6317 // patterns.
6318 //===----------------------------------------------------------------------===//
6319
6320 /// \brief Tiny helper function to identify a no-op mask.
6321 ///
6322 /// This is a somewhat boring predicate function. It checks whether the mask
6323 /// array input, which is assumed to be a single-input shuffle mask of the kind
6324 /// used by the X86 shuffle instructions (not a fully general
6325 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6326 /// in-place shuffle are 'no-op's.
6327 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6328   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6329     if (Mask[i] != -1 && Mask[i] != i)
6330       return false;
6331   return true;
6332 }
6333
6334 /// \brief Helper function to classify a mask as a single-input mask.
6335 ///
6336 /// This isn't a generic single-input test because in the vector shuffle
6337 /// lowering we canonicalize single inputs to be the first input operand. This
6338 /// means we can more quickly test for a single input by only checking whether
6339 /// an input from the second operand exists. We also assume that the size of
6340 /// mask corresponds to the size of the input vectors which isn't true in the
6341 /// fully general case.
6342 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6343   for (int M : Mask)
6344     if (M >= (int)Mask.size())
6345       return false;
6346   return true;
6347 }
6348
6349 /// \brief Test whether there are elements crossing 128-bit lanes in this
6350 /// shuffle mask.
6351 ///
6352 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6353 /// and we routinely test for these.
6354 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6355   int LaneSize = 128 / VT.getScalarSizeInBits();
6356   int Size = Mask.size();
6357   for (int i = 0; i < Size; ++i)
6358     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6359       return true;
6360   return false;
6361 }
6362
6363 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6364 ///
6365 /// This checks a shuffle mask to see if it is performing the same
6366 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6367 /// that it is also not lane-crossing. It may however involve a blend from the
6368 /// same lane of a second vector.
6369 ///
6370 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6371 /// non-trivial to compute in the face of undef lanes. The representation is
6372 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6373 /// entries from both V1 and V2 inputs to the wider mask.
6374 static bool
6375 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6376                                 SmallVectorImpl<int> &RepeatedMask) {
6377   int LaneSize = 128 / VT.getScalarSizeInBits();
6378   RepeatedMask.resize(LaneSize, -1);
6379   int Size = Mask.size();
6380   for (int i = 0; i < Size; ++i) {
6381     if (Mask[i] < 0)
6382       continue;
6383     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6384       // This entry crosses lanes, so there is no way to model this shuffle.
6385       return false;
6386
6387     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6388     if (RepeatedMask[i % LaneSize] == -1)
6389       // This is the first non-undef entry in this slot of a 128-bit lane.
6390       RepeatedMask[i % LaneSize] =
6391           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6392     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6393       // Found a mismatch with the repeated mask.
6394       return false;
6395   }
6396   return true;
6397 }
6398
6399 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6400 /// arguments.
6401 ///
6402 /// This is a fast way to test a shuffle mask against a fixed pattern:
6403 ///
6404 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6405 ///
6406 /// It returns true if the mask is exactly as wide as the argument list, and
6407 /// each element of the mask is either -1 (signifying undef) or the value given
6408 /// in the argument.
6409 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6410                                 ArrayRef<int> ExpectedMask) {
6411   if (Mask.size() != ExpectedMask.size())
6412     return false;
6413
6414   int Size = Mask.size();
6415
6416   // If the values are build vectors, we can look through them to find
6417   // equivalent inputs that make the shuffles equivalent.
6418   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6419   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6420
6421   for (int i = 0; i < Size; ++i)
6422     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6423       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6424       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6425       if (!MaskBV || !ExpectedBV ||
6426           MaskBV->getOperand(Mask[i] % Size) !=
6427               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6428         return false;
6429     }
6430
6431   return true;
6432 }
6433
6434 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6435 ///
6436 /// This helper function produces an 8-bit shuffle immediate corresponding to
6437 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6438 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6439 /// example.
6440 ///
6441 /// NB: We rely heavily on "undef" masks preserving the input lane.
6442 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6443                                           SelectionDAG &DAG) {
6444   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6445   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6446   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6447   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6448   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6449
6450   unsigned Imm = 0;
6451   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6452   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6453   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6454   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6455   return DAG.getConstant(Imm, DL, MVT::i8);
6456 }
6457
6458 /// \brief Compute whether each element of a shuffle is zeroable.
6459 ///
6460 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6461 /// Either it is an undef element in the shuffle mask, the element of the input
6462 /// referenced is undef, or the element of the input referenced is known to be
6463 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6464 /// as many lanes with this technique as possible to simplify the remaining
6465 /// shuffle.
6466 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6467                                                      SDValue V1, SDValue V2) {
6468   SmallBitVector Zeroable(Mask.size(), false);
6469
6470   while (V1.getOpcode() == ISD::BITCAST)
6471     V1 = V1->getOperand(0);
6472   while (V2.getOpcode() == ISD::BITCAST)
6473     V2 = V2->getOperand(0);
6474
6475   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6476   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6477
6478   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6479     int M = Mask[i];
6480     // Handle the easy cases.
6481     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6482       Zeroable[i] = true;
6483       continue;
6484     }
6485
6486     // If this is an index into a build_vector node (which has the same number
6487     // of elements), dig out the input value and use it.
6488     SDValue V = M < Size ? V1 : V2;
6489     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6490       continue;
6491
6492     SDValue Input = V.getOperand(M % Size);
6493     // The UNDEF opcode check really should be dead code here, but not quite
6494     // worth asserting on (it isn't invalid, just unexpected).
6495     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6496       Zeroable[i] = true;
6497   }
6498
6499   return Zeroable;
6500 }
6501
6502 /// \brief Try to emit a bitmask instruction for a shuffle.
6503 ///
6504 /// This handles cases where we can model a blend exactly as a bitmask due to
6505 /// one of the inputs being zeroable.
6506 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6507                                            SDValue V2, ArrayRef<int> Mask,
6508                                            SelectionDAG &DAG) {
6509   MVT EltVT = VT.getScalarType();
6510   int NumEltBits = EltVT.getSizeInBits();
6511   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6512   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6513   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6514                                     IntEltVT);
6515   if (EltVT.isFloatingPoint()) {
6516     Zero = DAG.getBitcast(EltVT, Zero);
6517     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6518   }
6519   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6520   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6521   SDValue V;
6522   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6523     if (Zeroable[i])
6524       continue;
6525     if (Mask[i] % Size != i)
6526       return SDValue(); // Not a blend.
6527     if (!V)
6528       V = Mask[i] < Size ? V1 : V2;
6529     else if (V != (Mask[i] < Size ? V1 : V2))
6530       return SDValue(); // Can only let one input through the mask.
6531
6532     VMaskOps[i] = AllOnes;
6533   }
6534   if (!V)
6535     return SDValue(); // No non-zeroable elements!
6536
6537   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6538   V = DAG.getNode(VT.isFloatingPoint()
6539                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6540                   DL, VT, V, VMask);
6541   return V;
6542 }
6543
6544 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6545 ///
6546 /// This is used as a fallback approach when first class blend instructions are
6547 /// unavailable. Currently it is only suitable for integer vectors, but could
6548 /// be generalized for floating point vectors if desirable.
6549 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6550                                             SDValue V2, ArrayRef<int> Mask,
6551                                             SelectionDAG &DAG) {
6552   assert(VT.isInteger() && "Only supports integer vector types!");
6553   MVT EltVT = VT.getScalarType();
6554   int NumEltBits = EltVT.getSizeInBits();
6555   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6556   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6557                                     EltVT);
6558   SmallVector<SDValue, 16> MaskOps;
6559   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6560     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6561       return SDValue(); // Shuffled input!
6562     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6563   }
6564
6565   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6566   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6567   // We have to cast V2 around.
6568   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6569   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6570                                       DAG.getBitcast(MaskVT, V1Mask),
6571                                       DAG.getBitcast(MaskVT, V2)));
6572   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6573 }
6574
6575 /// \brief Try to emit a blend instruction for a shuffle.
6576 ///
6577 /// This doesn't do any checks for the availability of instructions for blending
6578 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6579 /// be matched in the backend with the type given. What it does check for is
6580 /// that the shuffle mask is in fact a blend.
6581 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6582                                          SDValue V2, ArrayRef<int> Mask,
6583                                          const X86Subtarget *Subtarget,
6584                                          SelectionDAG &DAG) {
6585   unsigned BlendMask = 0;
6586   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6587     if (Mask[i] >= Size) {
6588       if (Mask[i] != i + Size)
6589         return SDValue(); // Shuffled V2 input!
6590       BlendMask |= 1u << i;
6591       continue;
6592     }
6593     if (Mask[i] >= 0 && Mask[i] != i)
6594       return SDValue(); // Shuffled V1 input!
6595   }
6596   switch (VT.SimpleTy) {
6597   case MVT::v2f64:
6598   case MVT::v4f32:
6599   case MVT::v4f64:
6600   case MVT::v8f32:
6601     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6602                        DAG.getConstant(BlendMask, DL, MVT::i8));
6603
6604   case MVT::v4i64:
6605   case MVT::v8i32:
6606     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6607     // FALLTHROUGH
6608   case MVT::v2i64:
6609   case MVT::v4i32:
6610     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6611     // that instruction.
6612     if (Subtarget->hasAVX2()) {
6613       // Scale the blend by the number of 32-bit dwords per element.
6614       int Scale =  VT.getScalarSizeInBits() / 32;
6615       BlendMask = 0;
6616       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6617         if (Mask[i] >= Size)
6618           for (int j = 0; j < Scale; ++j)
6619             BlendMask |= 1u << (i * Scale + j);
6620
6621       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6622       V1 = DAG.getBitcast(BlendVT, V1);
6623       V2 = DAG.getBitcast(BlendVT, V2);
6624       return DAG.getBitcast(
6625           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6626                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6627     }
6628     // FALLTHROUGH
6629   case MVT::v8i16: {
6630     // For integer shuffles we need to expand the mask and cast the inputs to
6631     // v8i16s prior to blending.
6632     int Scale = 8 / VT.getVectorNumElements();
6633     BlendMask = 0;
6634     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6635       if (Mask[i] >= Size)
6636         for (int j = 0; j < Scale; ++j)
6637           BlendMask |= 1u << (i * Scale + j);
6638
6639     V1 = DAG.getBitcast(MVT::v8i16, V1);
6640     V2 = DAG.getBitcast(MVT::v8i16, V2);
6641     return DAG.getBitcast(VT,
6642                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6643                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6644   }
6645
6646   case MVT::v16i16: {
6647     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6648     SmallVector<int, 8> RepeatedMask;
6649     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6650       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6651       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6652       BlendMask = 0;
6653       for (int i = 0; i < 8; ++i)
6654         if (RepeatedMask[i] >= 16)
6655           BlendMask |= 1u << i;
6656       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6657                          DAG.getConstant(BlendMask, DL, MVT::i8));
6658     }
6659   }
6660     // FALLTHROUGH
6661   case MVT::v16i8:
6662   case MVT::v32i8: {
6663     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6664            "256-bit byte-blends require AVX2 support!");
6665
6666     // Scale the blend by the number of bytes per element.
6667     int Scale = VT.getScalarSizeInBits() / 8;
6668
6669     // This form of blend is always done on bytes. Compute the byte vector
6670     // type.
6671     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6672
6673     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6674     // mix of LLVM's code generator and the x86 backend. We tell the code
6675     // generator that boolean values in the elements of an x86 vector register
6676     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6677     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6678     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6679     // of the element (the remaining are ignored) and 0 in that high bit would
6680     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6681     // the LLVM model for boolean values in vector elements gets the relevant
6682     // bit set, it is set backwards and over constrained relative to x86's
6683     // actual model.
6684     SmallVector<SDValue, 32> VSELECTMask;
6685     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6686       for (int j = 0; j < Scale; ++j)
6687         VSELECTMask.push_back(
6688             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6689                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6690                                           MVT::i8));
6691
6692     V1 = DAG.getBitcast(BlendVT, V1);
6693     V2 = DAG.getBitcast(BlendVT, V2);
6694     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6695                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6696                                                       BlendVT, VSELECTMask),
6697                                           V1, V2));
6698   }
6699
6700   default:
6701     llvm_unreachable("Not a supported integer vector type!");
6702   }
6703 }
6704
6705 /// \brief Try to lower as a blend of elements from two inputs followed by
6706 /// a single-input permutation.
6707 ///
6708 /// This matches the pattern where we can blend elements from two inputs and
6709 /// then reduce the shuffle to a single-input permutation.
6710 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6711                                                    SDValue V2,
6712                                                    ArrayRef<int> Mask,
6713                                                    SelectionDAG &DAG) {
6714   // We build up the blend mask while checking whether a blend is a viable way
6715   // to reduce the shuffle.
6716   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6717   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6718
6719   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6720     if (Mask[i] < 0)
6721       continue;
6722
6723     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6724
6725     if (BlendMask[Mask[i] % Size] == -1)
6726       BlendMask[Mask[i] % Size] = Mask[i];
6727     else if (BlendMask[Mask[i] % Size] != Mask[i])
6728       return SDValue(); // Can't blend in the needed input!
6729
6730     PermuteMask[i] = Mask[i] % Size;
6731   }
6732
6733   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6734   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6735 }
6736
6737 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6738 /// blends and permutes.
6739 ///
6740 /// This matches the extremely common pattern for handling combined
6741 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6742 /// operations. It will try to pick the best arrangement of shuffles and
6743 /// blends.
6744 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6745                                                           SDValue V1,
6746                                                           SDValue V2,
6747                                                           ArrayRef<int> Mask,
6748                                                           SelectionDAG &DAG) {
6749   // Shuffle the input elements into the desired positions in V1 and V2 and
6750   // blend them together.
6751   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6752   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6753   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6754   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6755     if (Mask[i] >= 0 && Mask[i] < Size) {
6756       V1Mask[i] = Mask[i];
6757       BlendMask[i] = i;
6758     } else if (Mask[i] >= Size) {
6759       V2Mask[i] = Mask[i] - Size;
6760       BlendMask[i] = i + Size;
6761     }
6762
6763   // Try to lower with the simpler initial blend strategy unless one of the
6764   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6765   // shuffle may be able to fold with a load or other benefit. However, when
6766   // we'll have to do 2x as many shuffles in order to achieve this, blending
6767   // first is a better strategy.
6768   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6769     if (SDValue BlendPerm =
6770             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6771       return BlendPerm;
6772
6773   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6774   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6775   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6776 }
6777
6778 /// \brief Try to lower a vector shuffle as a byte rotation.
6779 ///
6780 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6781 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6782 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6783 /// try to generically lower a vector shuffle through such an pattern. It
6784 /// does not check for the profitability of lowering either as PALIGNR or
6785 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6786 /// This matches shuffle vectors that look like:
6787 ///
6788 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6789 ///
6790 /// Essentially it concatenates V1 and V2, shifts right by some number of
6791 /// elements, and takes the low elements as the result. Note that while this is
6792 /// specified as a *right shift* because x86 is little-endian, it is a *left
6793 /// rotate* of the vector lanes.
6794 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6795                                               SDValue V2,
6796                                               ArrayRef<int> Mask,
6797                                               const X86Subtarget *Subtarget,
6798                                               SelectionDAG &DAG) {
6799   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6800
6801   int NumElts = Mask.size();
6802   int NumLanes = VT.getSizeInBits() / 128;
6803   int NumLaneElts = NumElts / NumLanes;
6804
6805   // We need to detect various ways of spelling a rotation:
6806   //   [11, 12, 13, 14, 15,  0,  1,  2]
6807   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6808   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6809   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6810   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6811   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6812   int Rotation = 0;
6813   SDValue Lo, Hi;
6814   for (int l = 0; l < NumElts; l += NumLaneElts) {
6815     for (int i = 0; i < NumLaneElts; ++i) {
6816       if (Mask[l + i] == -1)
6817         continue;
6818       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6819
6820       // Get the mod-Size index and lane correct it.
6821       int LaneIdx = (Mask[l + i] % NumElts) - l;
6822       // Make sure it was in this lane.
6823       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6824         return SDValue();
6825
6826       // Determine where a rotated vector would have started.
6827       int StartIdx = i - LaneIdx;
6828       if (StartIdx == 0)
6829         // The identity rotation isn't interesting, stop.
6830         return SDValue();
6831
6832       // If we found the tail of a vector the rotation must be the missing
6833       // front. If we found the head of a vector, it must be how much of the
6834       // head.
6835       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6836
6837       if (Rotation == 0)
6838         Rotation = CandidateRotation;
6839       else if (Rotation != CandidateRotation)
6840         // The rotations don't match, so we can't match this mask.
6841         return SDValue();
6842
6843       // Compute which value this mask is pointing at.
6844       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6845
6846       // Compute which of the two target values this index should be assigned
6847       // to. This reflects whether the high elements are remaining or the low
6848       // elements are remaining.
6849       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6850
6851       // Either set up this value if we've not encountered it before, or check
6852       // that it remains consistent.
6853       if (!TargetV)
6854         TargetV = MaskV;
6855       else if (TargetV != MaskV)
6856         // This may be a rotation, but it pulls from the inputs in some
6857         // unsupported interleaving.
6858         return SDValue();
6859     }
6860   }
6861
6862   // Check that we successfully analyzed the mask, and normalize the results.
6863   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6864   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6865   if (!Lo)
6866     Lo = Hi;
6867   else if (!Hi)
6868     Hi = Lo;
6869
6870   // The actual rotate instruction rotates bytes, so we need to scale the
6871   // rotation based on how many bytes are in the vector lane.
6872   int Scale = 16 / NumLaneElts;
6873
6874   // SSSE3 targets can use the palignr instruction.
6875   if (Subtarget->hasSSSE3()) {
6876     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6877     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6878     Lo = DAG.getBitcast(AlignVT, Lo);
6879     Hi = DAG.getBitcast(AlignVT, Hi);
6880
6881     return DAG.getBitcast(
6882         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6883                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6884   }
6885
6886   assert(VT.getSizeInBits() == 128 &&
6887          "Rotate-based lowering only supports 128-bit lowering!");
6888   assert(Mask.size() <= 16 &&
6889          "Can shuffle at most 16 bytes in a 128-bit vector!");
6890
6891   // Default SSE2 implementation
6892   int LoByteShift = 16 - Rotation * Scale;
6893   int HiByteShift = Rotation * Scale;
6894
6895   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6896   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6897   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6898
6899   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6900                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6901   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6902                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6903   return DAG.getBitcast(VT,
6904                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6905 }
6906
6907 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6908 ///
6909 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6910 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6911 /// matches elements from one of the input vectors shuffled to the left or
6912 /// right with zeroable elements 'shifted in'. It handles both the strictly
6913 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6914 /// quad word lane.
6915 ///
6916 /// PSHL : (little-endian) left bit shift.
6917 /// [ zz, 0, zz,  2 ]
6918 /// [ -1, 4, zz, -1 ]
6919 /// PSRL : (little-endian) right bit shift.
6920 /// [  1, zz,  3, zz]
6921 /// [ -1, -1,  7, zz]
6922 /// PSLLDQ : (little-endian) left byte shift
6923 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6924 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6925 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6926 /// PSRLDQ : (little-endian) right byte shift
6927 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6928 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6929 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6930 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6931                                          SDValue V2, ArrayRef<int> Mask,
6932                                          SelectionDAG &DAG) {
6933   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6934
6935   int Size = Mask.size();
6936   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6937
6938   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6939     for (int i = 0; i < Size; i += Scale)
6940       for (int j = 0; j < Shift; ++j)
6941         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6942           return false;
6943
6944     return true;
6945   };
6946
6947   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6948     for (int i = 0; i != Size; i += Scale) {
6949       unsigned Pos = Left ? i + Shift : i;
6950       unsigned Low = Left ? i : i + Shift;
6951       unsigned Len = Scale - Shift;
6952       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6953                                       Low + (V == V1 ? 0 : Size)))
6954         return SDValue();
6955     }
6956
6957     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6958     bool ByteShift = ShiftEltBits > 64;
6959     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6960                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6961     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6962
6963     // Normalize the scale for byte shifts to still produce an i64 element
6964     // type.
6965     Scale = ByteShift ? Scale / 2 : Scale;
6966
6967     // We need to round trip through the appropriate type for the shift.
6968     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6969     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6970     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6971            "Illegal integer vector type");
6972     V = DAG.getBitcast(ShiftVT, V);
6973
6974     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6975                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6976     return DAG.getBitcast(VT, V);
6977   };
6978
6979   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6980   // keep doubling the size of the integer elements up to that. We can
6981   // then shift the elements of the integer vector by whole multiples of
6982   // their width within the elements of the larger integer vector. Test each
6983   // multiple to see if we can find a match with the moved element indices
6984   // and that the shifted in elements are all zeroable.
6985   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6986     for (int Shift = 1; Shift != Scale; ++Shift)
6987       for (bool Left : {true, false})
6988         if (CheckZeros(Shift, Scale, Left))
6989           for (SDValue V : {V1, V2})
6990             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6991               return Match;
6992
6993   // no match
6994   return SDValue();
6995 }
6996
6997 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
6998 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
6999                                            SDValue V2, ArrayRef<int> Mask,
7000                                            SelectionDAG &DAG) {
7001   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7002   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7003
7004   int Size = Mask.size();
7005   int HalfSize = Size / 2;
7006   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7007
7008   // Upper half must be undefined.
7009   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7010     return SDValue();
7011
7012   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7013   // Remainder of lower half result is zero and upper half is all undef.
7014   auto LowerAsEXTRQ = [&]() {
7015     // Determine the extraction length from the part of the
7016     // lower half that isn't zeroable.
7017     int Len = HalfSize;
7018     for (; Len >= 0; --Len)
7019       if (!Zeroable[Len - 1])
7020         break;
7021     assert(Len > 0 && "Zeroable shuffle mask");
7022
7023     // Attempt to match first Len sequential elements from the lower half.
7024     SDValue Src;
7025     int Idx = -1;
7026     for (int i = 0; i != Len; ++i) {
7027       int M = Mask[i];
7028       if (M < 0)
7029         continue;
7030       SDValue &V = (M < Size ? V1 : V2);
7031       M = M % Size;
7032
7033       // All mask elements must be in the lower half.
7034       if (M > HalfSize)
7035         return SDValue();
7036
7037       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7038         Src = V;
7039         Idx = M - i;
7040         continue;
7041       }
7042       return SDValue();
7043     }
7044
7045     if (Idx < 0)
7046       return SDValue();
7047
7048     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7049     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7050     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7051     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7052                        DAG.getConstant(BitLen, DL, MVT::i8),
7053                        DAG.getConstant(BitIdx, DL, MVT::i8));
7054   };
7055
7056   if (SDValue ExtrQ = LowerAsEXTRQ())
7057     return ExtrQ;
7058
7059   // INSERTQ: Extract lowest Len elements from lower half of second source and
7060   // insert over first source, starting at Idx.
7061   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7062   auto LowerAsInsertQ = [&]() {
7063     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7064       SDValue Base;
7065
7066       // Attempt to match first source from mask before insertion point.
7067       if (isUndefInRange(Mask, 0, Idx)) {
7068         /* EMPTY */
7069       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7070         Base = V1;
7071       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7072         Base = V2;
7073       } else {
7074         continue;
7075       }
7076
7077       // Extend the extraction length looking to match both the insertion of
7078       // the second source and the remaining elements of the first.
7079       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7080         SDValue Insert;
7081         int Len = Hi - Idx;
7082
7083         // Match insertion.
7084         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7085           Insert = V1;
7086         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7087           Insert = V2;
7088         } else {
7089           continue;
7090         }
7091
7092         // Match the remaining elements of the lower half.
7093         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7094           /* EMPTY */
7095         } else if ((!Base || (Base == V1)) &&
7096                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7097           Base = V1;
7098         } else if ((!Base || (Base == V2)) &&
7099                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7100                                               Size + Hi)) {
7101           Base = V2;
7102         } else {
7103           continue;
7104         }
7105
7106         // We may not have a base (first source) - this can safely be undefined.
7107         if (!Base)
7108           Base = DAG.getUNDEF(VT);
7109
7110         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7111         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7112         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7113                            DAG.getConstant(BitLen, DL, MVT::i8),
7114                            DAG.getConstant(BitIdx, DL, MVT::i8));
7115       }
7116     }
7117
7118     return SDValue();
7119   };
7120
7121   if (SDValue InsertQ = LowerAsInsertQ())
7122     return InsertQ;
7123
7124   return SDValue();
7125 }
7126
7127 /// \brief Lower a vector shuffle as a zero or any extension.
7128 ///
7129 /// Given a specific number of elements, element bit width, and extension
7130 /// stride, produce either a zero or any extension based on the available
7131 /// features of the subtarget.
7132 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7133     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7134     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7135   assert(Scale > 1 && "Need a scale to extend.");
7136   int NumElements = VT.getVectorNumElements();
7137   int EltBits = VT.getScalarSizeInBits();
7138   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7139          "Only 8, 16, and 32 bit elements can be extended.");
7140   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7141
7142   // Found a valid zext mask! Try various lowering strategies based on the
7143   // input type and available ISA extensions.
7144   if (Subtarget->hasSSE41()) {
7145     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7146                                  NumElements / Scale);
7147     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7148   }
7149
7150   // For any extends we can cheat for larger element sizes and use shuffle
7151   // instructions that can fold with a load and/or copy.
7152   if (AnyExt && EltBits == 32) {
7153     int PSHUFDMask[4] = {0, -1, 1, -1};
7154     return DAG.getBitcast(
7155         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7156                         DAG.getBitcast(MVT::v4i32, InputV),
7157                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7158   }
7159   if (AnyExt && EltBits == 16 && Scale > 2) {
7160     int PSHUFDMask[4] = {0, -1, 0, -1};
7161     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7162                          DAG.getBitcast(MVT::v4i32, InputV),
7163                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7164     int PSHUFHWMask[4] = {1, -1, -1, -1};
7165     return DAG.getBitcast(
7166         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7167                         DAG.getBitcast(MVT::v8i16, InputV),
7168                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7169   }
7170
7171   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7172   // to 64-bits.
7173   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7174     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7175     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7176
7177     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7178                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7179                                          DAG.getConstant(EltBits, DL, MVT::i8),
7180                                          DAG.getConstant(0, DL, MVT::i8)));
7181     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7182       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7183
7184     SDValue Hi =
7185         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7186                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7187                                 DAG.getConstant(EltBits, DL, MVT::i8),
7188                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7189     return DAG.getNode(ISD::BITCAST, DL, VT,
7190                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7191   }
7192
7193   // If this would require more than 2 unpack instructions to expand, use
7194   // pshufb when available. We can only use more than 2 unpack instructions
7195   // when zero extending i8 elements which also makes it easier to use pshufb.
7196   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7197     assert(NumElements == 16 && "Unexpected byte vector width!");
7198     SDValue PSHUFBMask[16];
7199     for (int i = 0; i < 16; ++i)
7200       PSHUFBMask[i] =
7201           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7202     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7203     return DAG.getBitcast(VT,
7204                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7205                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7206                                                   MVT::v16i8, PSHUFBMask)));
7207   }
7208
7209   // Otherwise emit a sequence of unpacks.
7210   do {
7211     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7212     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7213                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7214     InputV = DAG.getBitcast(InputVT, InputV);
7215     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7216     Scale /= 2;
7217     EltBits *= 2;
7218     NumElements /= 2;
7219   } while (Scale > 1);
7220   return DAG.getBitcast(VT, InputV);
7221 }
7222
7223 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7224 ///
7225 /// This routine will try to do everything in its power to cleverly lower
7226 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7227 /// check for the profitability of this lowering,  it tries to aggressively
7228 /// match this pattern. It will use all of the micro-architectural details it
7229 /// can to emit an efficient lowering. It handles both blends with all-zero
7230 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7231 /// masking out later).
7232 ///
7233 /// The reason we have dedicated lowering for zext-style shuffles is that they
7234 /// are both incredibly common and often quite performance sensitive.
7235 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7236     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7237     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7238   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7239
7240   int Bits = VT.getSizeInBits();
7241   int NumElements = VT.getVectorNumElements();
7242   assert(VT.getScalarSizeInBits() <= 32 &&
7243          "Exceeds 32-bit integer zero extension limit");
7244   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7245
7246   // Define a helper function to check a particular ext-scale and lower to it if
7247   // valid.
7248   auto Lower = [&](int Scale) -> SDValue {
7249     SDValue InputV;
7250     bool AnyExt = true;
7251     for (int i = 0; i < NumElements; ++i) {
7252       if (Mask[i] == -1)
7253         continue; // Valid anywhere but doesn't tell us anything.
7254       if (i % Scale != 0) {
7255         // Each of the extended elements need to be zeroable.
7256         if (!Zeroable[i])
7257           return SDValue();
7258
7259         // We no longer are in the anyext case.
7260         AnyExt = false;
7261         continue;
7262       }
7263
7264       // Each of the base elements needs to be consecutive indices into the
7265       // same input vector.
7266       SDValue V = Mask[i] < NumElements ? V1 : V2;
7267       if (!InputV)
7268         InputV = V;
7269       else if (InputV != V)
7270         return SDValue(); // Flip-flopping inputs.
7271
7272       if (Mask[i] % NumElements != i / Scale)
7273         return SDValue(); // Non-consecutive strided elements.
7274     }
7275
7276     // If we fail to find an input, we have a zero-shuffle which should always
7277     // have already been handled.
7278     // FIXME: Maybe handle this here in case during blending we end up with one?
7279     if (!InputV)
7280       return SDValue();
7281
7282     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7283         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7284   };
7285
7286   // The widest scale possible for extending is to a 64-bit integer.
7287   assert(Bits % 64 == 0 &&
7288          "The number of bits in a vector must be divisible by 64 on x86!");
7289   int NumExtElements = Bits / 64;
7290
7291   // Each iteration, try extending the elements half as much, but into twice as
7292   // many elements.
7293   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7294     assert(NumElements % NumExtElements == 0 &&
7295            "The input vector size must be divisible by the extended size.");
7296     if (SDValue V = Lower(NumElements / NumExtElements))
7297       return V;
7298   }
7299
7300   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7301   if (Bits != 128)
7302     return SDValue();
7303
7304   // Returns one of the source operands if the shuffle can be reduced to a
7305   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7306   auto CanZExtLowHalf = [&]() {
7307     for (int i = NumElements / 2; i != NumElements; ++i)
7308       if (!Zeroable[i])
7309         return SDValue();
7310     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7311       return V1;
7312     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7313       return V2;
7314     return SDValue();
7315   };
7316
7317   if (SDValue V = CanZExtLowHalf()) {
7318     V = DAG.getBitcast(MVT::v2i64, V);
7319     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7320     return DAG.getBitcast(VT, V);
7321   }
7322
7323   // No viable ext lowering found.
7324   return SDValue();
7325 }
7326
7327 /// \brief Try to get a scalar value for a specific element of a vector.
7328 ///
7329 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7330 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7331                                               SelectionDAG &DAG) {
7332   MVT VT = V.getSimpleValueType();
7333   MVT EltVT = VT.getVectorElementType();
7334   while (V.getOpcode() == ISD::BITCAST)
7335     V = V.getOperand(0);
7336   // If the bitcasts shift the element size, we can't extract an equivalent
7337   // element from it.
7338   MVT NewVT = V.getSimpleValueType();
7339   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7340     return SDValue();
7341
7342   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7343       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7344     // Ensure the scalar operand is the same size as the destination.
7345     // FIXME: Add support for scalar truncation where possible.
7346     SDValue S = V.getOperand(Idx);
7347     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7348       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7349   }
7350
7351   return SDValue();
7352 }
7353
7354 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7355 ///
7356 /// This is particularly important because the set of instructions varies
7357 /// significantly based on whether the operand is a load or not.
7358 static bool isShuffleFoldableLoad(SDValue V) {
7359   while (V.getOpcode() == ISD::BITCAST)
7360     V = V.getOperand(0);
7361
7362   return ISD::isNON_EXTLoad(V.getNode());
7363 }
7364
7365 /// \brief Try to lower insertion of a single element into a zero vector.
7366 ///
7367 /// This is a common pattern that we have especially efficient patterns to lower
7368 /// across all subtarget feature sets.
7369 static SDValue lowerVectorShuffleAsElementInsertion(
7370     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7371     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7372   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7373   MVT ExtVT = VT;
7374   MVT EltVT = VT.getVectorElementType();
7375
7376   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7377                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7378                 Mask.begin();
7379   bool IsV1Zeroable = true;
7380   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7381     if (i != V2Index && !Zeroable[i]) {
7382       IsV1Zeroable = false;
7383       break;
7384     }
7385
7386   // Check for a single input from a SCALAR_TO_VECTOR node.
7387   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7388   // all the smarts here sunk into that routine. However, the current
7389   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7390   // vector shuffle lowering is dead.
7391   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7392                                                DAG);
7393   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7394     // We need to zext the scalar if it is smaller than an i32.
7395     V2S = DAG.getBitcast(EltVT, V2S);
7396     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7397       // Using zext to expand a narrow element won't work for non-zero
7398       // insertions.
7399       if (!IsV1Zeroable)
7400         return SDValue();
7401
7402       // Zero-extend directly to i32.
7403       ExtVT = MVT::v4i32;
7404       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7405     }
7406     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7407   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7408              EltVT == MVT::i16) {
7409     // Either not inserting from the low element of the input or the input
7410     // element size is too small to use VZEXT_MOVL to clear the high bits.
7411     return SDValue();
7412   }
7413
7414   if (!IsV1Zeroable) {
7415     // If V1 can't be treated as a zero vector we have fewer options to lower
7416     // this. We can't support integer vectors or non-zero targets cheaply, and
7417     // the V1 elements can't be permuted in any way.
7418     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7419     if (!VT.isFloatingPoint() || V2Index != 0)
7420       return SDValue();
7421     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7422     V1Mask[V2Index] = -1;
7423     if (!isNoopShuffleMask(V1Mask))
7424       return SDValue();
7425     // This is essentially a special case blend operation, but if we have
7426     // general purpose blend operations, they are always faster. Bail and let
7427     // the rest of the lowering handle these as blends.
7428     if (Subtarget->hasSSE41())
7429       return SDValue();
7430
7431     // Otherwise, use MOVSD or MOVSS.
7432     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7433            "Only two types of floating point element types to handle!");
7434     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7435                        ExtVT, V1, V2);
7436   }
7437
7438   // This lowering only works for the low element with floating point vectors.
7439   if (VT.isFloatingPoint() && V2Index != 0)
7440     return SDValue();
7441
7442   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7443   if (ExtVT != VT)
7444     V2 = DAG.getBitcast(VT, V2);
7445
7446   if (V2Index != 0) {
7447     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7448     // the desired position. Otherwise it is more efficient to do a vector
7449     // shift left. We know that we can do a vector shift left because all
7450     // the inputs are zero.
7451     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7452       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7453       V2Shuffle[V2Index] = 0;
7454       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7455     } else {
7456       V2 = DAG.getBitcast(MVT::v2i64, V2);
7457       V2 = DAG.getNode(
7458           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7459           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7460                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7461                               DAG.getDataLayout(), VT)));
7462       V2 = DAG.getBitcast(VT, V2);
7463     }
7464   }
7465   return V2;
7466 }
7467
7468 /// \brief Try to lower broadcast of a single element.
7469 ///
7470 /// For convenience, this code also bundles all of the subtarget feature set
7471 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7472 /// a convenient way to factor it out.
7473 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7474                                              ArrayRef<int> Mask,
7475                                              const X86Subtarget *Subtarget,
7476                                              SelectionDAG &DAG) {
7477   if (!Subtarget->hasAVX())
7478     return SDValue();
7479   if (VT.isInteger() && !Subtarget->hasAVX2())
7480     return SDValue();
7481
7482   // Check that the mask is a broadcast.
7483   int BroadcastIdx = -1;
7484   for (int M : Mask)
7485     if (M >= 0 && BroadcastIdx == -1)
7486       BroadcastIdx = M;
7487     else if (M >= 0 && M != BroadcastIdx)
7488       return SDValue();
7489
7490   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7491                                             "a sorted mask where the broadcast "
7492                                             "comes from V1.");
7493
7494   // Go up the chain of (vector) values to find a scalar load that we can
7495   // combine with the broadcast.
7496   for (;;) {
7497     switch (V.getOpcode()) {
7498     case ISD::CONCAT_VECTORS: {
7499       int OperandSize = Mask.size() / V.getNumOperands();
7500       V = V.getOperand(BroadcastIdx / OperandSize);
7501       BroadcastIdx %= OperandSize;
7502       continue;
7503     }
7504
7505     case ISD::INSERT_SUBVECTOR: {
7506       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7507       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7508       if (!ConstantIdx)
7509         break;
7510
7511       int BeginIdx = (int)ConstantIdx->getZExtValue();
7512       int EndIdx =
7513           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7514       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7515         BroadcastIdx -= BeginIdx;
7516         V = VInner;
7517       } else {
7518         V = VOuter;
7519       }
7520       continue;
7521     }
7522     }
7523     break;
7524   }
7525
7526   // Check if this is a broadcast of a scalar. We special case lowering
7527   // for scalars so that we can more effectively fold with loads.
7528   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7529       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7530     V = V.getOperand(BroadcastIdx);
7531
7532     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7533     // Only AVX2 has register broadcasts.
7534     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7535       return SDValue();
7536   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7537     // We can't broadcast from a vector register without AVX2, and we can only
7538     // broadcast from the zero-element of a vector register.
7539     return SDValue();
7540   }
7541
7542   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7543 }
7544
7545 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7546 // INSERTPS when the V1 elements are already in the correct locations
7547 // because otherwise we can just always use two SHUFPS instructions which
7548 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7549 // perform INSERTPS if a single V1 element is out of place and all V2
7550 // elements are zeroable.
7551 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7552                                             ArrayRef<int> Mask,
7553                                             SelectionDAG &DAG) {
7554   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7555   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7556   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7557   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7558
7559   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7560
7561   unsigned ZMask = 0;
7562   int V1DstIndex = -1;
7563   int V2DstIndex = -1;
7564   bool V1UsedInPlace = false;
7565
7566   for (int i = 0; i < 4; ++i) {
7567     // Synthesize a zero mask from the zeroable elements (includes undefs).
7568     if (Zeroable[i]) {
7569       ZMask |= 1 << i;
7570       continue;
7571     }
7572
7573     // Flag if we use any V1 inputs in place.
7574     if (i == Mask[i]) {
7575       V1UsedInPlace = true;
7576       continue;
7577     }
7578
7579     // We can only insert a single non-zeroable element.
7580     if (V1DstIndex != -1 || V2DstIndex != -1)
7581       return SDValue();
7582
7583     if (Mask[i] < 4) {
7584       // V1 input out of place for insertion.
7585       V1DstIndex = i;
7586     } else {
7587       // V2 input for insertion.
7588       V2DstIndex = i;
7589     }
7590   }
7591
7592   // Don't bother if we have no (non-zeroable) element for insertion.
7593   if (V1DstIndex == -1 && V2DstIndex == -1)
7594     return SDValue();
7595
7596   // Determine element insertion src/dst indices. The src index is from the
7597   // start of the inserted vector, not the start of the concatenated vector.
7598   unsigned V2SrcIndex = 0;
7599   if (V1DstIndex != -1) {
7600     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7601     // and don't use the original V2 at all.
7602     V2SrcIndex = Mask[V1DstIndex];
7603     V2DstIndex = V1DstIndex;
7604     V2 = V1;
7605   } else {
7606     V2SrcIndex = Mask[V2DstIndex] - 4;
7607   }
7608
7609   // If no V1 inputs are used in place, then the result is created only from
7610   // the zero mask and the V2 insertion - so remove V1 dependency.
7611   if (!V1UsedInPlace)
7612     V1 = DAG.getUNDEF(MVT::v4f32);
7613
7614   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7615   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7616
7617   // Insert the V2 element into the desired position.
7618   SDLoc DL(Op);
7619   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7620                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7621 }
7622
7623 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7624 /// UNPCK instruction.
7625 ///
7626 /// This specifically targets cases where we end up with alternating between
7627 /// the two inputs, and so can permute them into something that feeds a single
7628 /// UNPCK instruction. Note that this routine only targets integer vectors
7629 /// because for floating point vectors we have a generalized SHUFPS lowering
7630 /// strategy that handles everything that doesn't *exactly* match an unpack,
7631 /// making this clever lowering unnecessary.
7632 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7633                                           SDValue V2, ArrayRef<int> Mask,
7634                                           SelectionDAG &DAG) {
7635   assert(!VT.isFloatingPoint() &&
7636          "This routine only supports integer vectors.");
7637   assert(!isSingleInputShuffleMask(Mask) &&
7638          "This routine should only be used when blending two inputs.");
7639   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7640
7641   int Size = Mask.size();
7642
7643   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7644     return M >= 0 && M % Size < Size / 2;
7645   });
7646   int NumHiInputs = std::count_if(
7647       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7648
7649   bool UnpackLo = NumLoInputs >= NumHiInputs;
7650
7651   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7652     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7653     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7654
7655     for (int i = 0; i < Size; ++i) {
7656       if (Mask[i] < 0)
7657         continue;
7658
7659       // Each element of the unpack contains Scale elements from this mask.
7660       int UnpackIdx = i / Scale;
7661
7662       // We only handle the case where V1 feeds the first slots of the unpack.
7663       // We rely on canonicalization to ensure this is the case.
7664       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7665         return SDValue();
7666
7667       // Setup the mask for this input. The indexing is tricky as we have to
7668       // handle the unpack stride.
7669       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7670       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7671           Mask[i] % Size;
7672     }
7673
7674     // If we will have to shuffle both inputs to use the unpack, check whether
7675     // we can just unpack first and shuffle the result. If so, skip this unpack.
7676     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7677         !isNoopShuffleMask(V2Mask))
7678       return SDValue();
7679
7680     // Shuffle the inputs into place.
7681     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7682     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7683
7684     // Cast the inputs to the type we will use to unpack them.
7685     V1 = DAG.getBitcast(UnpackVT, V1);
7686     V2 = DAG.getBitcast(UnpackVT, V2);
7687
7688     // Unpack the inputs and cast the result back to the desired type.
7689     return DAG.getBitcast(
7690         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7691                         UnpackVT, V1, V2));
7692   };
7693
7694   // We try each unpack from the largest to the smallest to try and find one
7695   // that fits this mask.
7696   int OrigNumElements = VT.getVectorNumElements();
7697   int OrigScalarSize = VT.getScalarSizeInBits();
7698   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7699     int Scale = ScalarSize / OrigScalarSize;
7700     int NumElements = OrigNumElements / Scale;
7701     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7702     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7703       return Unpack;
7704   }
7705
7706   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7707   // initial unpack.
7708   if (NumLoInputs == 0 || NumHiInputs == 0) {
7709     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7710            "We have to have *some* inputs!");
7711     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7712
7713     // FIXME: We could consider the total complexity of the permute of each
7714     // possible unpacking. Or at the least we should consider how many
7715     // half-crossings are created.
7716     // FIXME: We could consider commuting the unpacks.
7717
7718     SmallVector<int, 32> PermMask;
7719     PermMask.assign(Size, -1);
7720     for (int i = 0; i < Size; ++i) {
7721       if (Mask[i] < 0)
7722         continue;
7723
7724       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7725
7726       PermMask[i] =
7727           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7728     }
7729     return DAG.getVectorShuffle(
7730         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7731                             DL, VT, V1, V2),
7732         DAG.getUNDEF(VT), PermMask);
7733   }
7734
7735   return SDValue();
7736 }
7737
7738 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7739 ///
7740 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7741 /// support for floating point shuffles but not integer shuffles. These
7742 /// instructions will incur a domain crossing penalty on some chips though so
7743 /// it is better to avoid lowering through this for integer vectors where
7744 /// possible.
7745 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7746                                        const X86Subtarget *Subtarget,
7747                                        SelectionDAG &DAG) {
7748   SDLoc DL(Op);
7749   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7750   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7751   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7752   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7753   ArrayRef<int> Mask = SVOp->getMask();
7754   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7755
7756   if (isSingleInputShuffleMask(Mask)) {
7757     // Use low duplicate instructions for masks that match their pattern.
7758     if (Subtarget->hasSSE3())
7759       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7760         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7761
7762     // Straight shuffle of a single input vector. Simulate this by using the
7763     // single input as both of the "inputs" to this instruction..
7764     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7765
7766     if (Subtarget->hasAVX()) {
7767       // If we have AVX, we can use VPERMILPS which will allow folding a load
7768       // into the shuffle.
7769       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7770                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7771     }
7772
7773     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7774                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7775   }
7776   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7777   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7778
7779   // If we have a single input, insert that into V1 if we can do so cheaply.
7780   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7781     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7782             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7783       return Insertion;
7784     // Try inverting the insertion since for v2 masks it is easy to do and we
7785     // can't reliably sort the mask one way or the other.
7786     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7787                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7788     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7789             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7790       return Insertion;
7791   }
7792
7793   // Try to use one of the special instruction patterns to handle two common
7794   // blend patterns if a zero-blend above didn't work.
7795   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7796       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7797     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7798       // We can either use a special instruction to load over the low double or
7799       // to move just the low double.
7800       return DAG.getNode(
7801           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7802           DL, MVT::v2f64, V2,
7803           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7804
7805   if (Subtarget->hasSSE41())
7806     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7807                                                   Subtarget, DAG))
7808       return Blend;
7809
7810   // Use dedicated unpack instructions for masks that match their pattern.
7811   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7812     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7813   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7814     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7815
7816   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7817   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7818                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7819 }
7820
7821 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7822 ///
7823 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7824 /// the integer unit to minimize domain crossing penalties. However, for blends
7825 /// it falls back to the floating point shuffle operation with appropriate bit
7826 /// casting.
7827 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7828                                        const X86Subtarget *Subtarget,
7829                                        SelectionDAG &DAG) {
7830   SDLoc DL(Op);
7831   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7832   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7833   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7834   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7835   ArrayRef<int> Mask = SVOp->getMask();
7836   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7837
7838   if (isSingleInputShuffleMask(Mask)) {
7839     // Check for being able to broadcast a single element.
7840     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7841                                                           Mask, Subtarget, DAG))
7842       return Broadcast;
7843
7844     // Straight shuffle of a single input vector. For everything from SSE2
7845     // onward this has a single fast instruction with no scary immediates.
7846     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7847     V1 = DAG.getBitcast(MVT::v4i32, V1);
7848     int WidenedMask[4] = {
7849         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7850         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7851     return DAG.getBitcast(
7852         MVT::v2i64,
7853         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7854                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7855   }
7856   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7857   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7858   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7859   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7860
7861   // If we have a blend of two PACKUS operations an the blend aligns with the
7862   // low and half halves, we can just merge the PACKUS operations. This is
7863   // particularly important as it lets us merge shuffles that this routine itself
7864   // creates.
7865   auto GetPackNode = [](SDValue V) {
7866     while (V.getOpcode() == ISD::BITCAST)
7867       V = V.getOperand(0);
7868
7869     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7870   };
7871   if (SDValue V1Pack = GetPackNode(V1))
7872     if (SDValue V2Pack = GetPackNode(V2))
7873       return DAG.getBitcast(MVT::v2i64,
7874                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7875                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7876                                                      : V1Pack.getOperand(1),
7877                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7878                                                      : V2Pack.getOperand(1)));
7879
7880   // Try to use shift instructions.
7881   if (SDValue Shift =
7882           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7883     return Shift;
7884
7885   // When loading a scalar and then shuffling it into a vector we can often do
7886   // the insertion cheaply.
7887   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7888           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7889     return Insertion;
7890   // Try inverting the insertion since for v2 masks it is easy to do and we
7891   // can't reliably sort the mask one way or the other.
7892   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7893   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7894           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7895     return Insertion;
7896
7897   // We have different paths for blend lowering, but they all must use the
7898   // *exact* same predicate.
7899   bool IsBlendSupported = Subtarget->hasSSE41();
7900   if (IsBlendSupported)
7901     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7902                                                   Subtarget, DAG))
7903       return Blend;
7904
7905   // Use dedicated unpack instructions for masks that match their pattern.
7906   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7907     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7908   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7909     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7910
7911   // Try to use byte rotation instructions.
7912   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7913   if (Subtarget->hasSSSE3())
7914     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7915             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7916       return Rotate;
7917
7918   // If we have direct support for blends, we should lower by decomposing into
7919   // a permute. That will be faster than the domain cross.
7920   if (IsBlendSupported)
7921     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7922                                                       Mask, DAG);
7923
7924   // We implement this with SHUFPD which is pretty lame because it will likely
7925   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7926   // However, all the alternatives are still more cycles and newer chips don't
7927   // have this problem. It would be really nice if x86 had better shuffles here.
7928   V1 = DAG.getBitcast(MVT::v2f64, V1);
7929   V2 = DAG.getBitcast(MVT::v2f64, V2);
7930   return DAG.getBitcast(MVT::v2i64,
7931                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7932 }
7933
7934 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7935 ///
7936 /// This is used to disable more specialized lowerings when the shufps lowering
7937 /// will happen to be efficient.
7938 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7939   // This routine only handles 128-bit shufps.
7940   assert(Mask.size() == 4 && "Unsupported mask size!");
7941
7942   // To lower with a single SHUFPS we need to have the low half and high half
7943   // each requiring a single input.
7944   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7945     return false;
7946   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7947     return false;
7948
7949   return true;
7950 }
7951
7952 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7953 ///
7954 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7955 /// It makes no assumptions about whether this is the *best* lowering, it simply
7956 /// uses it.
7957 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7958                                             ArrayRef<int> Mask, SDValue V1,
7959                                             SDValue V2, SelectionDAG &DAG) {
7960   SDValue LowV = V1, HighV = V2;
7961   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7962
7963   int NumV2Elements =
7964       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7965
7966   if (NumV2Elements == 1) {
7967     int V2Index =
7968         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7969         Mask.begin();
7970
7971     // Compute the index adjacent to V2Index and in the same half by toggling
7972     // the low bit.
7973     int V2AdjIndex = V2Index ^ 1;
7974
7975     if (Mask[V2AdjIndex] == -1) {
7976       // Handles all the cases where we have a single V2 element and an undef.
7977       // This will only ever happen in the high lanes because we commute the
7978       // vector otherwise.
7979       if (V2Index < 2)
7980         std::swap(LowV, HighV);
7981       NewMask[V2Index] -= 4;
7982     } else {
7983       // Handle the case where the V2 element ends up adjacent to a V1 element.
7984       // To make this work, blend them together as the first step.
7985       int V1Index = V2AdjIndex;
7986       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7987       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7988                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7989
7990       // Now proceed to reconstruct the final blend as we have the necessary
7991       // high or low half formed.
7992       if (V2Index < 2) {
7993         LowV = V2;
7994         HighV = V1;
7995       } else {
7996         HighV = V2;
7997       }
7998       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7999       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8000     }
8001   } else if (NumV2Elements == 2) {
8002     if (Mask[0] < 4 && Mask[1] < 4) {
8003       // Handle the easy case where we have V1 in the low lanes and V2 in the
8004       // high lanes.
8005       NewMask[2] -= 4;
8006       NewMask[3] -= 4;
8007     } else if (Mask[2] < 4 && Mask[3] < 4) {
8008       // We also handle the reversed case because this utility may get called
8009       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8010       // arrange things in the right direction.
8011       NewMask[0] -= 4;
8012       NewMask[1] -= 4;
8013       HighV = V1;
8014       LowV = V2;
8015     } else {
8016       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8017       // trying to place elements directly, just blend them and set up the final
8018       // shuffle to place them.
8019
8020       // The first two blend mask elements are for V1, the second two are for
8021       // V2.
8022       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8023                           Mask[2] < 4 ? Mask[2] : Mask[3],
8024                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8025                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8026       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8027                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8028
8029       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8030       // a blend.
8031       LowV = HighV = V1;
8032       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8033       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8034       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8035       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8036     }
8037   }
8038   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8039                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8040 }
8041
8042 /// \brief Lower 4-lane 32-bit floating point shuffles.
8043 ///
8044 /// Uses instructions exclusively from the floating point unit to minimize
8045 /// domain crossing penalties, as these are sufficient to implement all v4f32
8046 /// shuffles.
8047 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8048                                        const X86Subtarget *Subtarget,
8049                                        SelectionDAG &DAG) {
8050   SDLoc DL(Op);
8051   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8052   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8053   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8054   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8055   ArrayRef<int> Mask = SVOp->getMask();
8056   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8057
8058   int NumV2Elements =
8059       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8060
8061   if (NumV2Elements == 0) {
8062     // Check for being able to broadcast a single element.
8063     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8064                                                           Mask, Subtarget, DAG))
8065       return Broadcast;
8066
8067     // Use even/odd duplicate instructions for masks that match their pattern.
8068     if (Subtarget->hasSSE3()) {
8069       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8070         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8071       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8072         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8073     }
8074
8075     if (Subtarget->hasAVX()) {
8076       // If we have AVX, we can use VPERMILPS which will allow folding a load
8077       // into the shuffle.
8078       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8079                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8080     }
8081
8082     // Otherwise, use a straight shuffle of a single input vector. We pass the
8083     // input vector to both operands to simulate this with a SHUFPS.
8084     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8085                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8086   }
8087
8088   // There are special ways we can lower some single-element blends. However, we
8089   // have custom ways we can lower more complex single-element blends below that
8090   // we defer to if both this and BLENDPS fail to match, so restrict this to
8091   // when the V2 input is targeting element 0 of the mask -- that is the fast
8092   // case here.
8093   if (NumV2Elements == 1 && Mask[0] >= 4)
8094     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8095                                                          Mask, Subtarget, DAG))
8096       return V;
8097
8098   if (Subtarget->hasSSE41()) {
8099     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8100                                                   Subtarget, DAG))
8101       return Blend;
8102
8103     // Use INSERTPS if we can complete the shuffle efficiently.
8104     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8105       return V;
8106
8107     if (!isSingleSHUFPSMask(Mask))
8108       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8109               DL, MVT::v4f32, V1, V2, Mask, DAG))
8110         return BlendPerm;
8111   }
8112
8113   // Use dedicated unpack instructions for masks that match their pattern.
8114   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8115     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8116   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8117     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8118   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8119     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8120   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8121     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8122
8123   // Otherwise fall back to a SHUFPS lowering strategy.
8124   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8125 }
8126
8127 /// \brief Lower 4-lane i32 vector shuffles.
8128 ///
8129 /// We try to handle these with integer-domain shuffles where we can, but for
8130 /// blends we use the floating point domain blend instructions.
8131 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8132                                        const X86Subtarget *Subtarget,
8133                                        SelectionDAG &DAG) {
8134   SDLoc DL(Op);
8135   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8136   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8137   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8138   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8139   ArrayRef<int> Mask = SVOp->getMask();
8140   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8141
8142   // Whenever we can lower this as a zext, that instruction is strictly faster
8143   // than any alternative. It also allows us to fold memory operands into the
8144   // shuffle in many cases.
8145   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8146                                                          Mask, Subtarget, DAG))
8147     return ZExt;
8148
8149   int NumV2Elements =
8150       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8151
8152   if (NumV2Elements == 0) {
8153     // Check for being able to broadcast a single element.
8154     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8155                                                           Mask, Subtarget, DAG))
8156       return Broadcast;
8157
8158     // Straight shuffle of a single input vector. For everything from SSE2
8159     // onward this has a single fast instruction with no scary immediates.
8160     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8161     // but we aren't actually going to use the UNPCK instruction because doing
8162     // so prevents folding a load into this instruction or making a copy.
8163     const int UnpackLoMask[] = {0, 0, 1, 1};
8164     const int UnpackHiMask[] = {2, 2, 3, 3};
8165     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8166       Mask = UnpackLoMask;
8167     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8168       Mask = UnpackHiMask;
8169
8170     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8171                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8172   }
8173
8174   // Try to use shift instructions.
8175   if (SDValue Shift =
8176           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8177     return Shift;
8178
8179   // There are special ways we can lower some single-element blends.
8180   if (NumV2Elements == 1)
8181     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8182                                                          Mask, Subtarget, DAG))
8183       return V;
8184
8185   // We have different paths for blend lowering, but they all must use the
8186   // *exact* same predicate.
8187   bool IsBlendSupported = Subtarget->hasSSE41();
8188   if (IsBlendSupported)
8189     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8190                                                   Subtarget, DAG))
8191       return Blend;
8192
8193   if (SDValue Masked =
8194           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8195     return Masked;
8196
8197   // Use dedicated unpack instructions for masks that match their pattern.
8198   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8199     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8200   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8201     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8202   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8203     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8204   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8205     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8206
8207   // Try to use byte rotation instructions.
8208   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8209   if (Subtarget->hasSSSE3())
8210     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8211             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8212       return Rotate;
8213
8214   // If we have direct support for blends, we should lower by decomposing into
8215   // a permute. That will be faster than the domain cross.
8216   if (IsBlendSupported)
8217     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8218                                                       Mask, DAG);
8219
8220   // Try to lower by permuting the inputs into an unpack instruction.
8221   if (SDValue Unpack =
8222           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8223     return Unpack;
8224
8225   // We implement this with SHUFPS because it can blend from two vectors.
8226   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8227   // up the inputs, bypassing domain shift penalties that we would encur if we
8228   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8229   // relevant.
8230   return DAG.getBitcast(
8231       MVT::v4i32,
8232       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8233                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8234 }
8235
8236 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8237 /// shuffle lowering, and the most complex part.
8238 ///
8239 /// The lowering strategy is to try to form pairs of input lanes which are
8240 /// targeted at the same half of the final vector, and then use a dword shuffle
8241 /// to place them onto the right half, and finally unpack the paired lanes into
8242 /// their final position.
8243 ///
8244 /// The exact breakdown of how to form these dword pairs and align them on the
8245 /// correct sides is really tricky. See the comments within the function for
8246 /// more of the details.
8247 ///
8248 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8249 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8250 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8251 /// vector, form the analogous 128-bit 8-element Mask.
8252 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8253     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8254     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8255   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8256   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8257
8258   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8259   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8260   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8261
8262   SmallVector<int, 4> LoInputs;
8263   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8264                [](int M) { return M >= 0; });
8265   std::sort(LoInputs.begin(), LoInputs.end());
8266   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8267   SmallVector<int, 4> HiInputs;
8268   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8269                [](int M) { return M >= 0; });
8270   std::sort(HiInputs.begin(), HiInputs.end());
8271   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8272   int NumLToL =
8273       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8274   int NumHToL = LoInputs.size() - NumLToL;
8275   int NumLToH =
8276       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8277   int NumHToH = HiInputs.size() - NumLToH;
8278   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8279   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8280   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8281   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8282
8283   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8284   // such inputs we can swap two of the dwords across the half mark and end up
8285   // with <=2 inputs to each half in each half. Once there, we can fall through
8286   // to the generic code below. For example:
8287   //
8288   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8289   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8290   //
8291   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8292   // and an existing 2-into-2 on the other half. In this case we may have to
8293   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8294   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8295   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8296   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8297   // half than the one we target for fixing) will be fixed when we re-enter this
8298   // path. We will also combine away any sequence of PSHUFD instructions that
8299   // result into a single instruction. Here is an example of the tricky case:
8300   //
8301   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8302   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8303   //
8304   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8305   //
8306   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8307   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8308   //
8309   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8310   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8311   //
8312   // The result is fine to be handled by the generic logic.
8313   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8314                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8315                           int AOffset, int BOffset) {
8316     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8317            "Must call this with A having 3 or 1 inputs from the A half.");
8318     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8319            "Must call this with B having 1 or 3 inputs from the B half.");
8320     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8321            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8322
8323     // Compute the index of dword with only one word among the three inputs in
8324     // a half by taking the sum of the half with three inputs and subtracting
8325     // the sum of the actual three inputs. The difference is the remaining
8326     // slot.
8327     int ADWord, BDWord;
8328     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8329     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8330     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8331     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8332     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8333     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8334     int TripleNonInputIdx =
8335         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8336     TripleDWord = TripleNonInputIdx / 2;
8337
8338     // We use xor with one to compute the adjacent DWord to whichever one the
8339     // OneInput is in.
8340     OneInputDWord = (OneInput / 2) ^ 1;
8341
8342     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8343     // and BToA inputs. If there is also such a problem with the BToB and AToB
8344     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8345     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8346     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8347     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8348       // Compute how many inputs will be flipped by swapping these DWords. We
8349       // need
8350       // to balance this to ensure we don't form a 3-1 shuffle in the other
8351       // half.
8352       int NumFlippedAToBInputs =
8353           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8354           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8355       int NumFlippedBToBInputs =
8356           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8357           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8358       if ((NumFlippedAToBInputs == 1 &&
8359            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8360           (NumFlippedBToBInputs == 1 &&
8361            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8362         // We choose whether to fix the A half or B half based on whether that
8363         // half has zero flipped inputs. At zero, we may not be able to fix it
8364         // with that half. We also bias towards fixing the B half because that
8365         // will more commonly be the high half, and we have to bias one way.
8366         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8367                                                        ArrayRef<int> Inputs) {
8368           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8369           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8370                                          PinnedIdx ^ 1) != Inputs.end();
8371           // Determine whether the free index is in the flipped dword or the
8372           // unflipped dword based on where the pinned index is. We use this bit
8373           // in an xor to conditionally select the adjacent dword.
8374           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8375           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8376                                              FixFreeIdx) != Inputs.end();
8377           if (IsFixIdxInput == IsFixFreeIdxInput)
8378             FixFreeIdx += 1;
8379           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8380                                         FixFreeIdx) != Inputs.end();
8381           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8382                  "We need to be changing the number of flipped inputs!");
8383           int PSHUFHalfMask[] = {0, 1, 2, 3};
8384           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8385           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8386                           MVT::v8i16, V,
8387                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8388
8389           for (int &M : Mask)
8390             if (M != -1 && M == FixIdx)
8391               M = FixFreeIdx;
8392             else if (M != -1 && M == FixFreeIdx)
8393               M = FixIdx;
8394         };
8395         if (NumFlippedBToBInputs != 0) {
8396           int BPinnedIdx =
8397               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8398           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8399         } else {
8400           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8401           int APinnedIdx =
8402               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8403           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8404         }
8405       }
8406     }
8407
8408     int PSHUFDMask[] = {0, 1, 2, 3};
8409     PSHUFDMask[ADWord] = BDWord;
8410     PSHUFDMask[BDWord] = ADWord;
8411     V = DAG.getBitcast(
8412         VT,
8413         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8414                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8415
8416     // Adjust the mask to match the new locations of A and B.
8417     for (int &M : Mask)
8418       if (M != -1 && M/2 == ADWord)
8419         M = 2 * BDWord + M % 2;
8420       else if (M != -1 && M/2 == BDWord)
8421         M = 2 * ADWord + M % 2;
8422
8423     // Recurse back into this routine to re-compute state now that this isn't
8424     // a 3 and 1 problem.
8425     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8426                                                      DAG);
8427   };
8428   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8429     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8430   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8431     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8432
8433   // At this point there are at most two inputs to the low and high halves from
8434   // each half. That means the inputs can always be grouped into dwords and
8435   // those dwords can then be moved to the correct half with a dword shuffle.
8436   // We use at most one low and one high word shuffle to collect these paired
8437   // inputs into dwords, and finally a dword shuffle to place them.
8438   int PSHUFLMask[4] = {-1, -1, -1, -1};
8439   int PSHUFHMask[4] = {-1, -1, -1, -1};
8440   int PSHUFDMask[4] = {-1, -1, -1, -1};
8441
8442   // First fix the masks for all the inputs that are staying in their
8443   // original halves. This will then dictate the targets of the cross-half
8444   // shuffles.
8445   auto fixInPlaceInputs =
8446       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8447                     MutableArrayRef<int> SourceHalfMask,
8448                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8449     if (InPlaceInputs.empty())
8450       return;
8451     if (InPlaceInputs.size() == 1) {
8452       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8453           InPlaceInputs[0] - HalfOffset;
8454       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8455       return;
8456     }
8457     if (IncomingInputs.empty()) {
8458       // Just fix all of the in place inputs.
8459       for (int Input : InPlaceInputs) {
8460         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8461         PSHUFDMask[Input / 2] = Input / 2;
8462       }
8463       return;
8464     }
8465
8466     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8467     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8468         InPlaceInputs[0] - HalfOffset;
8469     // Put the second input next to the first so that they are packed into
8470     // a dword. We find the adjacent index by toggling the low bit.
8471     int AdjIndex = InPlaceInputs[0] ^ 1;
8472     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8473     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8474     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8475   };
8476   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8477   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8478
8479   // Now gather the cross-half inputs and place them into a free dword of
8480   // their target half.
8481   // FIXME: This operation could almost certainly be simplified dramatically to
8482   // look more like the 3-1 fixing operation.
8483   auto moveInputsToRightHalf = [&PSHUFDMask](
8484       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8485       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8486       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8487       int DestOffset) {
8488     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8489       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8490     };
8491     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8492                                                int Word) {
8493       int LowWord = Word & ~1;
8494       int HighWord = Word | 1;
8495       return isWordClobbered(SourceHalfMask, LowWord) ||
8496              isWordClobbered(SourceHalfMask, HighWord);
8497     };
8498
8499     if (IncomingInputs.empty())
8500       return;
8501
8502     if (ExistingInputs.empty()) {
8503       // Map any dwords with inputs from them into the right half.
8504       for (int Input : IncomingInputs) {
8505         // If the source half mask maps over the inputs, turn those into
8506         // swaps and use the swapped lane.
8507         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8508           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8509             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8510                 Input - SourceOffset;
8511             // We have to swap the uses in our half mask in one sweep.
8512             for (int &M : HalfMask)
8513               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8514                 M = Input;
8515               else if (M == Input)
8516                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8517           } else {
8518             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8519                        Input - SourceOffset &&
8520                    "Previous placement doesn't match!");
8521           }
8522           // Note that this correctly re-maps both when we do a swap and when
8523           // we observe the other side of the swap above. We rely on that to
8524           // avoid swapping the members of the input list directly.
8525           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8526         }
8527
8528         // Map the input's dword into the correct half.
8529         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8530           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8531         else
8532           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8533                      Input / 2 &&
8534                  "Previous placement doesn't match!");
8535       }
8536
8537       // And just directly shift any other-half mask elements to be same-half
8538       // as we will have mirrored the dword containing the element into the
8539       // same position within that half.
8540       for (int &M : HalfMask)
8541         if (M >= SourceOffset && M < SourceOffset + 4) {
8542           M = M - SourceOffset + DestOffset;
8543           assert(M >= 0 && "This should never wrap below zero!");
8544         }
8545       return;
8546     }
8547
8548     // Ensure we have the input in a viable dword of its current half. This
8549     // is particularly tricky because the original position may be clobbered
8550     // by inputs being moved and *staying* in that half.
8551     if (IncomingInputs.size() == 1) {
8552       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8553         int InputFixed = std::find(std::begin(SourceHalfMask),
8554                                    std::end(SourceHalfMask), -1) -
8555                          std::begin(SourceHalfMask) + SourceOffset;
8556         SourceHalfMask[InputFixed - SourceOffset] =
8557             IncomingInputs[0] - SourceOffset;
8558         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8559                      InputFixed);
8560         IncomingInputs[0] = InputFixed;
8561       }
8562     } else if (IncomingInputs.size() == 2) {
8563       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8564           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8565         // We have two non-adjacent or clobbered inputs we need to extract from
8566         // the source half. To do this, we need to map them into some adjacent
8567         // dword slot in the source mask.
8568         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8569                               IncomingInputs[1] - SourceOffset};
8570
8571         // If there is a free slot in the source half mask adjacent to one of
8572         // the inputs, place the other input in it. We use (Index XOR 1) to
8573         // compute an adjacent index.
8574         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8575             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8576           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8577           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8578           InputsFixed[1] = InputsFixed[0] ^ 1;
8579         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8580                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8581           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8582           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8583           InputsFixed[0] = InputsFixed[1] ^ 1;
8584         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8585                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8586           // The two inputs are in the same DWord but it is clobbered and the
8587           // adjacent DWord isn't used at all. Move both inputs to the free
8588           // slot.
8589           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8590           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8591           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8592           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8593         } else {
8594           // The only way we hit this point is if there is no clobbering
8595           // (because there are no off-half inputs to this half) and there is no
8596           // free slot adjacent to one of the inputs. In this case, we have to
8597           // swap an input with a non-input.
8598           for (int i = 0; i < 4; ++i)
8599             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8600                    "We can't handle any clobbers here!");
8601           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8602                  "Cannot have adjacent inputs here!");
8603
8604           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8605           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8606
8607           // We also have to update the final source mask in this case because
8608           // it may need to undo the above swap.
8609           for (int &M : FinalSourceHalfMask)
8610             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8611               M = InputsFixed[1] + SourceOffset;
8612             else if (M == InputsFixed[1] + SourceOffset)
8613               M = (InputsFixed[0] ^ 1) + SourceOffset;
8614
8615           InputsFixed[1] = InputsFixed[0] ^ 1;
8616         }
8617
8618         // Point everything at the fixed inputs.
8619         for (int &M : HalfMask)
8620           if (M == IncomingInputs[0])
8621             M = InputsFixed[0] + SourceOffset;
8622           else if (M == IncomingInputs[1])
8623             M = InputsFixed[1] + SourceOffset;
8624
8625         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8626         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8627       }
8628     } else {
8629       llvm_unreachable("Unhandled input size!");
8630     }
8631
8632     // Now hoist the DWord down to the right half.
8633     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8634     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8635     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8636     for (int &M : HalfMask)
8637       for (int Input : IncomingInputs)
8638         if (M == Input)
8639           M = FreeDWord * 2 + Input % 2;
8640   };
8641   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8642                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8643   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8644                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8645
8646   // Now enact all the shuffles we've computed to move the inputs into their
8647   // target half.
8648   if (!isNoopShuffleMask(PSHUFLMask))
8649     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8650                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8651   if (!isNoopShuffleMask(PSHUFHMask))
8652     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8653                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8654   if (!isNoopShuffleMask(PSHUFDMask))
8655     V = DAG.getBitcast(
8656         VT,
8657         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8658                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8659
8660   // At this point, each half should contain all its inputs, and we can then
8661   // just shuffle them into their final position.
8662   assert(std::count_if(LoMask.begin(), LoMask.end(),
8663                        [](int M) { return M >= 4; }) == 0 &&
8664          "Failed to lift all the high half inputs to the low mask!");
8665   assert(std::count_if(HiMask.begin(), HiMask.end(),
8666                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8667          "Failed to lift all the low half inputs to the high mask!");
8668
8669   // Do a half shuffle for the low mask.
8670   if (!isNoopShuffleMask(LoMask))
8671     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8672                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8673
8674   // Do a half shuffle with the high mask after shifting its values down.
8675   for (int &M : HiMask)
8676     if (M >= 0)
8677       M -= 4;
8678   if (!isNoopShuffleMask(HiMask))
8679     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8680                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8681
8682   return V;
8683 }
8684
8685 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8686 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8687                                           SDValue V2, ArrayRef<int> Mask,
8688                                           SelectionDAG &DAG, bool &V1InUse,
8689                                           bool &V2InUse) {
8690   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8691   SDValue V1Mask[16];
8692   SDValue V2Mask[16];
8693   V1InUse = false;
8694   V2InUse = false;
8695
8696   int Size = Mask.size();
8697   int Scale = 16 / Size;
8698   for (int i = 0; i < 16; ++i) {
8699     if (Mask[i / Scale] == -1) {
8700       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8701     } else {
8702       const int ZeroMask = 0x80;
8703       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8704                                           : ZeroMask;
8705       int V2Idx = Mask[i / Scale] < Size
8706                       ? ZeroMask
8707                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8708       if (Zeroable[i / Scale])
8709         V1Idx = V2Idx = ZeroMask;
8710       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8711       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8712       V1InUse |= (ZeroMask != V1Idx);
8713       V2InUse |= (ZeroMask != V2Idx);
8714     }
8715   }
8716
8717   if (V1InUse)
8718     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8719                      DAG.getBitcast(MVT::v16i8, V1),
8720                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8721   if (V2InUse)
8722     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8723                      DAG.getBitcast(MVT::v16i8, V2),
8724                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8725
8726   // If we need shuffled inputs from both, blend the two.
8727   SDValue V;
8728   if (V1InUse && V2InUse)
8729     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8730   else
8731     V = V1InUse ? V1 : V2;
8732
8733   // Cast the result back to the correct type.
8734   return DAG.getBitcast(VT, V);
8735 }
8736
8737 /// \brief Generic lowering of 8-lane i16 shuffles.
8738 ///
8739 /// This handles both single-input shuffles and combined shuffle/blends with
8740 /// two inputs. The single input shuffles are immediately delegated to
8741 /// a dedicated lowering routine.
8742 ///
8743 /// The blends are lowered in one of three fundamental ways. If there are few
8744 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8745 /// of the input is significantly cheaper when lowered as an interleaving of
8746 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8747 /// halves of the inputs separately (making them have relatively few inputs)
8748 /// and then concatenate them.
8749 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8750                                        const X86Subtarget *Subtarget,
8751                                        SelectionDAG &DAG) {
8752   SDLoc DL(Op);
8753   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8754   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8755   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8756   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8757   ArrayRef<int> OrigMask = SVOp->getMask();
8758   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8759                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8760   MutableArrayRef<int> Mask(MaskStorage);
8761
8762   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8763
8764   // Whenever we can lower this as a zext, that instruction is strictly faster
8765   // than any alternative.
8766   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8767           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8768     return ZExt;
8769
8770   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8771   (void)isV1;
8772   auto isV2 = [](int M) { return M >= 8; };
8773
8774   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8775
8776   if (NumV2Inputs == 0) {
8777     // Check for being able to broadcast a single element.
8778     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8779                                                           Mask, Subtarget, DAG))
8780       return Broadcast;
8781
8782     // Try to use shift instructions.
8783     if (SDValue Shift =
8784             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8785       return Shift;
8786
8787     // Use dedicated unpack instructions for masks that match their pattern.
8788     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8789       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8790     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8791       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8792
8793     // Try to use byte rotation instructions.
8794     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8795                                                         Mask, Subtarget, DAG))
8796       return Rotate;
8797
8798     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8799                                                      Subtarget, DAG);
8800   }
8801
8802   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8803          "All single-input shuffles should be canonicalized to be V1-input "
8804          "shuffles.");
8805
8806   // Try to use shift instructions.
8807   if (SDValue Shift =
8808           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8809     return Shift;
8810
8811   // See if we can use SSE4A Extraction / Insertion.
8812   if (Subtarget->hasSSE4A())
8813     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8814       return V;
8815
8816   // There are special ways we can lower some single-element blends.
8817   if (NumV2Inputs == 1)
8818     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8819                                                          Mask, Subtarget, DAG))
8820       return V;
8821
8822   // We have different paths for blend lowering, but they all must use the
8823   // *exact* same predicate.
8824   bool IsBlendSupported = Subtarget->hasSSE41();
8825   if (IsBlendSupported)
8826     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8827                                                   Subtarget, DAG))
8828       return Blend;
8829
8830   if (SDValue Masked =
8831           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8832     return Masked;
8833
8834   // Use dedicated unpack instructions for masks that match their pattern.
8835   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8836     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8837   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8838     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8839
8840   // Try to use byte rotation instructions.
8841   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8842           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8843     return Rotate;
8844
8845   if (SDValue BitBlend =
8846           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8847     return BitBlend;
8848
8849   if (SDValue Unpack =
8850           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8851     return Unpack;
8852
8853   // If we can't directly blend but can use PSHUFB, that will be better as it
8854   // can both shuffle and set up the inefficient blend.
8855   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8856     bool V1InUse, V2InUse;
8857     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8858                                       V1InUse, V2InUse);
8859   }
8860
8861   // We can always bit-blend if we have to so the fallback strategy is to
8862   // decompose into single-input permutes and blends.
8863   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8864                                                       Mask, DAG);
8865 }
8866
8867 /// \brief Check whether a compaction lowering can be done by dropping even
8868 /// elements and compute how many times even elements must be dropped.
8869 ///
8870 /// This handles shuffles which take every Nth element where N is a power of
8871 /// two. Example shuffle masks:
8872 ///
8873 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8874 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8875 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8876 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8877 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8878 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8879 ///
8880 /// Any of these lanes can of course be undef.
8881 ///
8882 /// This routine only supports N <= 3.
8883 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8884 /// for larger N.
8885 ///
8886 /// \returns N above, or the number of times even elements must be dropped if
8887 /// there is such a number. Otherwise returns zero.
8888 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8889   // Figure out whether we're looping over two inputs or just one.
8890   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8891
8892   // The modulus for the shuffle vector entries is based on whether this is
8893   // a single input or not.
8894   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8895   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8896          "We should only be called with masks with a power-of-2 size!");
8897
8898   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8899
8900   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8901   // and 2^3 simultaneously. This is because we may have ambiguity with
8902   // partially undef inputs.
8903   bool ViableForN[3] = {true, true, true};
8904
8905   for (int i = 0, e = Mask.size(); i < e; ++i) {
8906     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8907     // want.
8908     if (Mask[i] == -1)
8909       continue;
8910
8911     bool IsAnyViable = false;
8912     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8913       if (ViableForN[j]) {
8914         uint64_t N = j + 1;
8915
8916         // The shuffle mask must be equal to (i * 2^N) % M.
8917         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8918           IsAnyViable = true;
8919         else
8920           ViableForN[j] = false;
8921       }
8922     // Early exit if we exhaust the possible powers of two.
8923     if (!IsAnyViable)
8924       break;
8925   }
8926
8927   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8928     if (ViableForN[j])
8929       return j + 1;
8930
8931   // Return 0 as there is no viable power of two.
8932   return 0;
8933 }
8934
8935 /// \brief Generic lowering of v16i8 shuffles.
8936 ///
8937 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8938 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8939 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8940 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8941 /// back together.
8942 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8943                                        const X86Subtarget *Subtarget,
8944                                        SelectionDAG &DAG) {
8945   SDLoc DL(Op);
8946   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8947   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8948   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8949   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8950   ArrayRef<int> Mask = SVOp->getMask();
8951   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8952
8953   // Try to use shift instructions.
8954   if (SDValue Shift =
8955           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8956     return Shift;
8957
8958   // Try to use byte rotation instructions.
8959   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8960           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8961     return Rotate;
8962
8963   // Try to use a zext lowering.
8964   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8965           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8966     return ZExt;
8967
8968   // See if we can use SSE4A Extraction / Insertion.
8969   if (Subtarget->hasSSE4A())
8970     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8971       return V;
8972
8973   int NumV2Elements =
8974       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8975
8976   // For single-input shuffles, there are some nicer lowering tricks we can use.
8977   if (NumV2Elements == 0) {
8978     // Check for being able to broadcast a single element.
8979     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8980                                                           Mask, Subtarget, DAG))
8981       return Broadcast;
8982
8983     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8984     // Notably, this handles splat and partial-splat shuffles more efficiently.
8985     // However, it only makes sense if the pre-duplication shuffle simplifies
8986     // things significantly. Currently, this means we need to be able to
8987     // express the pre-duplication shuffle as an i16 shuffle.
8988     //
8989     // FIXME: We should check for other patterns which can be widened into an
8990     // i16 shuffle as well.
8991     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8992       for (int i = 0; i < 16; i += 2)
8993         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8994           return false;
8995
8996       return true;
8997     };
8998     auto tryToWidenViaDuplication = [&]() -> SDValue {
8999       if (!canWidenViaDuplication(Mask))
9000         return SDValue();
9001       SmallVector<int, 4> LoInputs;
9002       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9003                    [](int M) { return M >= 0 && M < 8; });
9004       std::sort(LoInputs.begin(), LoInputs.end());
9005       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9006                      LoInputs.end());
9007       SmallVector<int, 4> HiInputs;
9008       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9009                    [](int M) { return M >= 8; });
9010       std::sort(HiInputs.begin(), HiInputs.end());
9011       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9012                      HiInputs.end());
9013
9014       bool TargetLo = LoInputs.size() >= HiInputs.size();
9015       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9016       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9017
9018       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9019       SmallDenseMap<int, int, 8> LaneMap;
9020       for (int I : InPlaceInputs) {
9021         PreDupI16Shuffle[I/2] = I/2;
9022         LaneMap[I] = I;
9023       }
9024       int j = TargetLo ? 0 : 4, je = j + 4;
9025       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9026         // Check if j is already a shuffle of this input. This happens when
9027         // there are two adjacent bytes after we move the low one.
9028         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9029           // If we haven't yet mapped the input, search for a slot into which
9030           // we can map it.
9031           while (j < je && PreDupI16Shuffle[j] != -1)
9032             ++j;
9033
9034           if (j == je)
9035             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9036             return SDValue();
9037
9038           // Map this input with the i16 shuffle.
9039           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9040         }
9041
9042         // Update the lane map based on the mapping we ended up with.
9043         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9044       }
9045       V1 = DAG.getBitcast(
9046           MVT::v16i8,
9047           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9048                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9049
9050       // Unpack the bytes to form the i16s that will be shuffled into place.
9051       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9052                        MVT::v16i8, V1, V1);
9053
9054       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9055       for (int i = 0; i < 16; ++i)
9056         if (Mask[i] != -1) {
9057           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9058           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9059           if (PostDupI16Shuffle[i / 2] == -1)
9060             PostDupI16Shuffle[i / 2] = MappedMask;
9061           else
9062             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9063                    "Conflicting entrties in the original shuffle!");
9064         }
9065       return DAG.getBitcast(
9066           MVT::v16i8,
9067           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9068                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9069     };
9070     if (SDValue V = tryToWidenViaDuplication())
9071       return V;
9072   }
9073
9074   // Use dedicated unpack instructions for masks that match their pattern.
9075   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9076                                          0, 16, 1, 17, 2, 18, 3, 19,
9077                                          // High half.
9078                                          4, 20, 5, 21, 6, 22, 7, 23}))
9079     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9080   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9081                                          8, 24, 9, 25, 10, 26, 11, 27,
9082                                          // High half.
9083                                          12, 28, 13, 29, 14, 30, 15, 31}))
9084     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9085
9086   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9087   // with PSHUFB. It is important to do this before we attempt to generate any
9088   // blends but after all of the single-input lowerings. If the single input
9089   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9090   // want to preserve that and we can DAG combine any longer sequences into
9091   // a PSHUFB in the end. But once we start blending from multiple inputs,
9092   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9093   // and there are *very* few patterns that would actually be faster than the
9094   // PSHUFB approach because of its ability to zero lanes.
9095   //
9096   // FIXME: The only exceptions to the above are blends which are exact
9097   // interleavings with direct instructions supporting them. We currently don't
9098   // handle those well here.
9099   if (Subtarget->hasSSSE3()) {
9100     bool V1InUse = false;
9101     bool V2InUse = false;
9102
9103     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9104                                                 DAG, V1InUse, V2InUse);
9105
9106     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9107     // do so. This avoids using them to handle blends-with-zero which is
9108     // important as a single pshufb is significantly faster for that.
9109     if (V1InUse && V2InUse) {
9110       if (Subtarget->hasSSE41())
9111         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9112                                                       Mask, Subtarget, DAG))
9113           return Blend;
9114
9115       // We can use an unpack to do the blending rather than an or in some
9116       // cases. Even though the or may be (very minorly) more efficient, we
9117       // preference this lowering because there are common cases where part of
9118       // the complexity of the shuffles goes away when we do the final blend as
9119       // an unpack.
9120       // FIXME: It might be worth trying to detect if the unpack-feeding
9121       // shuffles will both be pshufb, in which case we shouldn't bother with
9122       // this.
9123       if (SDValue Unpack =
9124               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9125         return Unpack;
9126     }
9127
9128     return PSHUFB;
9129   }
9130
9131   // There are special ways we can lower some single-element blends.
9132   if (NumV2Elements == 1)
9133     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9134                                                          Mask, Subtarget, DAG))
9135       return V;
9136
9137   if (SDValue BitBlend =
9138           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9139     return BitBlend;
9140
9141   // Check whether a compaction lowering can be done. This handles shuffles
9142   // which take every Nth element for some even N. See the helper function for
9143   // details.
9144   //
9145   // We special case these as they can be particularly efficiently handled with
9146   // the PACKUSB instruction on x86 and they show up in common patterns of
9147   // rearranging bytes to truncate wide elements.
9148   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9149     // NumEvenDrops is the power of two stride of the elements. Another way of
9150     // thinking about it is that we need to drop the even elements this many
9151     // times to get the original input.
9152     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9153
9154     // First we need to zero all the dropped bytes.
9155     assert(NumEvenDrops <= 3 &&
9156            "No support for dropping even elements more than 3 times.");
9157     // We use the mask type to pick which bytes are preserved based on how many
9158     // elements are dropped.
9159     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9160     SDValue ByteClearMask = DAG.getBitcast(
9161         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9162     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9163     if (!IsSingleInput)
9164       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9165
9166     // Now pack things back together.
9167     V1 = DAG.getBitcast(MVT::v8i16, V1);
9168     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9169     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9170     for (int i = 1; i < NumEvenDrops; ++i) {
9171       Result = DAG.getBitcast(MVT::v8i16, Result);
9172       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9173     }
9174
9175     return Result;
9176   }
9177
9178   // Handle multi-input cases by blending single-input shuffles.
9179   if (NumV2Elements > 0)
9180     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9181                                                       Mask, DAG);
9182
9183   // The fallback path for single-input shuffles widens this into two v8i16
9184   // vectors with unpacks, shuffles those, and then pulls them back together
9185   // with a pack.
9186   SDValue V = V1;
9187
9188   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9189   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9190   for (int i = 0; i < 16; ++i)
9191     if (Mask[i] >= 0)
9192       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9193
9194   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9195
9196   SDValue VLoHalf, VHiHalf;
9197   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9198   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9199   // i16s.
9200   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9201                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9202       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9203                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9204     // Use a mask to drop the high bytes.
9205     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9206     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9207                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9208
9209     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9210     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9211
9212     // Squash the masks to point directly into VLoHalf.
9213     for (int &M : LoBlendMask)
9214       if (M >= 0)
9215         M /= 2;
9216     for (int &M : HiBlendMask)
9217       if (M >= 0)
9218         M /= 2;
9219   } else {
9220     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9221     // VHiHalf so that we can blend them as i16s.
9222     VLoHalf = DAG.getBitcast(
9223         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9224     VHiHalf = DAG.getBitcast(
9225         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9226   }
9227
9228   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9229   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9230
9231   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9232 }
9233
9234 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9235 ///
9236 /// This routine breaks down the specific type of 128-bit shuffle and
9237 /// dispatches to the lowering routines accordingly.
9238 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9239                                         MVT VT, const X86Subtarget *Subtarget,
9240                                         SelectionDAG &DAG) {
9241   switch (VT.SimpleTy) {
9242   case MVT::v2i64:
9243     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9244   case MVT::v2f64:
9245     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9246   case MVT::v4i32:
9247     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9248   case MVT::v4f32:
9249     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9250   case MVT::v8i16:
9251     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9252   case MVT::v16i8:
9253     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9254
9255   default:
9256     llvm_unreachable("Unimplemented!");
9257   }
9258 }
9259
9260 /// \brief Helper function to test whether a shuffle mask could be
9261 /// simplified by widening the elements being shuffled.
9262 ///
9263 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9264 /// leaves it in an unspecified state.
9265 ///
9266 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9267 /// shuffle masks. The latter have the special property of a '-2' representing
9268 /// a zero-ed lane of a vector.
9269 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9270                                     SmallVectorImpl<int> &WidenedMask) {
9271   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9272     // If both elements are undef, its trivial.
9273     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9274       WidenedMask.push_back(SM_SentinelUndef);
9275       continue;
9276     }
9277
9278     // Check for an undef mask and a mask value properly aligned to fit with
9279     // a pair of values. If we find such a case, use the non-undef mask's value.
9280     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9281       WidenedMask.push_back(Mask[i + 1] / 2);
9282       continue;
9283     }
9284     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9285       WidenedMask.push_back(Mask[i] / 2);
9286       continue;
9287     }
9288
9289     // When zeroing, we need to spread the zeroing across both lanes to widen.
9290     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9291       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9292           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9293         WidenedMask.push_back(SM_SentinelZero);
9294         continue;
9295       }
9296       return false;
9297     }
9298
9299     // Finally check if the two mask values are adjacent and aligned with
9300     // a pair.
9301     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9302       WidenedMask.push_back(Mask[i] / 2);
9303       continue;
9304     }
9305
9306     // Otherwise we can't safely widen the elements used in this shuffle.
9307     return false;
9308   }
9309   assert(WidenedMask.size() == Mask.size() / 2 &&
9310          "Incorrect size of mask after widening the elements!");
9311
9312   return true;
9313 }
9314
9315 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9316 ///
9317 /// This routine just extracts two subvectors, shuffles them independently, and
9318 /// then concatenates them back together. This should work effectively with all
9319 /// AVX vector shuffle types.
9320 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9321                                           SDValue V2, ArrayRef<int> Mask,
9322                                           SelectionDAG &DAG) {
9323   assert(VT.getSizeInBits() >= 256 &&
9324          "Only for 256-bit or wider vector shuffles!");
9325   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9326   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9327
9328   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9329   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9330
9331   int NumElements = VT.getVectorNumElements();
9332   int SplitNumElements = NumElements / 2;
9333   MVT ScalarVT = VT.getScalarType();
9334   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9335
9336   // Rather than splitting build-vectors, just build two narrower build
9337   // vectors. This helps shuffling with splats and zeros.
9338   auto SplitVector = [&](SDValue V) {
9339     while (V.getOpcode() == ISD::BITCAST)
9340       V = V->getOperand(0);
9341
9342     MVT OrigVT = V.getSimpleValueType();
9343     int OrigNumElements = OrigVT.getVectorNumElements();
9344     int OrigSplitNumElements = OrigNumElements / 2;
9345     MVT OrigScalarVT = OrigVT.getScalarType();
9346     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9347
9348     SDValue LoV, HiV;
9349
9350     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9351     if (!BV) {
9352       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9353                         DAG.getIntPtrConstant(0, DL));
9354       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9355                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9356     } else {
9357
9358       SmallVector<SDValue, 16> LoOps, HiOps;
9359       for (int i = 0; i < OrigSplitNumElements; ++i) {
9360         LoOps.push_back(BV->getOperand(i));
9361         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9362       }
9363       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9364       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9365     }
9366     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9367                           DAG.getBitcast(SplitVT, HiV));
9368   };
9369
9370   SDValue LoV1, HiV1, LoV2, HiV2;
9371   std::tie(LoV1, HiV1) = SplitVector(V1);
9372   std::tie(LoV2, HiV2) = SplitVector(V2);
9373
9374   // Now create two 4-way blends of these half-width vectors.
9375   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9376     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9377     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9378     for (int i = 0; i < SplitNumElements; ++i) {
9379       int M = HalfMask[i];
9380       if (M >= NumElements) {
9381         if (M >= NumElements + SplitNumElements)
9382           UseHiV2 = true;
9383         else
9384           UseLoV2 = true;
9385         V2BlendMask.push_back(M - NumElements);
9386         V1BlendMask.push_back(-1);
9387         BlendMask.push_back(SplitNumElements + i);
9388       } else if (M >= 0) {
9389         if (M >= SplitNumElements)
9390           UseHiV1 = true;
9391         else
9392           UseLoV1 = true;
9393         V2BlendMask.push_back(-1);
9394         V1BlendMask.push_back(M);
9395         BlendMask.push_back(i);
9396       } else {
9397         V2BlendMask.push_back(-1);
9398         V1BlendMask.push_back(-1);
9399         BlendMask.push_back(-1);
9400       }
9401     }
9402
9403     // Because the lowering happens after all combining takes place, we need to
9404     // manually combine these blend masks as much as possible so that we create
9405     // a minimal number of high-level vector shuffle nodes.
9406
9407     // First try just blending the halves of V1 or V2.
9408     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9409       return DAG.getUNDEF(SplitVT);
9410     if (!UseLoV2 && !UseHiV2)
9411       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9412     if (!UseLoV1 && !UseHiV1)
9413       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9414
9415     SDValue V1Blend, V2Blend;
9416     if (UseLoV1 && UseHiV1) {
9417       V1Blend =
9418         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9419     } else {
9420       // We only use half of V1 so map the usage down into the final blend mask.
9421       V1Blend = UseLoV1 ? LoV1 : HiV1;
9422       for (int i = 0; i < SplitNumElements; ++i)
9423         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9424           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9425     }
9426     if (UseLoV2 && UseHiV2) {
9427       V2Blend =
9428         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9429     } else {
9430       // We only use half of V2 so map the usage down into the final blend mask.
9431       V2Blend = UseLoV2 ? LoV2 : HiV2;
9432       for (int i = 0; i < SplitNumElements; ++i)
9433         if (BlendMask[i] >= SplitNumElements)
9434           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9435     }
9436     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9437   };
9438   SDValue Lo = HalfBlend(LoMask);
9439   SDValue Hi = HalfBlend(HiMask);
9440   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9441 }
9442
9443 /// \brief Either split a vector in halves or decompose the shuffles and the
9444 /// blend.
9445 ///
9446 /// This is provided as a good fallback for many lowerings of non-single-input
9447 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9448 /// between splitting the shuffle into 128-bit components and stitching those
9449 /// back together vs. extracting the single-input shuffles and blending those
9450 /// results.
9451 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9452                                                 SDValue V2, ArrayRef<int> Mask,
9453                                                 SelectionDAG &DAG) {
9454   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9455                                             "lower single-input shuffles as it "
9456                                             "could then recurse on itself.");
9457   int Size = Mask.size();
9458
9459   // If this can be modeled as a broadcast of two elements followed by a blend,
9460   // prefer that lowering. This is especially important because broadcasts can
9461   // often fold with memory operands.
9462   auto DoBothBroadcast = [&] {
9463     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9464     for (int M : Mask)
9465       if (M >= Size) {
9466         if (V2BroadcastIdx == -1)
9467           V2BroadcastIdx = M - Size;
9468         else if (M - Size != V2BroadcastIdx)
9469           return false;
9470       } else if (M >= 0) {
9471         if (V1BroadcastIdx == -1)
9472           V1BroadcastIdx = M;
9473         else if (M != V1BroadcastIdx)
9474           return false;
9475       }
9476     return true;
9477   };
9478   if (DoBothBroadcast())
9479     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9480                                                       DAG);
9481
9482   // If the inputs all stem from a single 128-bit lane of each input, then we
9483   // split them rather than blending because the split will decompose to
9484   // unusually few instructions.
9485   int LaneCount = VT.getSizeInBits() / 128;
9486   int LaneSize = Size / LaneCount;
9487   SmallBitVector LaneInputs[2];
9488   LaneInputs[0].resize(LaneCount, false);
9489   LaneInputs[1].resize(LaneCount, false);
9490   for (int i = 0; i < Size; ++i)
9491     if (Mask[i] >= 0)
9492       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9493   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9494     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9495
9496   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9497   // that the decomposed single-input shuffles don't end up here.
9498   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9499 }
9500
9501 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9502 /// a permutation and blend of those lanes.
9503 ///
9504 /// This essentially blends the out-of-lane inputs to each lane into the lane
9505 /// from a permuted copy of the vector. This lowering strategy results in four
9506 /// instructions in the worst case for a single-input cross lane shuffle which
9507 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9508 /// of. Special cases for each particular shuffle pattern should be handled
9509 /// prior to trying this lowering.
9510 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9511                                                        SDValue V1, SDValue V2,
9512                                                        ArrayRef<int> Mask,
9513                                                        SelectionDAG &DAG) {
9514   // FIXME: This should probably be generalized for 512-bit vectors as well.
9515   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9516   int LaneSize = Mask.size() / 2;
9517
9518   // If there are only inputs from one 128-bit lane, splitting will in fact be
9519   // less expensive. The flags track whether the given lane contains an element
9520   // that crosses to another lane.
9521   bool LaneCrossing[2] = {false, false};
9522   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9523     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9524       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9525   if (!LaneCrossing[0] || !LaneCrossing[1])
9526     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9527
9528   if (isSingleInputShuffleMask(Mask)) {
9529     SmallVector<int, 32> FlippedBlendMask;
9530     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9531       FlippedBlendMask.push_back(
9532           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9533                                   ? Mask[i]
9534                                   : Mask[i] % LaneSize +
9535                                         (i / LaneSize) * LaneSize + Size));
9536
9537     // Flip the vector, and blend the results which should now be in-lane. The
9538     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9539     // 5 for the high source. The value 3 selects the high half of source 2 and
9540     // the value 2 selects the low half of source 2. We only use source 2 to
9541     // allow folding it into a memory operand.
9542     unsigned PERMMask = 3 | 2 << 4;
9543     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9544                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9545     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9546   }
9547
9548   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9549   // will be handled by the above logic and a blend of the results, much like
9550   // other patterns in AVX.
9551   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9552 }
9553
9554 /// \brief Handle lowering 2-lane 128-bit shuffles.
9555 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9556                                         SDValue V2, ArrayRef<int> Mask,
9557                                         const X86Subtarget *Subtarget,
9558                                         SelectionDAG &DAG) {
9559   // TODO: If minimizing size and one of the inputs is a zero vector and the
9560   // the zero vector has only one use, we could use a VPERM2X128 to save the
9561   // instruction bytes needed to explicitly generate the zero vector.
9562
9563   // Blends are faster and handle all the non-lane-crossing cases.
9564   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9565                                                 Subtarget, DAG))
9566     return Blend;
9567
9568   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9569   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9570
9571   // If either input operand is a zero vector, use VPERM2X128 because its mask
9572   // allows us to replace the zero input with an implicit zero.
9573   if (!IsV1Zero && !IsV2Zero) {
9574     // Check for patterns which can be matched with a single insert of a 128-bit
9575     // subvector.
9576     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9577     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9578       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9579                                    VT.getVectorNumElements() / 2);
9580       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9581                                 DAG.getIntPtrConstant(0, DL));
9582       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9583                                 OnlyUsesV1 ? V1 : V2,
9584                                 DAG.getIntPtrConstant(0, DL));
9585       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9586     }
9587   }
9588
9589   // Otherwise form a 128-bit permutation. After accounting for undefs,
9590   // convert the 64-bit shuffle mask selection values into 128-bit
9591   // selection bits by dividing the indexes by 2 and shifting into positions
9592   // defined by a vperm2*128 instruction's immediate control byte.
9593
9594   // The immediate permute control byte looks like this:
9595   //    [1:0] - select 128 bits from sources for low half of destination
9596   //    [2]   - ignore
9597   //    [3]   - zero low half of destination
9598   //    [5:4] - select 128 bits from sources for high half of destination
9599   //    [6]   - ignore
9600   //    [7]   - zero high half of destination
9601
9602   int MaskLO = Mask[0];
9603   if (MaskLO == SM_SentinelUndef)
9604     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9605
9606   int MaskHI = Mask[2];
9607   if (MaskHI == SM_SentinelUndef)
9608     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9609
9610   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9611
9612   // If either input is a zero vector, replace it with an undef input.
9613   // Shuffle mask values <  4 are selecting elements of V1.
9614   // Shuffle mask values >= 4 are selecting elements of V2.
9615   // Adjust each half of the permute mask by clearing the half that was
9616   // selecting the zero vector and setting the zero mask bit.
9617   if (IsV1Zero) {
9618     V1 = DAG.getUNDEF(VT);
9619     if (MaskLO < 4)
9620       PermMask = (PermMask & 0xf0) | 0x08;
9621     if (MaskHI < 4)
9622       PermMask = (PermMask & 0x0f) | 0x80;
9623   }
9624   if (IsV2Zero) {
9625     V2 = DAG.getUNDEF(VT);
9626     if (MaskLO >= 4)
9627       PermMask = (PermMask & 0xf0) | 0x08;
9628     if (MaskHI >= 4)
9629       PermMask = (PermMask & 0x0f) | 0x80;
9630   }
9631
9632   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9633                      DAG.getConstant(PermMask, DL, MVT::i8));
9634 }
9635
9636 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9637 /// shuffling each lane.
9638 ///
9639 /// This will only succeed when the result of fixing the 128-bit lanes results
9640 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9641 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9642 /// the lane crosses early and then use simpler shuffles within each lane.
9643 ///
9644 /// FIXME: It might be worthwhile at some point to support this without
9645 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9646 /// in x86 only floating point has interesting non-repeating shuffles, and even
9647 /// those are still *marginally* more expensive.
9648 static SDValue lowerVectorShuffleByMerging128BitLanes(
9649     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9650     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9651   assert(!isSingleInputShuffleMask(Mask) &&
9652          "This is only useful with multiple inputs.");
9653
9654   int Size = Mask.size();
9655   int LaneSize = 128 / VT.getScalarSizeInBits();
9656   int NumLanes = Size / LaneSize;
9657   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9658
9659   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9660   // check whether the in-128-bit lane shuffles share a repeating pattern.
9661   SmallVector<int, 4> Lanes;
9662   Lanes.resize(NumLanes, -1);
9663   SmallVector<int, 4> InLaneMask;
9664   InLaneMask.resize(LaneSize, -1);
9665   for (int i = 0; i < Size; ++i) {
9666     if (Mask[i] < 0)
9667       continue;
9668
9669     int j = i / LaneSize;
9670
9671     if (Lanes[j] < 0) {
9672       // First entry we've seen for this lane.
9673       Lanes[j] = Mask[i] / LaneSize;
9674     } else if (Lanes[j] != Mask[i] / LaneSize) {
9675       // This doesn't match the lane selected previously!
9676       return SDValue();
9677     }
9678
9679     // Check that within each lane we have a consistent shuffle mask.
9680     int k = i % LaneSize;
9681     if (InLaneMask[k] < 0) {
9682       InLaneMask[k] = Mask[i] % LaneSize;
9683     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9684       // This doesn't fit a repeating in-lane mask.
9685       return SDValue();
9686     }
9687   }
9688
9689   // First shuffle the lanes into place.
9690   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9691                                 VT.getSizeInBits() / 64);
9692   SmallVector<int, 8> LaneMask;
9693   LaneMask.resize(NumLanes * 2, -1);
9694   for (int i = 0; i < NumLanes; ++i)
9695     if (Lanes[i] >= 0) {
9696       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9697       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9698     }
9699
9700   V1 = DAG.getBitcast(LaneVT, V1);
9701   V2 = DAG.getBitcast(LaneVT, V2);
9702   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9703
9704   // Cast it back to the type we actually want.
9705   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9706
9707   // Now do a simple shuffle that isn't lane crossing.
9708   SmallVector<int, 8> NewMask;
9709   NewMask.resize(Size, -1);
9710   for (int i = 0; i < Size; ++i)
9711     if (Mask[i] >= 0)
9712       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9713   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9714          "Must not introduce lane crosses at this point!");
9715
9716   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9717 }
9718
9719 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9720 /// given mask.
9721 ///
9722 /// This returns true if the elements from a particular input are already in the
9723 /// slot required by the given mask and require no permutation.
9724 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9725   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9726   int Size = Mask.size();
9727   for (int i = 0; i < Size; ++i)
9728     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9729       return false;
9730
9731   return true;
9732 }
9733
9734 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9735                                             ArrayRef<int> Mask, SDValue V1,
9736                                             SDValue V2, SelectionDAG &DAG) {
9737
9738   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9739   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9740   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9741   int NumElts = VT.getVectorNumElements();
9742   bool ShufpdMask = true;
9743   bool CommutableMask = true;
9744   unsigned Immediate = 0;
9745   for (int i = 0; i < NumElts; ++i) {
9746     if (Mask[i] < 0)
9747       continue;
9748     int Val = (i & 6) + NumElts * (i & 1);
9749     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9750     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9751       ShufpdMask = false;
9752     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9753       CommutableMask = false;
9754     Immediate |= (Mask[i] % 2) << i;
9755   }
9756   if (ShufpdMask)
9757     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9758                        DAG.getConstant(Immediate, DL, MVT::i8));
9759   if (CommutableMask)
9760     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9761                        DAG.getConstant(Immediate, DL, MVT::i8));
9762   return SDValue();
9763 }
9764
9765 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9766 ///
9767 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9768 /// isn't available.
9769 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9770                                        const X86Subtarget *Subtarget,
9771                                        SelectionDAG &DAG) {
9772   SDLoc DL(Op);
9773   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9774   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9775   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9776   ArrayRef<int> Mask = SVOp->getMask();
9777   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9778
9779   SmallVector<int, 4> WidenedMask;
9780   if (canWidenShuffleElements(Mask, WidenedMask))
9781     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9782                                     DAG);
9783
9784   if (isSingleInputShuffleMask(Mask)) {
9785     // Check for being able to broadcast a single element.
9786     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9787                                                           Mask, Subtarget, DAG))
9788       return Broadcast;
9789
9790     // Use low duplicate instructions for masks that match their pattern.
9791     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9792       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9793
9794     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9795       // Non-half-crossing single input shuffles can be lowerid with an
9796       // interleaved permutation.
9797       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9798                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9799       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9800                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9801     }
9802
9803     // With AVX2 we have direct support for this permutation.
9804     if (Subtarget->hasAVX2())
9805       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9806                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9807
9808     // Otherwise, fall back.
9809     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9810                                                    DAG);
9811   }
9812
9813   // X86 has dedicated unpack instructions that can handle specific blend
9814   // operations: UNPCKH and UNPCKL.
9815   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9816     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9817   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9818     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9819   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9820     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9821   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9822     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9823
9824   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9825                                                 Subtarget, DAG))
9826     return Blend;
9827
9828   // Check if the blend happens to exactly fit that of SHUFPD.
9829   if (SDValue Op =
9830       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9831     return Op;
9832
9833   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9834   // shuffle. However, if we have AVX2 and either inputs are already in place,
9835   // we will be able to shuffle even across lanes the other input in a single
9836   // instruction so skip this pattern.
9837   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9838                                  isShuffleMaskInputInPlace(1, Mask))))
9839     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9840             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9841       return Result;
9842
9843   // If we have AVX2 then we always want to lower with a blend because an v4 we
9844   // can fully permute the elements.
9845   if (Subtarget->hasAVX2())
9846     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9847                                                       Mask, DAG);
9848
9849   // Otherwise fall back on generic lowering.
9850   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9851 }
9852
9853 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9854 ///
9855 /// This routine is only called when we have AVX2 and thus a reasonable
9856 /// instruction set for v4i64 shuffling..
9857 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9858                                        const X86Subtarget *Subtarget,
9859                                        SelectionDAG &DAG) {
9860   SDLoc DL(Op);
9861   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9862   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9863   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9864   ArrayRef<int> Mask = SVOp->getMask();
9865   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9866   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9867
9868   SmallVector<int, 4> WidenedMask;
9869   if (canWidenShuffleElements(Mask, WidenedMask))
9870     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9871                                     DAG);
9872
9873   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9874                                                 Subtarget, DAG))
9875     return Blend;
9876
9877   // Check for being able to broadcast a single element.
9878   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9879                                                         Mask, Subtarget, DAG))
9880     return Broadcast;
9881
9882   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9883   // use lower latency instructions that will operate on both 128-bit lanes.
9884   SmallVector<int, 2> RepeatedMask;
9885   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9886     if (isSingleInputShuffleMask(Mask)) {
9887       int PSHUFDMask[] = {-1, -1, -1, -1};
9888       for (int i = 0; i < 2; ++i)
9889         if (RepeatedMask[i] >= 0) {
9890           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9891           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9892         }
9893       return DAG.getBitcast(
9894           MVT::v4i64,
9895           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9896                       DAG.getBitcast(MVT::v8i32, V1),
9897                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9898     }
9899   }
9900
9901   // AVX2 provides a direct instruction for permuting a single input across
9902   // lanes.
9903   if (isSingleInputShuffleMask(Mask))
9904     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9905                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9906
9907   // Try to use shift instructions.
9908   if (SDValue Shift =
9909           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9910     return Shift;
9911
9912   // Use dedicated unpack instructions for masks that match their pattern.
9913   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9914     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9915   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9916     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9917   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9918     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9919   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9920     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9921
9922   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9923   // shuffle. However, if we have AVX2 and either inputs are already in place,
9924   // we will be able to shuffle even across lanes the other input in a single
9925   // instruction so skip this pattern.
9926   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9927                                  isShuffleMaskInputInPlace(1, Mask))))
9928     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9929             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9930       return Result;
9931
9932   // Otherwise fall back on generic blend lowering.
9933   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9934                                                     Mask, DAG);
9935 }
9936
9937 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9938 ///
9939 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9940 /// isn't available.
9941 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9942                                        const X86Subtarget *Subtarget,
9943                                        SelectionDAG &DAG) {
9944   SDLoc DL(Op);
9945   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9946   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9947   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9948   ArrayRef<int> Mask = SVOp->getMask();
9949   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9950
9951   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9952                                                 Subtarget, DAG))
9953     return Blend;
9954
9955   // Check for being able to broadcast a single element.
9956   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9957                                                         Mask, Subtarget, DAG))
9958     return Broadcast;
9959
9960   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9961   // options to efficiently lower the shuffle.
9962   SmallVector<int, 4> RepeatedMask;
9963   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9964     assert(RepeatedMask.size() == 4 &&
9965            "Repeated masks must be half the mask width!");
9966
9967     // Use even/odd duplicate instructions for masks that match their pattern.
9968     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9969       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9970     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9971       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9972
9973     if (isSingleInputShuffleMask(Mask))
9974       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9975                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9976
9977     // Use dedicated unpack instructions for masks that match their pattern.
9978     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9979       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9980     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9981       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9982     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9983       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9984     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9985       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9986
9987     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9988     // have already handled any direct blends. We also need to squash the
9989     // repeated mask into a simulated v4f32 mask.
9990     for (int i = 0; i < 4; ++i)
9991       if (RepeatedMask[i] >= 8)
9992         RepeatedMask[i] -= 4;
9993     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9994   }
9995
9996   // If we have a single input shuffle with different shuffle patterns in the
9997   // two 128-bit lanes use the variable mask to VPERMILPS.
9998   if (isSingleInputShuffleMask(Mask)) {
9999     SDValue VPermMask[8];
10000     for (int i = 0; i < 8; ++i)
10001       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10002                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10003     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10004       return DAG.getNode(
10005           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10006           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10007
10008     if (Subtarget->hasAVX2())
10009       return DAG.getNode(
10010           X86ISD::VPERMV, DL, MVT::v8f32,
10011           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10012                                                  MVT::v8i32, VPermMask)),
10013           V1);
10014
10015     // Otherwise, fall back.
10016     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10017                                                    DAG);
10018   }
10019
10020   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10021   // shuffle.
10022   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10023           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10024     return Result;
10025
10026   // If we have AVX2 then we always want to lower with a blend because at v8 we
10027   // can fully permute the elements.
10028   if (Subtarget->hasAVX2())
10029     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10030                                                       Mask, DAG);
10031
10032   // Otherwise fall back on generic lowering.
10033   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10034 }
10035
10036 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10037 ///
10038 /// This routine is only called when we have AVX2 and thus a reasonable
10039 /// instruction set for v8i32 shuffling..
10040 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10041                                        const X86Subtarget *Subtarget,
10042                                        SelectionDAG &DAG) {
10043   SDLoc DL(Op);
10044   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10045   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10046   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10047   ArrayRef<int> Mask = SVOp->getMask();
10048   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10049   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10050
10051   // Whenever we can lower this as a zext, that instruction is strictly faster
10052   // than any alternative. It also allows us to fold memory operands into the
10053   // shuffle in many cases.
10054   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10055                                                          Mask, Subtarget, DAG))
10056     return ZExt;
10057
10058   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10059                                                 Subtarget, DAG))
10060     return Blend;
10061
10062   // Check for being able to broadcast a single element.
10063   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10064                                                         Mask, Subtarget, DAG))
10065     return Broadcast;
10066
10067   // If the shuffle mask is repeated in each 128-bit lane we can use more
10068   // efficient instructions that mirror the shuffles across the two 128-bit
10069   // lanes.
10070   SmallVector<int, 4> RepeatedMask;
10071   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10072     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10073     if (isSingleInputShuffleMask(Mask))
10074       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10075                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10076
10077     // Use dedicated unpack instructions for masks that match their pattern.
10078     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10079       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10080     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10081       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10082     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10083       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10084     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10085       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10086   }
10087
10088   // Try to use shift instructions.
10089   if (SDValue Shift =
10090           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10091     return Shift;
10092
10093   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10094           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10095     return Rotate;
10096
10097   // If the shuffle patterns aren't repeated but it is a single input, directly
10098   // generate a cross-lane VPERMD instruction.
10099   if (isSingleInputShuffleMask(Mask)) {
10100     SDValue VPermMask[8];
10101     for (int i = 0; i < 8; ++i)
10102       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10103                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10104     return DAG.getNode(
10105         X86ISD::VPERMV, DL, MVT::v8i32,
10106         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10107   }
10108
10109   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10110   // shuffle.
10111   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10112           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10113     return Result;
10114
10115   // Otherwise fall back on generic blend lowering.
10116   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10117                                                     Mask, DAG);
10118 }
10119
10120 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10121 ///
10122 /// This routine is only called when we have AVX2 and thus a reasonable
10123 /// instruction set for v16i16 shuffling..
10124 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10125                                         const X86Subtarget *Subtarget,
10126                                         SelectionDAG &DAG) {
10127   SDLoc DL(Op);
10128   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10129   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10130   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10131   ArrayRef<int> Mask = SVOp->getMask();
10132   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10133   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10134
10135   // Whenever we can lower this as a zext, that instruction is strictly faster
10136   // than any alternative. It also allows us to fold memory operands into the
10137   // shuffle in many cases.
10138   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10139                                                          Mask, Subtarget, DAG))
10140     return ZExt;
10141
10142   // Check for being able to broadcast a single element.
10143   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10144                                                         Mask, Subtarget, DAG))
10145     return Broadcast;
10146
10147   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10148                                                 Subtarget, DAG))
10149     return Blend;
10150
10151   // Use dedicated unpack instructions for masks that match their pattern.
10152   if (isShuffleEquivalent(V1, V2, Mask,
10153                           {// First 128-bit lane:
10154                            0, 16, 1, 17, 2, 18, 3, 19,
10155                            // Second 128-bit lane:
10156                            8, 24, 9, 25, 10, 26, 11, 27}))
10157     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10158   if (isShuffleEquivalent(V1, V2, Mask,
10159                           {// First 128-bit lane:
10160                            4, 20, 5, 21, 6, 22, 7, 23,
10161                            // Second 128-bit lane:
10162                            12, 28, 13, 29, 14, 30, 15, 31}))
10163     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10164
10165   // Try to use shift instructions.
10166   if (SDValue Shift =
10167           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10168     return Shift;
10169
10170   // Try to use byte rotation instructions.
10171   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10172           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10173     return Rotate;
10174
10175   if (isSingleInputShuffleMask(Mask)) {
10176     // There are no generalized cross-lane shuffle operations available on i16
10177     // element types.
10178     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10179       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10180                                                      Mask, DAG);
10181
10182     SmallVector<int, 8> RepeatedMask;
10183     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10184       // As this is a single-input shuffle, the repeated mask should be
10185       // a strictly valid v8i16 mask that we can pass through to the v8i16
10186       // lowering to handle even the v16 case.
10187       return lowerV8I16GeneralSingleInputVectorShuffle(
10188           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10189     }
10190
10191     SDValue PSHUFBMask[32];
10192     for (int i = 0; i < 16; ++i) {
10193       if (Mask[i] == -1) {
10194         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10195         continue;
10196       }
10197
10198       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10199       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10200       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10201       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10202     }
10203     return DAG.getBitcast(MVT::v16i16,
10204                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10205                                       DAG.getBitcast(MVT::v32i8, V1),
10206                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10207                                                   MVT::v32i8, PSHUFBMask)));
10208   }
10209
10210   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10211   // shuffle.
10212   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10213           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10214     return Result;
10215
10216   // Otherwise fall back on generic lowering.
10217   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10218 }
10219
10220 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10221 ///
10222 /// This routine is only called when we have AVX2 and thus a reasonable
10223 /// instruction set for v32i8 shuffling..
10224 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10225                                        const X86Subtarget *Subtarget,
10226                                        SelectionDAG &DAG) {
10227   SDLoc DL(Op);
10228   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10229   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10230   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10231   ArrayRef<int> Mask = SVOp->getMask();
10232   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10233   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10234
10235   // Whenever we can lower this as a zext, that instruction is strictly faster
10236   // than any alternative. It also allows us to fold memory operands into the
10237   // shuffle in many cases.
10238   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10239                                                          Mask, Subtarget, DAG))
10240     return ZExt;
10241
10242   // Check for being able to broadcast a single element.
10243   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10244                                                         Mask, Subtarget, DAG))
10245     return Broadcast;
10246
10247   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10248                                                 Subtarget, DAG))
10249     return Blend;
10250
10251   // Use dedicated unpack instructions for masks that match their pattern.
10252   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10253   // 256-bit lanes.
10254   if (isShuffleEquivalent(
10255           V1, V2, Mask,
10256           {// First 128-bit lane:
10257            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10258            // Second 128-bit lane:
10259            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10260     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10261   if (isShuffleEquivalent(
10262           V1, V2, Mask,
10263           {// First 128-bit lane:
10264            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10265            // Second 128-bit lane:
10266            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10267     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10268
10269   // Try to use shift instructions.
10270   if (SDValue Shift =
10271           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10272     return Shift;
10273
10274   // Try to use byte rotation instructions.
10275   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10276           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10277     return Rotate;
10278
10279   if (isSingleInputShuffleMask(Mask)) {
10280     // There are no generalized cross-lane shuffle operations available on i8
10281     // element types.
10282     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10283       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10284                                                      Mask, DAG);
10285
10286     SDValue PSHUFBMask[32];
10287     for (int i = 0; i < 32; ++i)
10288       PSHUFBMask[i] =
10289           Mask[i] < 0
10290               ? DAG.getUNDEF(MVT::i8)
10291               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10292                                 MVT::i8);
10293
10294     return DAG.getNode(
10295         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10296         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10297   }
10298
10299   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10300   // shuffle.
10301   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10302           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10303     return Result;
10304
10305   // Otherwise fall back on generic lowering.
10306   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10307 }
10308
10309 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10310 ///
10311 /// This routine either breaks down the specific type of a 256-bit x86 vector
10312 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10313 /// together based on the available instructions.
10314 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10315                                         MVT VT, const X86Subtarget *Subtarget,
10316                                         SelectionDAG &DAG) {
10317   SDLoc DL(Op);
10318   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10319   ArrayRef<int> Mask = SVOp->getMask();
10320
10321   // If we have a single input to the zero element, insert that into V1 if we
10322   // can do so cheaply.
10323   int NumElts = VT.getVectorNumElements();
10324   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10325     return M >= NumElts;
10326   });
10327
10328   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10329     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10330                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10331       return Insertion;
10332
10333   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10334   // check for those subtargets here and avoid much of the subtarget querying in
10335   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10336   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10337   // floating point types there eventually, just immediately cast everything to
10338   // a float and operate entirely in that domain.
10339   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10340     int ElementBits = VT.getScalarSizeInBits();
10341     if (ElementBits < 32)
10342       // No floating point type available, decompose into 128-bit vectors.
10343       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10344
10345     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10346                                 VT.getVectorNumElements());
10347     V1 = DAG.getBitcast(FpVT, V1);
10348     V2 = DAG.getBitcast(FpVT, V2);
10349     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10350   }
10351
10352   switch (VT.SimpleTy) {
10353   case MVT::v4f64:
10354     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10355   case MVT::v4i64:
10356     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10357   case MVT::v8f32:
10358     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10359   case MVT::v8i32:
10360     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10361   case MVT::v16i16:
10362     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10363   case MVT::v32i8:
10364     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10365
10366   default:
10367     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10368   }
10369 }
10370
10371 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10372 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10373                                        const X86Subtarget *Subtarget,
10374                                        SelectionDAG &DAG) {
10375   SDLoc DL(Op);
10376   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10377   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10378   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10379   ArrayRef<int> Mask = SVOp->getMask();
10380   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10381
10382   // X86 has dedicated unpack instructions that can handle specific blend
10383   // operations: UNPCKH and UNPCKL.
10384   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10385     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10386   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10387     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10388
10389   // FIXME: Implement direct support for this type!
10390   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10391 }
10392
10393 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10394 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10395                                        const X86Subtarget *Subtarget,
10396                                        SelectionDAG &DAG) {
10397   SDLoc DL(Op);
10398   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10399   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10400   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10401   ArrayRef<int> Mask = SVOp->getMask();
10402   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10403
10404   // Use dedicated unpack instructions for masks that match their pattern.
10405   if (isShuffleEquivalent(V1, V2, Mask,
10406                           {// First 128-bit lane.
10407                            0, 16, 1, 17, 4, 20, 5, 21,
10408                            // Second 128-bit lane.
10409                            8, 24, 9, 25, 12, 28, 13, 29}))
10410     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10411   if (isShuffleEquivalent(V1, V2, Mask,
10412                           {// First 128-bit lane.
10413                            2, 18, 3, 19, 6, 22, 7, 23,
10414                            // Second 128-bit lane.
10415                            10, 26, 11, 27, 14, 30, 15, 31}))
10416     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10417
10418   // FIXME: Implement direct support for this type!
10419   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10420 }
10421
10422 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10423 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10424                                        const X86Subtarget *Subtarget,
10425                                        SelectionDAG &DAG) {
10426   SDLoc DL(Op);
10427   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10428   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10429   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10430   ArrayRef<int> Mask = SVOp->getMask();
10431   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10432
10433   // X86 has dedicated unpack instructions that can handle specific blend
10434   // operations: UNPCKH and UNPCKL.
10435   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10436     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10437   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10438     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10439
10440   // FIXME: Implement direct support for this type!
10441   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10442 }
10443
10444 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10445 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10446                                        const X86Subtarget *Subtarget,
10447                                        SelectionDAG &DAG) {
10448   SDLoc DL(Op);
10449   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10450   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10451   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10452   ArrayRef<int> Mask = SVOp->getMask();
10453   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10454
10455   // Use dedicated unpack instructions for masks that match their pattern.
10456   if (isShuffleEquivalent(V1, V2, Mask,
10457                           {// First 128-bit lane.
10458                            0, 16, 1, 17, 4, 20, 5, 21,
10459                            // Second 128-bit lane.
10460                            8, 24, 9, 25, 12, 28, 13, 29}))
10461     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10462   if (isShuffleEquivalent(V1, V2, Mask,
10463                           {// First 128-bit lane.
10464                            2, 18, 3, 19, 6, 22, 7, 23,
10465                            // Second 128-bit lane.
10466                            10, 26, 11, 27, 14, 30, 15, 31}))
10467     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10468
10469   // FIXME: Implement direct support for this type!
10470   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10471 }
10472
10473 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10474 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10475                                         const X86Subtarget *Subtarget,
10476                                         SelectionDAG &DAG) {
10477   SDLoc DL(Op);
10478   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10479   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10480   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10481   ArrayRef<int> Mask = SVOp->getMask();
10482   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10483   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10484
10485   // FIXME: Implement direct support for this type!
10486   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10487 }
10488
10489 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10490 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10491                                        const X86Subtarget *Subtarget,
10492                                        SelectionDAG &DAG) {
10493   SDLoc DL(Op);
10494   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10495   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10496   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10497   ArrayRef<int> Mask = SVOp->getMask();
10498   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10499   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10500
10501   // FIXME: Implement direct support for this type!
10502   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10503 }
10504
10505 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10506 ///
10507 /// This routine either breaks down the specific type of a 512-bit x86 vector
10508 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10509 /// together based on the available instructions.
10510 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10511                                         MVT VT, const X86Subtarget *Subtarget,
10512                                         SelectionDAG &DAG) {
10513   SDLoc DL(Op);
10514   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10515   ArrayRef<int> Mask = SVOp->getMask();
10516   assert(Subtarget->hasAVX512() &&
10517          "Cannot lower 512-bit vectors w/ basic ISA!");
10518
10519   // Check for being able to broadcast a single element.
10520   if (SDValue Broadcast =
10521           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10522     return Broadcast;
10523
10524   // Dispatch to each element type for lowering. If we don't have supprot for
10525   // specific element type shuffles at 512 bits, immediately split them and
10526   // lower them. Each lowering routine of a given type is allowed to assume that
10527   // the requisite ISA extensions for that element type are available.
10528   switch (VT.SimpleTy) {
10529   case MVT::v8f64:
10530     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10531   case MVT::v16f32:
10532     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10533   case MVT::v8i64:
10534     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10535   case MVT::v16i32:
10536     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10537   case MVT::v32i16:
10538     if (Subtarget->hasBWI())
10539       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10540     break;
10541   case MVT::v64i8:
10542     if (Subtarget->hasBWI())
10543       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10544     break;
10545
10546   default:
10547     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10548   }
10549
10550   // Otherwise fall back on splitting.
10551   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10552 }
10553
10554 /// \brief Top-level lowering for x86 vector shuffles.
10555 ///
10556 /// This handles decomposition, canonicalization, and lowering of all x86
10557 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10558 /// above in helper routines. The canonicalization attempts to widen shuffles
10559 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10560 /// s.t. only one of the two inputs needs to be tested, etc.
10561 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10562                                   SelectionDAG &DAG) {
10563   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10564   ArrayRef<int> Mask = SVOp->getMask();
10565   SDValue V1 = Op.getOperand(0);
10566   SDValue V2 = Op.getOperand(1);
10567   MVT VT = Op.getSimpleValueType();
10568   int NumElements = VT.getVectorNumElements();
10569   SDLoc dl(Op);
10570
10571   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10572
10573   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10574   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10575   if (V1IsUndef && V2IsUndef)
10576     return DAG.getUNDEF(VT);
10577
10578   // When we create a shuffle node we put the UNDEF node to second operand,
10579   // but in some cases the first operand may be transformed to UNDEF.
10580   // In this case we should just commute the node.
10581   if (V1IsUndef)
10582     return DAG.getCommutedVectorShuffle(*SVOp);
10583
10584   // Check for non-undef masks pointing at an undef vector and make the masks
10585   // undef as well. This makes it easier to match the shuffle based solely on
10586   // the mask.
10587   if (V2IsUndef)
10588     for (int M : Mask)
10589       if (M >= NumElements) {
10590         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10591         for (int &M : NewMask)
10592           if (M >= NumElements)
10593             M = -1;
10594         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10595       }
10596
10597   // We actually see shuffles that are entirely re-arrangements of a set of
10598   // zero inputs. This mostly happens while decomposing complex shuffles into
10599   // simple ones. Directly lower these as a buildvector of zeros.
10600   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10601   if (Zeroable.all())
10602     return getZeroVector(VT, Subtarget, DAG, dl);
10603
10604   // Try to collapse shuffles into using a vector type with fewer elements but
10605   // wider element types. We cap this to not form integers or floating point
10606   // elements wider than 64 bits, but it might be interesting to form i128
10607   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10608   SmallVector<int, 16> WidenedMask;
10609   if (VT.getScalarSizeInBits() < 64 &&
10610       canWidenShuffleElements(Mask, WidenedMask)) {
10611     MVT NewEltVT = VT.isFloatingPoint()
10612                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10613                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10614     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10615     // Make sure that the new vector type is legal. For example, v2f64 isn't
10616     // legal on SSE1.
10617     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10618       V1 = DAG.getBitcast(NewVT, V1);
10619       V2 = DAG.getBitcast(NewVT, V2);
10620       return DAG.getBitcast(
10621           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10622     }
10623   }
10624
10625   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10626   for (int M : SVOp->getMask())
10627     if (M < 0)
10628       ++NumUndefElements;
10629     else if (M < NumElements)
10630       ++NumV1Elements;
10631     else
10632       ++NumV2Elements;
10633
10634   // Commute the shuffle as needed such that more elements come from V1 than
10635   // V2. This allows us to match the shuffle pattern strictly on how many
10636   // elements come from V1 without handling the symmetric cases.
10637   if (NumV2Elements > NumV1Elements)
10638     return DAG.getCommutedVectorShuffle(*SVOp);
10639
10640   // When the number of V1 and V2 elements are the same, try to minimize the
10641   // number of uses of V2 in the low half of the vector. When that is tied,
10642   // ensure that the sum of indices for V1 is equal to or lower than the sum
10643   // indices for V2. When those are equal, try to ensure that the number of odd
10644   // indices for V1 is lower than the number of odd indices for V2.
10645   if (NumV1Elements == NumV2Elements) {
10646     int LowV1Elements = 0, LowV2Elements = 0;
10647     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10648       if (M >= NumElements)
10649         ++LowV2Elements;
10650       else if (M >= 0)
10651         ++LowV1Elements;
10652     if (LowV2Elements > LowV1Elements) {
10653       return DAG.getCommutedVectorShuffle(*SVOp);
10654     } else if (LowV2Elements == LowV1Elements) {
10655       int SumV1Indices = 0, SumV2Indices = 0;
10656       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10657         if (SVOp->getMask()[i] >= NumElements)
10658           SumV2Indices += i;
10659         else if (SVOp->getMask()[i] >= 0)
10660           SumV1Indices += i;
10661       if (SumV2Indices < SumV1Indices) {
10662         return DAG.getCommutedVectorShuffle(*SVOp);
10663       } else if (SumV2Indices == SumV1Indices) {
10664         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10665         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10666           if (SVOp->getMask()[i] >= NumElements)
10667             NumV2OddIndices += i % 2;
10668           else if (SVOp->getMask()[i] >= 0)
10669             NumV1OddIndices += i % 2;
10670         if (NumV2OddIndices < NumV1OddIndices)
10671           return DAG.getCommutedVectorShuffle(*SVOp);
10672       }
10673     }
10674   }
10675
10676   // For each vector width, delegate to a specialized lowering routine.
10677   if (VT.getSizeInBits() == 128)
10678     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10679
10680   if (VT.getSizeInBits() == 256)
10681     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10682
10683   // Force AVX-512 vectors to be scalarized for now.
10684   // FIXME: Implement AVX-512 support!
10685   if (VT.getSizeInBits() == 512)
10686     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10687
10688   llvm_unreachable("Unimplemented!");
10689 }
10690
10691 // This function assumes its argument is a BUILD_VECTOR of constants or
10692 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10693 // true.
10694 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10695                                     unsigned &MaskValue) {
10696   MaskValue = 0;
10697   unsigned NumElems = BuildVector->getNumOperands();
10698   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10699   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10700   unsigned NumElemsInLane = NumElems / NumLanes;
10701
10702   // Blend for v16i16 should be symetric for the both lanes.
10703   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10704     SDValue EltCond = BuildVector->getOperand(i);
10705     SDValue SndLaneEltCond =
10706         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10707
10708     int Lane1Cond = -1, Lane2Cond = -1;
10709     if (isa<ConstantSDNode>(EltCond))
10710       Lane1Cond = !isZero(EltCond);
10711     if (isa<ConstantSDNode>(SndLaneEltCond))
10712       Lane2Cond = !isZero(SndLaneEltCond);
10713
10714     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10715       // Lane1Cond != 0, means we want the first argument.
10716       // Lane1Cond == 0, means we want the second argument.
10717       // The encoding of this argument is 0 for the first argument, 1
10718       // for the second. Therefore, invert the condition.
10719       MaskValue |= !Lane1Cond << i;
10720     else if (Lane1Cond < 0)
10721       MaskValue |= !Lane2Cond << i;
10722     else
10723       return false;
10724   }
10725   return true;
10726 }
10727
10728 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10729 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10730                                            const X86Subtarget *Subtarget,
10731                                            SelectionDAG &DAG) {
10732   SDValue Cond = Op.getOperand(0);
10733   SDValue LHS = Op.getOperand(1);
10734   SDValue RHS = Op.getOperand(2);
10735   SDLoc dl(Op);
10736   MVT VT = Op.getSimpleValueType();
10737
10738   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10739     return SDValue();
10740   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10741
10742   // Only non-legal VSELECTs reach this lowering, convert those into generic
10743   // shuffles and re-use the shuffle lowering path for blends.
10744   SmallVector<int, 32> Mask;
10745   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10746     SDValue CondElt = CondBV->getOperand(i);
10747     Mask.push_back(
10748         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10749   }
10750   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10751 }
10752
10753 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10754   // A vselect where all conditions and data are constants can be optimized into
10755   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10756   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10757       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10758       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10759     return SDValue();
10760
10761   // Try to lower this to a blend-style vector shuffle. This can handle all
10762   // constant condition cases.
10763   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10764     return BlendOp;
10765
10766   // Variable blends are only legal from SSE4.1 onward.
10767   if (!Subtarget->hasSSE41())
10768     return SDValue();
10769
10770   // Only some types will be legal on some subtargets. If we can emit a legal
10771   // VSELECT-matching blend, return Op, and but if we need to expand, return
10772   // a null value.
10773   switch (Op.getSimpleValueType().SimpleTy) {
10774   default:
10775     // Most of the vector types have blends past SSE4.1.
10776     return Op;
10777
10778   case MVT::v32i8:
10779     // The byte blends for AVX vectors were introduced only in AVX2.
10780     if (Subtarget->hasAVX2())
10781       return Op;
10782
10783     return SDValue();
10784
10785   case MVT::v8i16:
10786   case MVT::v16i16:
10787     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10788     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10789       return Op;
10790
10791     // FIXME: We should custom lower this by fixing the condition and using i8
10792     // blends.
10793     return SDValue();
10794   }
10795 }
10796
10797 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10798   MVT VT = Op.getSimpleValueType();
10799   SDLoc dl(Op);
10800
10801   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10802     return SDValue();
10803
10804   if (VT.getSizeInBits() == 8) {
10805     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10806                                   Op.getOperand(0), Op.getOperand(1));
10807     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10808                                   DAG.getValueType(VT));
10809     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10810   }
10811
10812   if (VT.getSizeInBits() == 16) {
10813     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10814     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10815     if (Idx == 0)
10816       return DAG.getNode(
10817           ISD::TRUNCATE, dl, MVT::i16,
10818           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10819                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10820                       Op.getOperand(1)));
10821     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10822                                   Op.getOperand(0), Op.getOperand(1));
10823     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10824                                   DAG.getValueType(VT));
10825     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10826   }
10827
10828   if (VT == MVT::f32) {
10829     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10830     // the result back to FR32 register. It's only worth matching if the
10831     // result has a single use which is a store or a bitcast to i32.  And in
10832     // the case of a store, it's not worth it if the index is a constant 0,
10833     // because a MOVSSmr can be used instead, which is smaller and faster.
10834     if (!Op.hasOneUse())
10835       return SDValue();
10836     SDNode *User = *Op.getNode()->use_begin();
10837     if ((User->getOpcode() != ISD::STORE ||
10838          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10839           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10840         (User->getOpcode() != ISD::BITCAST ||
10841          User->getValueType(0) != MVT::i32))
10842       return SDValue();
10843     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10844                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10845                                   Op.getOperand(1));
10846     return DAG.getBitcast(MVT::f32, Extract);
10847   }
10848
10849   if (VT == MVT::i32 || VT == MVT::i64) {
10850     // ExtractPS/pextrq works with constant index.
10851     if (isa<ConstantSDNode>(Op.getOperand(1)))
10852       return Op;
10853   }
10854   return SDValue();
10855 }
10856
10857 /// Extract one bit from mask vector, like v16i1 or v8i1.
10858 /// AVX-512 feature.
10859 SDValue
10860 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10861   SDValue Vec = Op.getOperand(0);
10862   SDLoc dl(Vec);
10863   MVT VecVT = Vec.getSimpleValueType();
10864   SDValue Idx = Op.getOperand(1);
10865   MVT EltVT = Op.getSimpleValueType();
10866
10867   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10868   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10869          "Unexpected vector type in ExtractBitFromMaskVector");
10870
10871   // variable index can't be handled in mask registers,
10872   // extend vector to VR512
10873   if (!isa<ConstantSDNode>(Idx)) {
10874     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10875     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10876     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10877                               ExtVT.getVectorElementType(), Ext, Idx);
10878     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10879   }
10880
10881   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10882   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10883   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10884     rc = getRegClassFor(MVT::v16i1);
10885   unsigned MaxSift = rc->getSize()*8 - 1;
10886   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10887                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10888   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10889                     DAG.getConstant(MaxSift, dl, MVT::i8));
10890   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10891                        DAG.getIntPtrConstant(0, dl));
10892 }
10893
10894 SDValue
10895 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10896                                            SelectionDAG &DAG) const {
10897   SDLoc dl(Op);
10898   SDValue Vec = Op.getOperand(0);
10899   MVT VecVT = Vec.getSimpleValueType();
10900   SDValue Idx = Op.getOperand(1);
10901
10902   if (Op.getSimpleValueType() == MVT::i1)
10903     return ExtractBitFromMaskVector(Op, DAG);
10904
10905   if (!isa<ConstantSDNode>(Idx)) {
10906     if (VecVT.is512BitVector() ||
10907         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10908          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10909
10910       MVT MaskEltVT =
10911         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10912       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10913                                     MaskEltVT.getSizeInBits());
10914
10915       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10916       auto PtrVT = getPointerTy(DAG.getDataLayout());
10917       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10918                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10919                                  DAG.getConstant(0, dl, PtrVT));
10920       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10921       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10922                          DAG.getConstant(0, dl, PtrVT));
10923     }
10924     return SDValue();
10925   }
10926
10927   // If this is a 256-bit vector result, first extract the 128-bit vector and
10928   // then extract the element from the 128-bit vector.
10929   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10930
10931     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10932     // Get the 128-bit vector.
10933     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10934     MVT EltVT = VecVT.getVectorElementType();
10935
10936     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10937
10938     //if (IdxVal >= NumElems/2)
10939     //  IdxVal -= NumElems/2;
10940     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10941     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10942                        DAG.getConstant(IdxVal, dl, MVT::i32));
10943   }
10944
10945   assert(VecVT.is128BitVector() && "Unexpected vector length");
10946
10947   if (Subtarget->hasSSE41())
10948     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10949       return Res;
10950
10951   MVT VT = Op.getSimpleValueType();
10952   // TODO: handle v16i8.
10953   if (VT.getSizeInBits() == 16) {
10954     SDValue Vec = Op.getOperand(0);
10955     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10956     if (Idx == 0)
10957       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10958                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10959                                      DAG.getBitcast(MVT::v4i32, Vec),
10960                                      Op.getOperand(1)));
10961     // Transform it so it match pextrw which produces a 32-bit result.
10962     MVT EltVT = MVT::i32;
10963     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10964                                   Op.getOperand(0), Op.getOperand(1));
10965     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10966                                   DAG.getValueType(VT));
10967     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10968   }
10969
10970   if (VT.getSizeInBits() == 32) {
10971     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10972     if (Idx == 0)
10973       return Op;
10974
10975     // SHUFPS the element to the lowest double word, then movss.
10976     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10977     MVT VVT = Op.getOperand(0).getSimpleValueType();
10978     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10979                                        DAG.getUNDEF(VVT), Mask);
10980     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10981                        DAG.getIntPtrConstant(0, dl));
10982   }
10983
10984   if (VT.getSizeInBits() == 64) {
10985     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10986     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10987     //        to match extract_elt for f64.
10988     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10989     if (Idx == 0)
10990       return Op;
10991
10992     // UNPCKHPD the element to the lowest double word, then movsd.
10993     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10994     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10995     int Mask[2] = { 1, -1 };
10996     MVT VVT = Op.getOperand(0).getSimpleValueType();
10997     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10998                                        DAG.getUNDEF(VVT), Mask);
10999     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11000                        DAG.getIntPtrConstant(0, dl));
11001   }
11002
11003   return SDValue();
11004 }
11005
11006 /// Insert one bit to mask vector, like v16i1 or v8i1.
11007 /// AVX-512 feature.
11008 SDValue
11009 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11010   SDLoc dl(Op);
11011   SDValue Vec = Op.getOperand(0);
11012   SDValue Elt = Op.getOperand(1);
11013   SDValue Idx = Op.getOperand(2);
11014   MVT VecVT = Vec.getSimpleValueType();
11015
11016   if (!isa<ConstantSDNode>(Idx)) {
11017     // Non constant index. Extend source and destination,
11018     // insert element and then truncate the result.
11019     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11020     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11021     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11022       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11023       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11024     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11025   }
11026
11027   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11028   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11029   if (IdxVal)
11030     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11031                            DAG.getConstant(IdxVal, dl, MVT::i8));
11032   if (Vec.getOpcode() == ISD::UNDEF)
11033     return EltInVec;
11034   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11035 }
11036
11037 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11038                                                   SelectionDAG &DAG) const {
11039   MVT VT = Op.getSimpleValueType();
11040   MVT EltVT = VT.getVectorElementType();
11041
11042   if (EltVT == MVT::i1)
11043     return InsertBitToMaskVector(Op, DAG);
11044
11045   SDLoc dl(Op);
11046   SDValue N0 = Op.getOperand(0);
11047   SDValue N1 = Op.getOperand(1);
11048   SDValue N2 = Op.getOperand(2);
11049   if (!isa<ConstantSDNode>(N2))
11050     return SDValue();
11051   auto *N2C = cast<ConstantSDNode>(N2);
11052   unsigned IdxVal = N2C->getZExtValue();
11053
11054   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11055   // into that, and then insert the subvector back into the result.
11056   if (VT.is256BitVector() || VT.is512BitVector()) {
11057     // With a 256-bit vector, we can insert into the zero element efficiently
11058     // using a blend if we have AVX or AVX2 and the right data type.
11059     if (VT.is256BitVector() && IdxVal == 0) {
11060       // TODO: It is worthwhile to cast integer to floating point and back
11061       // and incur a domain crossing penalty if that's what we'll end up
11062       // doing anyway after extracting to a 128-bit vector.
11063       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11064           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11065         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11066         N2 = DAG.getIntPtrConstant(1, dl);
11067         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11068       }
11069     }
11070
11071     // Get the desired 128-bit vector chunk.
11072     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11073
11074     // Insert the element into the desired chunk.
11075     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11076     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11077
11078     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11079                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11080
11081     // Insert the changed part back into the bigger vector
11082     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11083   }
11084   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11085
11086   if (Subtarget->hasSSE41()) {
11087     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11088       unsigned Opc;
11089       if (VT == MVT::v8i16) {
11090         Opc = X86ISD::PINSRW;
11091       } else {
11092         assert(VT == MVT::v16i8);
11093         Opc = X86ISD::PINSRB;
11094       }
11095
11096       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11097       // argument.
11098       if (N1.getValueType() != MVT::i32)
11099         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11100       if (N2.getValueType() != MVT::i32)
11101         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11102       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11103     }
11104
11105     if (EltVT == MVT::f32) {
11106       // Bits [7:6] of the constant are the source select. This will always be
11107       //   zero here. The DAG Combiner may combine an extract_elt index into
11108       //   these bits. For example (insert (extract, 3), 2) could be matched by
11109       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11110       // Bits [5:4] of the constant are the destination select. This is the
11111       //   value of the incoming immediate.
11112       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11113       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11114
11115       const Function *F = DAG.getMachineFunction().getFunction();
11116       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11117       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11118         // If this is an insertion of 32-bits into the low 32-bits of
11119         // a vector, we prefer to generate a blend with immediate rather
11120         // than an insertps. Blends are simpler operations in hardware and so
11121         // will always have equal or better performance than insertps.
11122         // But if optimizing for size and there's a load folding opportunity,
11123         // generate insertps because blendps does not have a 32-bit memory
11124         // operand form.
11125         N2 = DAG.getIntPtrConstant(1, dl);
11126         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11127         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11128       }
11129       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11130       // Create this as a scalar to vector..
11131       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11132       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11133     }
11134
11135     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11136       // PINSR* works with constant index.
11137       return Op;
11138     }
11139   }
11140
11141   if (EltVT == MVT::i8)
11142     return SDValue();
11143
11144   if (EltVT.getSizeInBits() == 16) {
11145     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11146     // as its second argument.
11147     if (N1.getValueType() != MVT::i32)
11148       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11149     if (N2.getValueType() != MVT::i32)
11150       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11151     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11152   }
11153   return SDValue();
11154 }
11155
11156 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11157   SDLoc dl(Op);
11158   MVT OpVT = Op.getSimpleValueType();
11159
11160   // If this is a 256-bit vector result, first insert into a 128-bit
11161   // vector and then insert into the 256-bit vector.
11162   if (!OpVT.is128BitVector()) {
11163     // Insert into a 128-bit vector.
11164     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11165     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11166                                  OpVT.getVectorNumElements() / SizeFactor);
11167
11168     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11169
11170     // Insert the 128-bit vector.
11171     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11172   }
11173
11174   if (OpVT == MVT::v1i64 &&
11175       Op.getOperand(0).getValueType() == MVT::i64)
11176     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11177
11178   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11179   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11180   return DAG.getBitcast(
11181       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11182 }
11183
11184 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11185 // a simple subregister reference or explicit instructions to grab
11186 // upper bits of a vector.
11187 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11188                                       SelectionDAG &DAG) {
11189   SDLoc dl(Op);
11190   SDValue In =  Op.getOperand(0);
11191   SDValue Idx = Op.getOperand(1);
11192   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11193   MVT ResVT   = Op.getSimpleValueType();
11194   MVT InVT    = In.getSimpleValueType();
11195
11196   if (Subtarget->hasFp256()) {
11197     if (ResVT.is128BitVector() &&
11198         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11199         isa<ConstantSDNode>(Idx)) {
11200       return Extract128BitVector(In, IdxVal, DAG, dl);
11201     }
11202     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11203         isa<ConstantSDNode>(Idx)) {
11204       return Extract256BitVector(In, IdxVal, DAG, dl);
11205     }
11206   }
11207   return SDValue();
11208 }
11209
11210 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11211 // simple superregister reference or explicit instructions to insert
11212 // the upper bits of a vector.
11213 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11214                                      SelectionDAG &DAG) {
11215   if (!Subtarget->hasAVX())
11216     return SDValue();
11217
11218   SDLoc dl(Op);
11219   SDValue Vec = Op.getOperand(0);
11220   SDValue SubVec = Op.getOperand(1);
11221   SDValue Idx = Op.getOperand(2);
11222
11223   if (!isa<ConstantSDNode>(Idx))
11224     return SDValue();
11225
11226   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11227   MVT OpVT = Op.getSimpleValueType();
11228   MVT SubVecVT = SubVec.getSimpleValueType();
11229
11230   // Fold two 16-byte subvector loads into one 32-byte load:
11231   // (insert_subvector (insert_subvector undef, (load addr), 0),
11232   //                   (load addr + 16), Elts/2)
11233   // --> load32 addr
11234   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11235       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11236       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11237       !Subtarget->isUnalignedMem32Slow()) {
11238     SDValue SubVec2 = Vec.getOperand(1);
11239     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11240       if (Idx2->getZExtValue() == 0) {
11241         SDValue Ops[] = { SubVec2, SubVec };
11242         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11243           return Ld;
11244       }
11245     }
11246   }
11247
11248   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11249       SubVecVT.is128BitVector())
11250     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11251
11252   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11253     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11254
11255   if (OpVT.getVectorElementType() == MVT::i1) {
11256     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11257       return Op;
11258     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11259     SDValue Undef = DAG.getUNDEF(OpVT);
11260     unsigned NumElems = OpVT.getVectorNumElements();
11261     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11262
11263     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11264       // Zero upper bits of the Vec
11265       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11266       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11267
11268       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11269                                  SubVec, ZeroIdx);
11270       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11271       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11272     }
11273     if (IdxVal == 0) {
11274       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11275                                  SubVec, ZeroIdx);
11276       // Zero upper bits of the Vec2
11277       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11278       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11279       // Zero lower bits of the Vec
11280       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11281       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11282       // Merge them together
11283       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11284     }
11285   }
11286   return SDValue();
11287 }
11288
11289 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11290 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11291 // one of the above mentioned nodes. It has to be wrapped because otherwise
11292 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11293 // be used to form addressing mode. These wrapped nodes will be selected
11294 // into MOV32ri.
11295 SDValue
11296 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11297   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11298
11299   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11300   // global base reg.
11301   unsigned char OpFlag = 0;
11302   unsigned WrapperKind = X86ISD::Wrapper;
11303   CodeModel::Model M = DAG.getTarget().getCodeModel();
11304
11305   if (Subtarget->isPICStyleRIPRel() &&
11306       (M == CodeModel::Small || M == CodeModel::Kernel))
11307     WrapperKind = X86ISD::WrapperRIP;
11308   else if (Subtarget->isPICStyleGOT())
11309     OpFlag = X86II::MO_GOTOFF;
11310   else if (Subtarget->isPICStyleStubPIC())
11311     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11312
11313   auto PtrVT = getPointerTy(DAG.getDataLayout());
11314   SDValue Result = DAG.getTargetConstantPool(
11315       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11316   SDLoc DL(CP);
11317   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11318   // With PIC, the address is actually $g + Offset.
11319   if (OpFlag) {
11320     Result =
11321         DAG.getNode(ISD::ADD, DL, PtrVT,
11322                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11323   }
11324
11325   return Result;
11326 }
11327
11328 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11329   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11330
11331   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11332   // global base reg.
11333   unsigned char OpFlag = 0;
11334   unsigned WrapperKind = X86ISD::Wrapper;
11335   CodeModel::Model M = DAG.getTarget().getCodeModel();
11336
11337   if (Subtarget->isPICStyleRIPRel() &&
11338       (M == CodeModel::Small || M == CodeModel::Kernel))
11339     WrapperKind = X86ISD::WrapperRIP;
11340   else if (Subtarget->isPICStyleGOT())
11341     OpFlag = X86II::MO_GOTOFF;
11342   else if (Subtarget->isPICStyleStubPIC())
11343     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11344
11345   auto PtrVT = getPointerTy(DAG.getDataLayout());
11346   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11347   SDLoc DL(JT);
11348   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11349
11350   // With PIC, the address is actually $g + Offset.
11351   if (OpFlag)
11352     Result =
11353         DAG.getNode(ISD::ADD, DL, PtrVT,
11354                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11355
11356   return Result;
11357 }
11358
11359 SDValue
11360 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11361   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11362
11363   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11364   // global base reg.
11365   unsigned char OpFlag = 0;
11366   unsigned WrapperKind = X86ISD::Wrapper;
11367   CodeModel::Model M = DAG.getTarget().getCodeModel();
11368
11369   if (Subtarget->isPICStyleRIPRel() &&
11370       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11371     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11372       OpFlag = X86II::MO_GOTPCREL;
11373     WrapperKind = X86ISD::WrapperRIP;
11374   } else if (Subtarget->isPICStyleGOT()) {
11375     OpFlag = X86II::MO_GOT;
11376   } else if (Subtarget->isPICStyleStubPIC()) {
11377     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11378   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11379     OpFlag = X86II::MO_DARWIN_NONLAZY;
11380   }
11381
11382   auto PtrVT = getPointerTy(DAG.getDataLayout());
11383   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11384
11385   SDLoc DL(Op);
11386   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11387
11388   // With PIC, the address is actually $g + Offset.
11389   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11390       !Subtarget->is64Bit()) {
11391     Result =
11392         DAG.getNode(ISD::ADD, DL, PtrVT,
11393                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11394   }
11395
11396   // For symbols that require a load from a stub to get the address, emit the
11397   // load.
11398   if (isGlobalStubReference(OpFlag))
11399     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11400                          MachinePointerInfo::getGOT(), false, false, false, 0);
11401
11402   return Result;
11403 }
11404
11405 SDValue
11406 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11407   // Create the TargetBlockAddressAddress node.
11408   unsigned char OpFlags =
11409     Subtarget->ClassifyBlockAddressReference();
11410   CodeModel::Model M = DAG.getTarget().getCodeModel();
11411   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11412   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11413   SDLoc dl(Op);
11414   auto PtrVT = getPointerTy(DAG.getDataLayout());
11415   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11416
11417   if (Subtarget->isPICStyleRIPRel() &&
11418       (M == CodeModel::Small || M == CodeModel::Kernel))
11419     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11420   else
11421     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11422
11423   // With PIC, the address is actually $g + Offset.
11424   if (isGlobalRelativeToPICBase(OpFlags)) {
11425     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11426                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11427   }
11428
11429   return Result;
11430 }
11431
11432 SDValue
11433 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11434                                       int64_t Offset, SelectionDAG &DAG) const {
11435   // Create the TargetGlobalAddress node, folding in the constant
11436   // offset if it is legal.
11437   unsigned char OpFlags =
11438       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11439   CodeModel::Model M = DAG.getTarget().getCodeModel();
11440   auto PtrVT = getPointerTy(DAG.getDataLayout());
11441   SDValue Result;
11442   if (OpFlags == X86II::MO_NO_FLAG &&
11443       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11444     // A direct static reference to a global.
11445     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11446     Offset = 0;
11447   } else {
11448     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11449   }
11450
11451   if (Subtarget->isPICStyleRIPRel() &&
11452       (M == CodeModel::Small || M == CodeModel::Kernel))
11453     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11454   else
11455     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11456
11457   // With PIC, the address is actually $g + Offset.
11458   if (isGlobalRelativeToPICBase(OpFlags)) {
11459     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11460                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11461   }
11462
11463   // For globals that require a load from a stub to get the address, emit the
11464   // load.
11465   if (isGlobalStubReference(OpFlags))
11466     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11467                          MachinePointerInfo::getGOT(), false, false, false, 0);
11468
11469   // If there was a non-zero offset that we didn't fold, create an explicit
11470   // addition for it.
11471   if (Offset != 0)
11472     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11473                          DAG.getConstant(Offset, dl, PtrVT));
11474
11475   return Result;
11476 }
11477
11478 SDValue
11479 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11480   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11481   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11482   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11483 }
11484
11485 static SDValue
11486 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11487            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11488            unsigned char OperandFlags, bool LocalDynamic = false) {
11489   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11490   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11491   SDLoc dl(GA);
11492   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11493                                            GA->getValueType(0),
11494                                            GA->getOffset(),
11495                                            OperandFlags);
11496
11497   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11498                                            : X86ISD::TLSADDR;
11499
11500   if (InFlag) {
11501     SDValue Ops[] = { Chain,  TGA, *InFlag };
11502     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11503   } else {
11504     SDValue Ops[]  = { Chain, TGA };
11505     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11506   }
11507
11508   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11509   MFI->setAdjustsStack(true);
11510   MFI->setHasCalls(true);
11511
11512   SDValue Flag = Chain.getValue(1);
11513   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11514 }
11515
11516 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11517 static SDValue
11518 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11519                                 const EVT PtrVT) {
11520   SDValue InFlag;
11521   SDLoc dl(GA);  // ? function entry point might be better
11522   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11523                                    DAG.getNode(X86ISD::GlobalBaseReg,
11524                                                SDLoc(), PtrVT), InFlag);
11525   InFlag = Chain.getValue(1);
11526
11527   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11528 }
11529
11530 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11531 static SDValue
11532 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11533                                 const EVT PtrVT) {
11534   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11535                     X86::RAX, X86II::MO_TLSGD);
11536 }
11537
11538 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11539                                            SelectionDAG &DAG,
11540                                            const EVT PtrVT,
11541                                            bool is64Bit) {
11542   SDLoc dl(GA);
11543
11544   // Get the start address of the TLS block for this module.
11545   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11546       .getInfo<X86MachineFunctionInfo>();
11547   MFI->incNumLocalDynamicTLSAccesses();
11548
11549   SDValue Base;
11550   if (is64Bit) {
11551     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11552                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11553   } else {
11554     SDValue InFlag;
11555     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11556         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11557     InFlag = Chain.getValue(1);
11558     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11559                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11560   }
11561
11562   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11563   // of Base.
11564
11565   // Build x@dtpoff.
11566   unsigned char OperandFlags = X86II::MO_DTPOFF;
11567   unsigned WrapperKind = X86ISD::Wrapper;
11568   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11569                                            GA->getValueType(0),
11570                                            GA->getOffset(), OperandFlags);
11571   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11572
11573   // Add x@dtpoff with the base.
11574   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11575 }
11576
11577 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11578 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11579                                    const EVT PtrVT, TLSModel::Model model,
11580                                    bool is64Bit, bool isPIC) {
11581   SDLoc dl(GA);
11582
11583   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11584   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11585                                                          is64Bit ? 257 : 256));
11586
11587   SDValue ThreadPointer =
11588       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11589                   MachinePointerInfo(Ptr), false, false, false, 0);
11590
11591   unsigned char OperandFlags = 0;
11592   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11593   // initialexec.
11594   unsigned WrapperKind = X86ISD::Wrapper;
11595   if (model == TLSModel::LocalExec) {
11596     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11597   } else if (model == TLSModel::InitialExec) {
11598     if (is64Bit) {
11599       OperandFlags = X86II::MO_GOTTPOFF;
11600       WrapperKind = X86ISD::WrapperRIP;
11601     } else {
11602       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11603     }
11604   } else {
11605     llvm_unreachable("Unexpected model");
11606   }
11607
11608   // emit "addl x@ntpoff,%eax" (local exec)
11609   // or "addl x@indntpoff,%eax" (initial exec)
11610   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11611   SDValue TGA =
11612       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11613                                  GA->getOffset(), OperandFlags);
11614   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11615
11616   if (model == TLSModel::InitialExec) {
11617     if (isPIC && !is64Bit) {
11618       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11619                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11620                            Offset);
11621     }
11622
11623     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11624                          MachinePointerInfo::getGOT(), false, false, false, 0);
11625   }
11626
11627   // The address of the thread local variable is the add of the thread
11628   // pointer with the offset of the variable.
11629   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11630 }
11631
11632 SDValue
11633 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11634
11635   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11636   const GlobalValue *GV = GA->getGlobal();
11637   auto PtrVT = getPointerTy(DAG.getDataLayout());
11638
11639   if (Subtarget->isTargetELF()) {
11640     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11641     switch (model) {
11642       case TLSModel::GeneralDynamic:
11643         if (Subtarget->is64Bit())
11644           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11645         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11646       case TLSModel::LocalDynamic:
11647         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11648                                            Subtarget->is64Bit());
11649       case TLSModel::InitialExec:
11650       case TLSModel::LocalExec:
11651         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11652                                    DAG.getTarget().getRelocationModel() ==
11653                                        Reloc::PIC_);
11654     }
11655     llvm_unreachable("Unknown TLS model.");
11656   }
11657
11658   if (Subtarget->isTargetDarwin()) {
11659     // Darwin only has one model of TLS.  Lower to that.
11660     unsigned char OpFlag = 0;
11661     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11662                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11663
11664     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11665     // global base reg.
11666     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11667                  !Subtarget->is64Bit();
11668     if (PIC32)
11669       OpFlag = X86II::MO_TLVP_PIC_BASE;
11670     else
11671       OpFlag = X86II::MO_TLVP;
11672     SDLoc DL(Op);
11673     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11674                                                 GA->getValueType(0),
11675                                                 GA->getOffset(), OpFlag);
11676     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11677
11678     // With PIC32, the address is actually $g + Offset.
11679     if (PIC32)
11680       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11681                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11682                            Offset);
11683
11684     // Lowering the machine isd will make sure everything is in the right
11685     // location.
11686     SDValue Chain = DAG.getEntryNode();
11687     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11688     SDValue Args[] = { Chain, Offset };
11689     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11690
11691     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11692     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11693     MFI->setAdjustsStack(true);
11694
11695     // And our return value (tls address) is in the standard call return value
11696     // location.
11697     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11698     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11699   }
11700
11701   if (Subtarget->isTargetKnownWindowsMSVC() ||
11702       Subtarget->isTargetWindowsGNU()) {
11703     // Just use the implicit TLS architecture
11704     // Need to generate someting similar to:
11705     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11706     //                                  ; from TEB
11707     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11708     //   mov     rcx, qword [rdx+rcx*8]
11709     //   mov     eax, .tls$:tlsvar
11710     //   [rax+rcx] contains the address
11711     // Windows 64bit: gs:0x58
11712     // Windows 32bit: fs:__tls_array
11713
11714     SDLoc dl(GA);
11715     SDValue Chain = DAG.getEntryNode();
11716
11717     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11718     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11719     // use its literal value of 0x2C.
11720     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11721                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11722                                                              256)
11723                                         : Type::getInt32PtrTy(*DAG.getContext(),
11724                                                               257));
11725
11726     SDValue TlsArray = Subtarget->is64Bit()
11727                            ? DAG.getIntPtrConstant(0x58, dl)
11728                            : (Subtarget->isTargetWindowsGNU()
11729                                   ? DAG.getIntPtrConstant(0x2C, dl)
11730                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11731
11732     SDValue ThreadPointer =
11733         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11734                     false, false, 0);
11735
11736     SDValue res;
11737     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11738       res = ThreadPointer;
11739     } else {
11740       // Load the _tls_index variable
11741       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11742       if (Subtarget->is64Bit())
11743         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11744                              MachinePointerInfo(), MVT::i32, false, false,
11745                              false, 0);
11746       else
11747         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11748                           false, false, 0);
11749
11750       auto &DL = DAG.getDataLayout();
11751       SDValue Scale =
11752           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11753       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11754
11755       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11756     }
11757
11758     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11759                       false, 0);
11760
11761     // Get the offset of start of .tls section
11762     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11763                                              GA->getValueType(0),
11764                                              GA->getOffset(), X86II::MO_SECREL);
11765     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11766
11767     // The address of the thread local variable is the add of the thread
11768     // pointer with the offset of the variable.
11769     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11770   }
11771
11772   llvm_unreachable("TLS not implemented for this target.");
11773 }
11774
11775 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11776 /// and take a 2 x i32 value to shift plus a shift amount.
11777 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11778   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11779   MVT VT = Op.getSimpleValueType();
11780   unsigned VTBits = VT.getSizeInBits();
11781   SDLoc dl(Op);
11782   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11783   SDValue ShOpLo = Op.getOperand(0);
11784   SDValue ShOpHi = Op.getOperand(1);
11785   SDValue ShAmt  = Op.getOperand(2);
11786   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11787   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11788   // during isel.
11789   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11790                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11791   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11792                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11793                        : DAG.getConstant(0, dl, VT);
11794
11795   SDValue Tmp2, Tmp3;
11796   if (Op.getOpcode() == ISD::SHL_PARTS) {
11797     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11798     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11799   } else {
11800     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11801     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11802   }
11803
11804   // If the shift amount is larger or equal than the width of a part we can't
11805   // rely on the results of shld/shrd. Insert a test and select the appropriate
11806   // values for large shift amounts.
11807   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11808                                 DAG.getConstant(VTBits, dl, MVT::i8));
11809   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11810                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11811
11812   SDValue Hi, Lo;
11813   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11814   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11815   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11816
11817   if (Op.getOpcode() == ISD::SHL_PARTS) {
11818     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11819     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11820   } else {
11821     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11822     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11823   }
11824
11825   SDValue Ops[2] = { Lo, Hi };
11826   return DAG.getMergeValues(Ops, dl);
11827 }
11828
11829 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11830                                            SelectionDAG &DAG) const {
11831   SDValue Src = Op.getOperand(0);
11832   MVT SrcVT = Src.getSimpleValueType();
11833   MVT VT = Op.getSimpleValueType();
11834   SDLoc dl(Op);
11835
11836   if (SrcVT.isVector()) {
11837     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11838       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11839                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11840                          DAG.getUNDEF(SrcVT)));
11841     }
11842     if (SrcVT.getVectorElementType() == MVT::i1) {
11843       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11844       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11845                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11846     }
11847     return SDValue();
11848   }
11849
11850   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11851          "Unknown SINT_TO_FP to lower!");
11852
11853   // These are really Legal; return the operand so the caller accepts it as
11854   // Legal.
11855   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11856     return Op;
11857   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11858       Subtarget->is64Bit()) {
11859     return Op;
11860   }
11861
11862   unsigned Size = SrcVT.getSizeInBits()/8;
11863   MachineFunction &MF = DAG.getMachineFunction();
11864   auto PtrVT = getPointerTy(MF.getDataLayout());
11865   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11866   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11867   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11868                                StackSlot,
11869                                MachinePointerInfo::getFixedStack(SSFI),
11870                                false, false, 0);
11871   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11872 }
11873
11874 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11875                                      SDValue StackSlot,
11876                                      SelectionDAG &DAG) const {
11877   // Build the FILD
11878   SDLoc DL(Op);
11879   SDVTList Tys;
11880   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11881   if (useSSE)
11882     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11883   else
11884     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11885
11886   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11887
11888   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11889   MachineMemOperand *MMO;
11890   if (FI) {
11891     int SSFI = FI->getIndex();
11892     MMO =
11893       DAG.getMachineFunction()
11894       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11895                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11896   } else {
11897     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11898     StackSlot = StackSlot.getOperand(1);
11899   }
11900   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11901   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11902                                            X86ISD::FILD, DL,
11903                                            Tys, Ops, SrcVT, MMO);
11904
11905   if (useSSE) {
11906     Chain = Result.getValue(1);
11907     SDValue InFlag = Result.getValue(2);
11908
11909     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11910     // shouldn't be necessary except that RFP cannot be live across
11911     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11912     MachineFunction &MF = DAG.getMachineFunction();
11913     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11914     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11915     auto PtrVT = getPointerTy(MF.getDataLayout());
11916     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11917     Tys = DAG.getVTList(MVT::Other);
11918     SDValue Ops[] = {
11919       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11920     };
11921     MachineMemOperand *MMO =
11922       DAG.getMachineFunction()
11923       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11924                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11925
11926     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11927                                     Ops, Op.getValueType(), MMO);
11928     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11929                          MachinePointerInfo::getFixedStack(SSFI),
11930                          false, false, false, 0);
11931   }
11932
11933   return Result;
11934 }
11935
11936 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11937 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11938                                                SelectionDAG &DAG) const {
11939   // This algorithm is not obvious. Here it is what we're trying to output:
11940   /*
11941      movq       %rax,  %xmm0
11942      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11943      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11944      #ifdef __SSE3__
11945        haddpd   %xmm0, %xmm0
11946      #else
11947        pshufd   $0x4e, %xmm0, %xmm1
11948        addpd    %xmm1, %xmm0
11949      #endif
11950   */
11951
11952   SDLoc dl(Op);
11953   LLVMContext *Context = DAG.getContext();
11954
11955   // Build some magic constants.
11956   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11957   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11958   auto PtrVT = getPointerTy(DAG.getDataLayout());
11959   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11960
11961   SmallVector<Constant*,2> CV1;
11962   CV1.push_back(
11963     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11964                                       APInt(64, 0x4330000000000000ULL))));
11965   CV1.push_back(
11966     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11967                                       APInt(64, 0x4530000000000000ULL))));
11968   Constant *C1 = ConstantVector::get(CV1);
11969   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11970
11971   // Load the 64-bit value into an XMM register.
11972   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11973                             Op.getOperand(0));
11974   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11975                               MachinePointerInfo::getConstantPool(),
11976                               false, false, false, 16);
11977   SDValue Unpck1 =
11978       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11979
11980   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11981                               MachinePointerInfo::getConstantPool(),
11982                               false, false, false, 16);
11983   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11984   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11985   SDValue Result;
11986
11987   if (Subtarget->hasSSE3()) {
11988     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11989     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11990   } else {
11991     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
11992     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11993                                            S2F, 0x4E, DAG);
11994     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11995                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
11996   }
11997
11998   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11999                      DAG.getIntPtrConstant(0, dl));
12000 }
12001
12002 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12003 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12004                                                SelectionDAG &DAG) const {
12005   SDLoc dl(Op);
12006   // FP constant to bias correct the final result.
12007   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12008                                    MVT::f64);
12009
12010   // Load the 32-bit value into an XMM register.
12011   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12012                              Op.getOperand(0));
12013
12014   // Zero out the upper parts of the register.
12015   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12016
12017   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12018                      DAG.getBitcast(MVT::v2f64, Load),
12019                      DAG.getIntPtrConstant(0, dl));
12020
12021   // Or the load with the bias.
12022   SDValue Or = DAG.getNode(
12023       ISD::OR, dl, MVT::v2i64,
12024       DAG.getBitcast(MVT::v2i64,
12025                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12026       DAG.getBitcast(MVT::v2i64,
12027                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12028   Or =
12029       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12030                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12031
12032   // Subtract the bias.
12033   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12034
12035   // Handle final rounding.
12036   EVT DestVT = Op.getValueType();
12037
12038   if (DestVT.bitsLT(MVT::f64))
12039     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12040                        DAG.getIntPtrConstant(0, dl));
12041   if (DestVT.bitsGT(MVT::f64))
12042     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12043
12044   // Handle final rounding.
12045   return Sub;
12046 }
12047
12048 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12049                                      const X86Subtarget &Subtarget) {
12050   // The algorithm is the following:
12051   // #ifdef __SSE4_1__
12052   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12053   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12054   //                                 (uint4) 0x53000000, 0xaa);
12055   // #else
12056   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12057   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12058   // #endif
12059   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12060   //     return (float4) lo + fhi;
12061
12062   SDLoc DL(Op);
12063   SDValue V = Op->getOperand(0);
12064   EVT VecIntVT = V.getValueType();
12065   bool Is128 = VecIntVT == MVT::v4i32;
12066   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12067   // If we convert to something else than the supported type, e.g., to v4f64,
12068   // abort early.
12069   if (VecFloatVT != Op->getValueType(0))
12070     return SDValue();
12071
12072   unsigned NumElts = VecIntVT.getVectorNumElements();
12073   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12074          "Unsupported custom type");
12075   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12076
12077   // In the #idef/#else code, we have in common:
12078   // - The vector of constants:
12079   // -- 0x4b000000
12080   // -- 0x53000000
12081   // - A shift:
12082   // -- v >> 16
12083
12084   // Create the splat vector for 0x4b000000.
12085   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12086   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12087                            CstLow, CstLow, CstLow, CstLow};
12088   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12089                                   makeArrayRef(&CstLowArray[0], NumElts));
12090   // Create the splat vector for 0x53000000.
12091   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12092   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12093                             CstHigh, CstHigh, CstHigh, CstHigh};
12094   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12095                                    makeArrayRef(&CstHighArray[0], NumElts));
12096
12097   // Create the right shift.
12098   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12099   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12100                              CstShift, CstShift, CstShift, CstShift};
12101   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12102                                     makeArrayRef(&CstShiftArray[0], NumElts));
12103   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12104
12105   SDValue Low, High;
12106   if (Subtarget.hasSSE41()) {
12107     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12108     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12109     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12110     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12111     // Low will be bitcasted right away, so do not bother bitcasting back to its
12112     // original type.
12113     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12114                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12115     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12116     //                                 (uint4) 0x53000000, 0xaa);
12117     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12118     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12119     // High will be bitcasted right away, so do not bother bitcasting back to
12120     // its original type.
12121     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12122                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12123   } else {
12124     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12125     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12126                                      CstMask, CstMask, CstMask);
12127     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12128     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12129     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12130
12131     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12132     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12133   }
12134
12135   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12136   SDValue CstFAdd = DAG.getConstantFP(
12137       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12138   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12139                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12140   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12141                                    makeArrayRef(&CstFAddArray[0], NumElts));
12142
12143   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12144   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12145   SDValue FHigh =
12146       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12147   //     return (float4) lo + fhi;
12148   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12149   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12150 }
12151
12152 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12153                                                SelectionDAG &DAG) const {
12154   SDValue N0 = Op.getOperand(0);
12155   MVT SVT = N0.getSimpleValueType();
12156   SDLoc dl(Op);
12157
12158   switch (SVT.SimpleTy) {
12159   default:
12160     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12161   case MVT::v4i8:
12162   case MVT::v4i16:
12163   case MVT::v8i8:
12164   case MVT::v8i16: {
12165     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12166     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12167                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12168   }
12169   case MVT::v4i32:
12170   case MVT::v8i32:
12171     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12172   case MVT::v16i8:
12173   case MVT::v16i16:
12174     if (Subtarget->hasAVX512())
12175       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12176                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12177   }
12178   llvm_unreachable(nullptr);
12179 }
12180
12181 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12182                                            SelectionDAG &DAG) const {
12183   SDValue N0 = Op.getOperand(0);
12184   SDLoc dl(Op);
12185   auto PtrVT = getPointerTy(DAG.getDataLayout());
12186
12187   if (Op.getValueType().isVector())
12188     return lowerUINT_TO_FP_vec(Op, DAG);
12189
12190   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12191   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12192   // the optimization here.
12193   if (DAG.SignBitIsZero(N0))
12194     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12195
12196   MVT SrcVT = N0.getSimpleValueType();
12197   MVT DstVT = Op.getSimpleValueType();
12198   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12199     return LowerUINT_TO_FP_i64(Op, DAG);
12200   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12201     return LowerUINT_TO_FP_i32(Op, DAG);
12202   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12203     return SDValue();
12204
12205   // Make a 64-bit buffer, and use it to build an FILD.
12206   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12207   if (SrcVT == MVT::i32) {
12208     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12209     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12210     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12211                                   StackSlot, MachinePointerInfo(),
12212                                   false, false, 0);
12213     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12214                                   OffsetSlot, MachinePointerInfo(),
12215                                   false, false, 0);
12216     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12217     return Fild;
12218   }
12219
12220   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12221   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12222                                StackSlot, MachinePointerInfo(),
12223                                false, false, 0);
12224   // For i64 source, we need to add the appropriate power of 2 if the input
12225   // was negative.  This is the same as the optimization in
12226   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12227   // we must be careful to do the computation in x87 extended precision, not
12228   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12229   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12230   MachineMemOperand *MMO =
12231     DAG.getMachineFunction()
12232     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12233                           MachineMemOperand::MOLoad, 8, 8);
12234
12235   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12236   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12237   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12238                                          MVT::i64, MMO);
12239
12240   APInt FF(32, 0x5F800000ULL);
12241
12242   // Check whether the sign bit is set.
12243   SDValue SignSet = DAG.getSetCC(
12244       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12245       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12246
12247   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12248   SDValue FudgePtr = DAG.getConstantPool(
12249       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12250
12251   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12252   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12253   SDValue Four = DAG.getIntPtrConstant(4, dl);
12254   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12255                                Zero, Four);
12256   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12257
12258   // Load the value out, extending it from f32 to f80.
12259   // FIXME: Avoid the extend by constructing the right constant pool?
12260   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12261                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12262                                  MVT::f32, false, false, false, 4);
12263   // Extend everything to 80 bits to force it to be done on x87.
12264   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12265   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12266                      DAG.getIntPtrConstant(0, dl));
12267 }
12268
12269 std::pair<SDValue,SDValue>
12270 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12271                                     bool IsSigned, bool IsReplace) const {
12272   SDLoc DL(Op);
12273
12274   EVT DstTy = Op.getValueType();
12275   auto PtrVT = getPointerTy(DAG.getDataLayout());
12276
12277   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12278     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12279     DstTy = MVT::i64;
12280   }
12281
12282   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12283          DstTy.getSimpleVT() >= MVT::i16 &&
12284          "Unknown FP_TO_INT to lower!");
12285
12286   // These are really Legal.
12287   if (DstTy == MVT::i32 &&
12288       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12289     return std::make_pair(SDValue(), SDValue());
12290   if (Subtarget->is64Bit() &&
12291       DstTy == MVT::i64 &&
12292       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12293     return std::make_pair(SDValue(), SDValue());
12294
12295   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12296   // stack slot, or into the FTOL runtime function.
12297   MachineFunction &MF = DAG.getMachineFunction();
12298   unsigned MemSize = DstTy.getSizeInBits()/8;
12299   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12300   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12301
12302   unsigned Opc;
12303   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12304     Opc = X86ISD::WIN_FTOL;
12305   else
12306     switch (DstTy.getSimpleVT().SimpleTy) {
12307     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12308     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12309     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12310     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12311     }
12312
12313   SDValue Chain = DAG.getEntryNode();
12314   SDValue Value = Op.getOperand(0);
12315   EVT TheVT = Op.getOperand(0).getValueType();
12316   // FIXME This causes a redundant load/store if the SSE-class value is already
12317   // in memory, such as if it is on the callstack.
12318   if (isScalarFPTypeInSSEReg(TheVT)) {
12319     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12320     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12321                          MachinePointerInfo::getFixedStack(SSFI),
12322                          false, false, 0);
12323     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12324     SDValue Ops[] = {
12325       Chain, StackSlot, DAG.getValueType(TheVT)
12326     };
12327
12328     MachineMemOperand *MMO =
12329       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12330                               MachineMemOperand::MOLoad, MemSize, MemSize);
12331     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12332     Chain = Value.getValue(1);
12333     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12334     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12335   }
12336
12337   MachineMemOperand *MMO =
12338     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12339                             MachineMemOperand::MOStore, MemSize, MemSize);
12340
12341   if (Opc != X86ISD::WIN_FTOL) {
12342     // Build the FP_TO_INT*_IN_MEM
12343     SDValue Ops[] = { Chain, Value, StackSlot };
12344     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12345                                            Ops, DstTy, MMO);
12346     return std::make_pair(FIST, StackSlot);
12347   } else {
12348     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12349       DAG.getVTList(MVT::Other, MVT::Glue),
12350       Chain, Value);
12351     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12352       MVT::i32, ftol.getValue(1));
12353     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12354       MVT::i32, eax.getValue(2));
12355     SDValue Ops[] = { eax, edx };
12356     SDValue pair = IsReplace
12357       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12358       : DAG.getMergeValues(Ops, DL);
12359     return std::make_pair(pair, SDValue());
12360   }
12361 }
12362
12363 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12364                               const X86Subtarget *Subtarget) {
12365   MVT VT = Op->getSimpleValueType(0);
12366   SDValue In = Op->getOperand(0);
12367   MVT InVT = In.getSimpleValueType();
12368   SDLoc dl(Op);
12369
12370   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12371     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12372
12373   // Optimize vectors in AVX mode:
12374   //
12375   //   v8i16 -> v8i32
12376   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12377   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12378   //   Concat upper and lower parts.
12379   //
12380   //   v4i32 -> v4i64
12381   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12382   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12383   //   Concat upper and lower parts.
12384   //
12385
12386   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12387       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12388       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12389     return SDValue();
12390
12391   if (Subtarget->hasInt256())
12392     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12393
12394   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12395   SDValue Undef = DAG.getUNDEF(InVT);
12396   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12397   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12398   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12399
12400   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12401                              VT.getVectorNumElements()/2);
12402
12403   OpLo = DAG.getBitcast(HVT, OpLo);
12404   OpHi = DAG.getBitcast(HVT, OpHi);
12405
12406   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12407 }
12408
12409 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12410                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12411   MVT VT = Op->getSimpleValueType(0);
12412   SDValue In = Op->getOperand(0);
12413   MVT InVT = In.getSimpleValueType();
12414   SDLoc DL(Op);
12415   unsigned int NumElts = VT.getVectorNumElements();
12416   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12417     return SDValue();
12418
12419   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12420     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12421
12422   assert(InVT.getVectorElementType() == MVT::i1);
12423   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12424   SDValue One =
12425    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12426   SDValue Zero =
12427    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12428
12429   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12430   if (VT.is512BitVector())
12431     return V;
12432   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12433 }
12434
12435 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12436                                SelectionDAG &DAG) {
12437   if (Subtarget->hasFp256())
12438     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12439       return Res;
12440
12441   return SDValue();
12442 }
12443
12444 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12445                                 SelectionDAG &DAG) {
12446   SDLoc DL(Op);
12447   MVT VT = Op.getSimpleValueType();
12448   SDValue In = Op.getOperand(0);
12449   MVT SVT = In.getSimpleValueType();
12450
12451   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12452     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12453
12454   if (Subtarget->hasFp256())
12455     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12456       return Res;
12457
12458   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12459          VT.getVectorNumElements() != SVT.getVectorNumElements());
12460   return SDValue();
12461 }
12462
12463 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12464   SDLoc DL(Op);
12465   MVT VT = Op.getSimpleValueType();
12466   SDValue In = Op.getOperand(0);
12467   MVT InVT = In.getSimpleValueType();
12468
12469   if (VT == MVT::i1) {
12470     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12471            "Invalid scalar TRUNCATE operation");
12472     if (InVT.getSizeInBits() >= 32)
12473       return SDValue();
12474     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12475     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12476   }
12477   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12478          "Invalid TRUNCATE operation");
12479
12480   // move vector to mask - truncate solution for SKX
12481   if (VT.getVectorElementType() == MVT::i1) {
12482     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12483         Subtarget->hasBWI())
12484       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12485     if ((InVT.is256BitVector() || InVT.is128BitVector())
12486         && InVT.getScalarSizeInBits() <= 16 &&
12487         Subtarget->hasBWI() && Subtarget->hasVLX())
12488       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12489     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12490         Subtarget->hasDQI())
12491       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12492     if ((InVT.is256BitVector() || InVT.is128BitVector())
12493         && InVT.getScalarSizeInBits() >= 32 &&
12494         Subtarget->hasDQI() && Subtarget->hasVLX())
12495       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12496   }
12497
12498   if (VT.getVectorElementType() == MVT::i1) {
12499     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12500     unsigned NumElts = InVT.getVectorNumElements();
12501     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12502     if (InVT.getSizeInBits() < 512) {
12503       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12504       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12505       InVT = ExtVT;
12506     }
12507
12508     SDValue OneV =
12509      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12510     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12511     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12512   }
12513
12514   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12515   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12516       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12517     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12518
12519   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12520     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12521     if (Subtarget->hasInt256()) {
12522       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12523       In = DAG.getBitcast(MVT::v8i32, In);
12524       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12525                                 ShufMask);
12526       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12527                          DAG.getIntPtrConstant(0, DL));
12528     }
12529
12530     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12531                                DAG.getIntPtrConstant(0, DL));
12532     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12533                                DAG.getIntPtrConstant(2, DL));
12534     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12535     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12536     static const int ShufMask[] = {0, 2, 4, 6};
12537     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12538   }
12539
12540   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12541     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12542     if (Subtarget->hasInt256()) {
12543       In = DAG.getBitcast(MVT::v32i8, In);
12544
12545       SmallVector<SDValue,32> pshufbMask;
12546       for (unsigned i = 0; i < 2; ++i) {
12547         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12548         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12549         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12550         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12551         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12552         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12553         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12554         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12555         for (unsigned j = 0; j < 8; ++j)
12556           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12557       }
12558       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12559       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12560       In = DAG.getBitcast(MVT::v4i64, In);
12561
12562       static const int ShufMask[] = {0,  2,  -1,  -1};
12563       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12564                                 &ShufMask[0]);
12565       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12566                        DAG.getIntPtrConstant(0, DL));
12567       return DAG.getBitcast(VT, In);
12568     }
12569
12570     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12571                                DAG.getIntPtrConstant(0, DL));
12572
12573     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12574                                DAG.getIntPtrConstant(4, DL));
12575
12576     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12577     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12578
12579     // The PSHUFB mask:
12580     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12581                                    -1, -1, -1, -1, -1, -1, -1, -1};
12582
12583     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12584     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12585     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12586
12587     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12588     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12589
12590     // The MOVLHPS Mask:
12591     static const int ShufMask2[] = {0, 1, 4, 5};
12592     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12593     return DAG.getBitcast(MVT::v8i16, res);
12594   }
12595
12596   // Handle truncation of V256 to V128 using shuffles.
12597   if (!VT.is128BitVector() || !InVT.is256BitVector())
12598     return SDValue();
12599
12600   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12601
12602   unsigned NumElems = VT.getVectorNumElements();
12603   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12604
12605   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12606   // Prepare truncation shuffle mask
12607   for (unsigned i = 0; i != NumElems; ++i)
12608     MaskVec[i] = i * 2;
12609   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12610                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12611   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12612                      DAG.getIntPtrConstant(0, DL));
12613 }
12614
12615 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12616                                            SelectionDAG &DAG) const {
12617   assert(!Op.getSimpleValueType().isVector());
12618
12619   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12620     /*IsSigned=*/ true, /*IsReplace=*/ false);
12621   SDValue FIST = Vals.first, StackSlot = Vals.second;
12622   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12623   if (!FIST.getNode()) return Op;
12624
12625   if (StackSlot.getNode())
12626     // Load the result.
12627     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12628                        FIST, StackSlot, MachinePointerInfo(),
12629                        false, false, false, 0);
12630
12631   // The node is the result.
12632   return FIST;
12633 }
12634
12635 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12636                                            SelectionDAG &DAG) const {
12637   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12638     /*IsSigned=*/ false, /*IsReplace=*/ false);
12639   SDValue FIST = Vals.first, StackSlot = Vals.second;
12640   assert(FIST.getNode() && "Unexpected failure");
12641
12642   if (StackSlot.getNode())
12643     // Load the result.
12644     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12645                        FIST, StackSlot, MachinePointerInfo(),
12646                        false, false, false, 0);
12647
12648   // The node is the result.
12649   return FIST;
12650 }
12651
12652 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12653   SDLoc DL(Op);
12654   MVT VT = Op.getSimpleValueType();
12655   SDValue In = Op.getOperand(0);
12656   MVT SVT = In.getSimpleValueType();
12657
12658   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12659
12660   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12661                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12662                                  In, DAG.getUNDEF(SVT)));
12663 }
12664
12665 /// The only differences between FABS and FNEG are the mask and the logic op.
12666 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12667 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12668   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12669          "Wrong opcode for lowering FABS or FNEG.");
12670
12671   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12672
12673   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12674   // into an FNABS. We'll lower the FABS after that if it is still in use.
12675   if (IsFABS)
12676     for (SDNode *User : Op->uses())
12677       if (User->getOpcode() == ISD::FNEG)
12678         return Op;
12679
12680   SDLoc dl(Op);
12681   MVT VT = Op.getSimpleValueType();
12682
12683   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12684   // decide if we should generate a 16-byte constant mask when we only need 4 or
12685   // 8 bytes for the scalar case.
12686
12687   MVT LogicVT;
12688   MVT EltVT;
12689   unsigned NumElts;
12690   
12691   if (VT.isVector()) {
12692     LogicVT = VT;
12693     EltVT = VT.getVectorElementType();
12694     NumElts = VT.getVectorNumElements();
12695   } else {
12696     // There are no scalar bitwise logical SSE/AVX instructions, so we
12697     // generate a 16-byte vector constant and logic op even for the scalar case.
12698     // Using a 16-byte mask allows folding the load of the mask with
12699     // the logic op, so it can save (~4 bytes) on code size.
12700     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12701     EltVT = VT;
12702     NumElts = (VT == MVT::f64) ? 2 : 4;
12703   }
12704
12705   unsigned EltBits = EltVT.getSizeInBits();
12706   LLVMContext *Context = DAG.getContext();
12707   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12708   APInt MaskElt =
12709     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12710   Constant *C = ConstantInt::get(*Context, MaskElt);
12711   C = ConstantVector::getSplat(NumElts, C);
12712   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12713   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12714   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12715   SDValue Mask = DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12716                              MachinePointerInfo::getConstantPool(),
12717                              false, false, false, Alignment);
12718
12719   SDValue Op0 = Op.getOperand(0);
12720   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12721   unsigned LogicOp =
12722     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12723   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12724
12725   if (VT.isVector())
12726     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12727
12728   // For the scalar case extend to a 128-bit vector, perform the logic op,
12729   // and extract the scalar result back out.
12730   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12731   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12732   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12733                      DAG.getIntPtrConstant(0, dl));
12734 }
12735
12736 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12737   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12738   LLVMContext *Context = DAG.getContext();
12739   SDValue Op0 = Op.getOperand(0);
12740   SDValue Op1 = Op.getOperand(1);
12741   SDLoc dl(Op);
12742   MVT VT = Op.getSimpleValueType();
12743   MVT SrcVT = Op1.getSimpleValueType();
12744
12745   // If second operand is smaller, extend it first.
12746   if (SrcVT.bitsLT(VT)) {
12747     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12748     SrcVT = VT;
12749   }
12750   // And if it is bigger, shrink it first.
12751   if (SrcVT.bitsGT(VT)) {
12752     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12753     SrcVT = VT;
12754   }
12755
12756   // At this point the operands and the result should have the same
12757   // type, and that won't be f80 since that is not custom lowered.
12758
12759   const fltSemantics &Sem =
12760       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12761   const unsigned SizeInBits = VT.getSizeInBits();
12762
12763   SmallVector<Constant *, 4> CV(
12764       VT == MVT::f64 ? 2 : 4,
12765       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12766
12767   // First, clear all bits but the sign bit from the second operand (sign).
12768   CV[0] = ConstantFP::get(*Context,
12769                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12770   Constant *C = ConstantVector::get(CV);
12771   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12772   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12773
12774   // Perform all logic operations as 16-byte vectors because there are no
12775   // scalar FP logic instructions in SSE. This allows load folding of the
12776   // constants into the logic instructions.
12777   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12778   SDValue Mask1 = DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12779                               MachinePointerInfo::getConstantPool(),
12780                               false, false, false, 16);
12781   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12782   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12783
12784   // Next, clear the sign bit from the first operand (magnitude).
12785   // If it's a constant, we can clear it here.
12786   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12787     APFloat APF = Op0CN->getValueAPF();
12788     // If the magnitude is a positive zero, the sign bit alone is enough.
12789     if (APF.isPosZero())
12790       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12791                          DAG.getIntPtrConstant(0, dl));
12792     APF.clearSign();
12793     CV[0] = ConstantFP::get(*Context, APF);
12794   } else {
12795     CV[0] = ConstantFP::get(
12796         *Context,
12797         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12798   }
12799   C = ConstantVector::get(CV);
12800   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12801   SDValue Val = DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12802                             MachinePointerInfo::getConstantPool(),
12803                             false, false, false, 16);
12804   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12805   if (!isa<ConstantFPSDNode>(Op0)) {
12806     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12807     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12808   }
12809   // OR the magnitude value with the sign bit.
12810   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12811   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12812                      DAG.getIntPtrConstant(0, dl));
12813 }
12814
12815 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12816   SDValue N0 = Op.getOperand(0);
12817   SDLoc dl(Op);
12818   MVT VT = Op.getSimpleValueType();
12819
12820   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12821   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12822                                   DAG.getConstant(1, dl, VT));
12823   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12824 }
12825
12826 // Check whether an OR'd tree is PTEST-able.
12827 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12828                                       SelectionDAG &DAG) {
12829   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12830
12831   if (!Subtarget->hasSSE41())
12832     return SDValue();
12833
12834   if (!Op->hasOneUse())
12835     return SDValue();
12836
12837   SDNode *N = Op.getNode();
12838   SDLoc DL(N);
12839
12840   SmallVector<SDValue, 8> Opnds;
12841   DenseMap<SDValue, unsigned> VecInMap;
12842   SmallVector<SDValue, 8> VecIns;
12843   EVT VT = MVT::Other;
12844
12845   // Recognize a special case where a vector is casted into wide integer to
12846   // test all 0s.
12847   Opnds.push_back(N->getOperand(0));
12848   Opnds.push_back(N->getOperand(1));
12849
12850   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12851     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12852     // BFS traverse all OR'd operands.
12853     if (I->getOpcode() == ISD::OR) {
12854       Opnds.push_back(I->getOperand(0));
12855       Opnds.push_back(I->getOperand(1));
12856       // Re-evaluate the number of nodes to be traversed.
12857       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12858       continue;
12859     }
12860
12861     // Quit if a non-EXTRACT_VECTOR_ELT
12862     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12863       return SDValue();
12864
12865     // Quit if without a constant index.
12866     SDValue Idx = I->getOperand(1);
12867     if (!isa<ConstantSDNode>(Idx))
12868       return SDValue();
12869
12870     SDValue ExtractedFromVec = I->getOperand(0);
12871     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12872     if (M == VecInMap.end()) {
12873       VT = ExtractedFromVec.getValueType();
12874       // Quit if not 128/256-bit vector.
12875       if (!VT.is128BitVector() && !VT.is256BitVector())
12876         return SDValue();
12877       // Quit if not the same type.
12878       if (VecInMap.begin() != VecInMap.end() &&
12879           VT != VecInMap.begin()->first.getValueType())
12880         return SDValue();
12881       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12882       VecIns.push_back(ExtractedFromVec);
12883     }
12884     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12885   }
12886
12887   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12888          "Not extracted from 128-/256-bit vector.");
12889
12890   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12891
12892   for (DenseMap<SDValue, unsigned>::const_iterator
12893         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12894     // Quit if not all elements are used.
12895     if (I->second != FullMask)
12896       return SDValue();
12897   }
12898
12899   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12900
12901   // Cast all vectors into TestVT for PTEST.
12902   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12903     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12904
12905   // If more than one full vectors are evaluated, OR them first before PTEST.
12906   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12907     // Each iteration will OR 2 nodes and append the result until there is only
12908     // 1 node left, i.e. the final OR'd value of all vectors.
12909     SDValue LHS = VecIns[Slot];
12910     SDValue RHS = VecIns[Slot + 1];
12911     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12912   }
12913
12914   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12915                      VecIns.back(), VecIns.back());
12916 }
12917
12918 /// \brief return true if \c Op has a use that doesn't just read flags.
12919 static bool hasNonFlagsUse(SDValue Op) {
12920   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12921        ++UI) {
12922     SDNode *User = *UI;
12923     unsigned UOpNo = UI.getOperandNo();
12924     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12925       // Look pass truncate.
12926       UOpNo = User->use_begin().getOperandNo();
12927       User = *User->use_begin();
12928     }
12929
12930     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12931         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12932       return true;
12933   }
12934   return false;
12935 }
12936
12937 /// Emit nodes that will be selected as "test Op0,Op0", or something
12938 /// equivalent.
12939 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12940                                     SelectionDAG &DAG) const {
12941   if (Op.getValueType() == MVT::i1) {
12942     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12943     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12944                        DAG.getConstant(0, dl, MVT::i8));
12945   }
12946   // CF and OF aren't always set the way we want. Determine which
12947   // of these we need.
12948   bool NeedCF = false;
12949   bool NeedOF = false;
12950   switch (X86CC) {
12951   default: break;
12952   case X86::COND_A: case X86::COND_AE:
12953   case X86::COND_B: case X86::COND_BE:
12954     NeedCF = true;
12955     break;
12956   case X86::COND_G: case X86::COND_GE:
12957   case X86::COND_L: case X86::COND_LE:
12958   case X86::COND_O: case X86::COND_NO: {
12959     // Check if we really need to set the
12960     // Overflow flag. If NoSignedWrap is present
12961     // that is not actually needed.
12962     switch (Op->getOpcode()) {
12963     case ISD::ADD:
12964     case ISD::SUB:
12965     case ISD::MUL:
12966     case ISD::SHL: {
12967       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12968       if (BinNode->Flags.hasNoSignedWrap())
12969         break;
12970     }
12971     default:
12972       NeedOF = true;
12973       break;
12974     }
12975     break;
12976   }
12977   }
12978   // See if we can use the EFLAGS value from the operand instead of
12979   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12980   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12981   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12982     // Emit a CMP with 0, which is the TEST pattern.
12983     //if (Op.getValueType() == MVT::i1)
12984     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12985     //                     DAG.getConstant(0, MVT::i1));
12986     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12987                        DAG.getConstant(0, dl, Op.getValueType()));
12988   }
12989   unsigned Opcode = 0;
12990   unsigned NumOperands = 0;
12991
12992   // Truncate operations may prevent the merge of the SETCC instruction
12993   // and the arithmetic instruction before it. Attempt to truncate the operands
12994   // of the arithmetic instruction and use a reduced bit-width instruction.
12995   bool NeedTruncation = false;
12996   SDValue ArithOp = Op;
12997   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12998     SDValue Arith = Op->getOperand(0);
12999     // Both the trunc and the arithmetic op need to have one user each.
13000     if (Arith->hasOneUse())
13001       switch (Arith.getOpcode()) {
13002         default: break;
13003         case ISD::ADD:
13004         case ISD::SUB:
13005         case ISD::AND:
13006         case ISD::OR:
13007         case ISD::XOR: {
13008           NeedTruncation = true;
13009           ArithOp = Arith;
13010         }
13011       }
13012   }
13013
13014   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13015   // which may be the result of a CAST.  We use the variable 'Op', which is the
13016   // non-casted variable when we check for possible users.
13017   switch (ArithOp.getOpcode()) {
13018   case ISD::ADD:
13019     // Due to an isel shortcoming, be conservative if this add is likely to be
13020     // selected as part of a load-modify-store instruction. When the root node
13021     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13022     // uses of other nodes in the match, such as the ADD in this case. This
13023     // leads to the ADD being left around and reselected, with the result being
13024     // two adds in the output.  Alas, even if none our users are stores, that
13025     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13026     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13027     // climbing the DAG back to the root, and it doesn't seem to be worth the
13028     // effort.
13029     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13030          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13031       if (UI->getOpcode() != ISD::CopyToReg &&
13032           UI->getOpcode() != ISD::SETCC &&
13033           UI->getOpcode() != ISD::STORE)
13034         goto default_case;
13035
13036     if (ConstantSDNode *C =
13037         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13038       // An add of one will be selected as an INC.
13039       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13040         Opcode = X86ISD::INC;
13041         NumOperands = 1;
13042         break;
13043       }
13044
13045       // An add of negative one (subtract of one) will be selected as a DEC.
13046       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13047         Opcode = X86ISD::DEC;
13048         NumOperands = 1;
13049         break;
13050       }
13051     }
13052
13053     // Otherwise use a regular EFLAGS-setting add.
13054     Opcode = X86ISD::ADD;
13055     NumOperands = 2;
13056     break;
13057   case ISD::SHL:
13058   case ISD::SRL:
13059     // If we have a constant logical shift that's only used in a comparison
13060     // against zero turn it into an equivalent AND. This allows turning it into
13061     // a TEST instruction later.
13062     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13063         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13064       EVT VT = Op.getValueType();
13065       unsigned BitWidth = VT.getSizeInBits();
13066       unsigned ShAmt = Op->getConstantOperandVal(1);
13067       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13068         break;
13069       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13070                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13071                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13072       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13073         break;
13074       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13075                                 DAG.getConstant(Mask, dl, VT));
13076       DAG.ReplaceAllUsesWith(Op, New);
13077       Op = New;
13078     }
13079     break;
13080
13081   case ISD::AND:
13082     // If the primary and result isn't used, don't bother using X86ISD::AND,
13083     // because a TEST instruction will be better.
13084     if (!hasNonFlagsUse(Op))
13085       break;
13086     // FALL THROUGH
13087   case ISD::SUB:
13088   case ISD::OR:
13089   case ISD::XOR:
13090     // Due to the ISEL shortcoming noted above, be conservative if this op is
13091     // likely to be selected as part of a load-modify-store instruction.
13092     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13093            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13094       if (UI->getOpcode() == ISD::STORE)
13095         goto default_case;
13096
13097     // Otherwise use a regular EFLAGS-setting instruction.
13098     switch (ArithOp.getOpcode()) {
13099     default: llvm_unreachable("unexpected operator!");
13100     case ISD::SUB: Opcode = X86ISD::SUB; break;
13101     case ISD::XOR: Opcode = X86ISD::XOR; break;
13102     case ISD::AND: Opcode = X86ISD::AND; break;
13103     case ISD::OR: {
13104       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13105         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13106         if (EFLAGS.getNode())
13107           return EFLAGS;
13108       }
13109       Opcode = X86ISD::OR;
13110       break;
13111     }
13112     }
13113
13114     NumOperands = 2;
13115     break;
13116   case X86ISD::ADD:
13117   case X86ISD::SUB:
13118   case X86ISD::INC:
13119   case X86ISD::DEC:
13120   case X86ISD::OR:
13121   case X86ISD::XOR:
13122   case X86ISD::AND:
13123     return SDValue(Op.getNode(), 1);
13124   default:
13125   default_case:
13126     break;
13127   }
13128
13129   // If we found that truncation is beneficial, perform the truncation and
13130   // update 'Op'.
13131   if (NeedTruncation) {
13132     EVT VT = Op.getValueType();
13133     SDValue WideVal = Op->getOperand(0);
13134     EVT WideVT = WideVal.getValueType();
13135     unsigned ConvertedOp = 0;
13136     // Use a target machine opcode to prevent further DAGCombine
13137     // optimizations that may separate the arithmetic operations
13138     // from the setcc node.
13139     switch (WideVal.getOpcode()) {
13140       default: break;
13141       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13142       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13143       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13144       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13145       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13146     }
13147
13148     if (ConvertedOp) {
13149       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13150       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13151         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13152         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13153         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13154       }
13155     }
13156   }
13157
13158   if (Opcode == 0)
13159     // Emit a CMP with 0, which is the TEST pattern.
13160     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13161                        DAG.getConstant(0, dl, Op.getValueType()));
13162
13163   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13164   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13165
13166   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13167   DAG.ReplaceAllUsesWith(Op, New);
13168   return SDValue(New.getNode(), 1);
13169 }
13170
13171 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13172 /// equivalent.
13173 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13174                                    SDLoc dl, SelectionDAG &DAG) const {
13175   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13176     if (C->getAPIntValue() == 0)
13177       return EmitTest(Op0, X86CC, dl, DAG);
13178
13179      if (Op0.getValueType() == MVT::i1)
13180        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13181   }
13182
13183   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13184        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13185     // Do the comparison at i32 if it's smaller, besides the Atom case.
13186     // This avoids subregister aliasing issues. Keep the smaller reference
13187     // if we're optimizing for size, however, as that'll allow better folding
13188     // of memory operations.
13189     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13190         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13191             Attribute::MinSize) &&
13192         !Subtarget->isAtom()) {
13193       unsigned ExtendOp =
13194           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13195       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13196       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13197     }
13198     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13199     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13200     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13201                               Op0, Op1);
13202     return SDValue(Sub.getNode(), 1);
13203   }
13204   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13205 }
13206
13207 /// Convert a comparison if required by the subtarget.
13208 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13209                                                  SelectionDAG &DAG) const {
13210   // If the subtarget does not support the FUCOMI instruction, floating-point
13211   // comparisons have to be converted.
13212   if (Subtarget->hasCMov() ||
13213       Cmp.getOpcode() != X86ISD::CMP ||
13214       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13215       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13216     return Cmp;
13217
13218   // The instruction selector will select an FUCOM instruction instead of
13219   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13220   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13221   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13222   SDLoc dl(Cmp);
13223   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13224   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13225   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13226                             DAG.getConstant(8, dl, MVT::i8));
13227   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13228   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13229 }
13230
13231 /// The minimum architected relative accuracy is 2^-12. We need one
13232 /// Newton-Raphson step to have a good float result (24 bits of precision).
13233 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13234                                             DAGCombinerInfo &DCI,
13235                                             unsigned &RefinementSteps,
13236                                             bool &UseOneConstNR) const {
13237   EVT VT = Op.getValueType();
13238   const char *RecipOp;
13239
13240   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13241   // TODO: Add support for AVX512 (v16f32).
13242   // It is likely not profitable to do this for f64 because a double-precision
13243   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13244   // instructions: convert to single, rsqrtss, convert back to double, refine
13245   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13246   // along with FMA, this could be a throughput win.
13247   if (VT == MVT::f32 && Subtarget->hasSSE1())
13248     RecipOp = "sqrtf";
13249   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13250            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13251     RecipOp = "vec-sqrtf";
13252   else
13253     return SDValue();
13254
13255   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13256   if (!Recips.isEnabled(RecipOp))
13257     return SDValue();
13258
13259   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13260   UseOneConstNR = false;
13261   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13262 }
13263
13264 /// The minimum architected relative accuracy is 2^-12. We need one
13265 /// Newton-Raphson step to have a good float result (24 bits of precision).
13266 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13267                                             DAGCombinerInfo &DCI,
13268                                             unsigned &RefinementSteps) const {
13269   EVT VT = Op.getValueType();
13270   const char *RecipOp;
13271
13272   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13273   // TODO: Add support for AVX512 (v16f32).
13274   // It is likely not profitable to do this for f64 because a double-precision
13275   // reciprocal estimate with refinement on x86 prior to FMA requires
13276   // 15 instructions: convert to single, rcpss, convert back to double, refine
13277   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13278   // along with FMA, this could be a throughput win.
13279   if (VT == MVT::f32 && Subtarget->hasSSE1())
13280     RecipOp = "divf";
13281   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13282            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13283     RecipOp = "vec-divf";
13284   else
13285     return SDValue();
13286
13287   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13288   if (!Recips.isEnabled(RecipOp))
13289     return SDValue();
13290
13291   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13292   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13293 }
13294
13295 /// If we have at least two divisions that use the same divisor, convert to
13296 /// multplication by a reciprocal. This may need to be adjusted for a given
13297 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13298 /// This is because we still need one division to calculate the reciprocal and
13299 /// then we need two multiplies by that reciprocal as replacements for the
13300 /// original divisions.
13301 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13302   return NumUsers > 1;
13303 }
13304
13305 static bool isAllOnes(SDValue V) {
13306   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13307   return C && C->isAllOnesValue();
13308 }
13309
13310 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13311 /// if it's possible.
13312 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13313                                      SDLoc dl, SelectionDAG &DAG) const {
13314   SDValue Op0 = And.getOperand(0);
13315   SDValue Op1 = And.getOperand(1);
13316   if (Op0.getOpcode() == ISD::TRUNCATE)
13317     Op0 = Op0.getOperand(0);
13318   if (Op1.getOpcode() == ISD::TRUNCATE)
13319     Op1 = Op1.getOperand(0);
13320
13321   SDValue LHS, RHS;
13322   if (Op1.getOpcode() == ISD::SHL)
13323     std::swap(Op0, Op1);
13324   if (Op0.getOpcode() == ISD::SHL) {
13325     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13326       if (And00C->getZExtValue() == 1) {
13327         // If we looked past a truncate, check that it's only truncating away
13328         // known zeros.
13329         unsigned BitWidth = Op0.getValueSizeInBits();
13330         unsigned AndBitWidth = And.getValueSizeInBits();
13331         if (BitWidth > AndBitWidth) {
13332           APInt Zeros, Ones;
13333           DAG.computeKnownBits(Op0, Zeros, Ones);
13334           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13335             return SDValue();
13336         }
13337         LHS = Op1;
13338         RHS = Op0.getOperand(1);
13339       }
13340   } else if (Op1.getOpcode() == ISD::Constant) {
13341     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13342     uint64_t AndRHSVal = AndRHS->getZExtValue();
13343     SDValue AndLHS = Op0;
13344
13345     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13346       LHS = AndLHS.getOperand(0);
13347       RHS = AndLHS.getOperand(1);
13348     }
13349
13350     // Use BT if the immediate can't be encoded in a TEST instruction.
13351     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13352       LHS = AndLHS;
13353       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13354     }
13355   }
13356
13357   if (LHS.getNode()) {
13358     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13359     // instruction.  Since the shift amount is in-range-or-undefined, we know
13360     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13361     // the encoding for the i16 version is larger than the i32 version.
13362     // Also promote i16 to i32 for performance / code size reason.
13363     if (LHS.getValueType() == MVT::i8 ||
13364         LHS.getValueType() == MVT::i16)
13365       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13366
13367     // If the operand types disagree, extend the shift amount to match.  Since
13368     // BT ignores high bits (like shifts) we can use anyextend.
13369     if (LHS.getValueType() != RHS.getValueType())
13370       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13371
13372     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13373     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13374     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13375                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13376   }
13377
13378   return SDValue();
13379 }
13380
13381 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13382 /// mask CMPs.
13383 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13384                               SDValue &Op1) {
13385   unsigned SSECC;
13386   bool Swap = false;
13387
13388   // SSE Condition code mapping:
13389   //  0 - EQ
13390   //  1 - LT
13391   //  2 - LE
13392   //  3 - UNORD
13393   //  4 - NEQ
13394   //  5 - NLT
13395   //  6 - NLE
13396   //  7 - ORD
13397   switch (SetCCOpcode) {
13398   default: llvm_unreachable("Unexpected SETCC condition");
13399   case ISD::SETOEQ:
13400   case ISD::SETEQ:  SSECC = 0; break;
13401   case ISD::SETOGT:
13402   case ISD::SETGT:  Swap = true; // Fallthrough
13403   case ISD::SETLT:
13404   case ISD::SETOLT: SSECC = 1; break;
13405   case ISD::SETOGE:
13406   case ISD::SETGE:  Swap = true; // Fallthrough
13407   case ISD::SETLE:
13408   case ISD::SETOLE: SSECC = 2; break;
13409   case ISD::SETUO:  SSECC = 3; break;
13410   case ISD::SETUNE:
13411   case ISD::SETNE:  SSECC = 4; break;
13412   case ISD::SETULE: Swap = true; // Fallthrough
13413   case ISD::SETUGE: SSECC = 5; break;
13414   case ISD::SETULT: Swap = true; // Fallthrough
13415   case ISD::SETUGT: SSECC = 6; break;
13416   case ISD::SETO:   SSECC = 7; break;
13417   case ISD::SETUEQ:
13418   case ISD::SETONE: SSECC = 8; break;
13419   }
13420   if (Swap)
13421     std::swap(Op0, Op1);
13422
13423   return SSECC;
13424 }
13425
13426 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13427 // ones, and then concatenate the result back.
13428 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13429   MVT VT = Op.getSimpleValueType();
13430
13431   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13432          "Unsupported value type for operation");
13433
13434   unsigned NumElems = VT.getVectorNumElements();
13435   SDLoc dl(Op);
13436   SDValue CC = Op.getOperand(2);
13437
13438   // Extract the LHS vectors
13439   SDValue LHS = Op.getOperand(0);
13440   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13441   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13442
13443   // Extract the RHS vectors
13444   SDValue RHS = Op.getOperand(1);
13445   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13446   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13447
13448   // Issue the operation on the smaller types and concatenate the result back
13449   MVT EltVT = VT.getVectorElementType();
13450   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13451   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13452                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13453                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13454 }
13455
13456 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13457   SDValue Op0 = Op.getOperand(0);
13458   SDValue Op1 = Op.getOperand(1);
13459   SDValue CC = Op.getOperand(2);
13460   MVT VT = Op.getSimpleValueType();
13461   SDLoc dl(Op);
13462
13463   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13464          "Unexpected type for boolean compare operation");
13465   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13466   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13467                                DAG.getConstant(-1, dl, VT));
13468   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13469                                DAG.getConstant(-1, dl, VT));
13470   switch (SetCCOpcode) {
13471   default: llvm_unreachable("Unexpected SETCC condition");
13472   case ISD::SETEQ:
13473     // (x == y) -> ~(x ^ y)
13474     return DAG.getNode(ISD::XOR, dl, VT,
13475                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13476                        DAG.getConstant(-1, dl, VT));
13477   case ISD::SETNE:
13478     // (x != y) -> (x ^ y)
13479     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13480   case ISD::SETUGT:
13481   case ISD::SETGT:
13482     // (x > y) -> (x & ~y)
13483     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13484   case ISD::SETULT:
13485   case ISD::SETLT:
13486     // (x < y) -> (~x & y)
13487     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13488   case ISD::SETULE:
13489   case ISD::SETLE:
13490     // (x <= y) -> (~x | y)
13491     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13492   case ISD::SETUGE:
13493   case ISD::SETGE:
13494     // (x >=y) -> (x | ~y)
13495     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13496   }
13497 }
13498
13499 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13500                                      const X86Subtarget *Subtarget) {
13501   SDValue Op0 = Op.getOperand(0);
13502   SDValue Op1 = Op.getOperand(1);
13503   SDValue CC = Op.getOperand(2);
13504   MVT VT = Op.getSimpleValueType();
13505   SDLoc dl(Op);
13506
13507   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13508          Op.getValueType().getScalarType() == MVT::i1 &&
13509          "Cannot set masked compare for this operation");
13510
13511   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13512   unsigned  Opc = 0;
13513   bool Unsigned = false;
13514   bool Swap = false;
13515   unsigned SSECC;
13516   switch (SetCCOpcode) {
13517   default: llvm_unreachable("Unexpected SETCC condition");
13518   case ISD::SETNE:  SSECC = 4; break;
13519   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13520   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13521   case ISD::SETLT:  Swap = true; //fall-through
13522   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13523   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13524   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13525   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13526   case ISD::SETULE: Unsigned = true; //fall-through
13527   case ISD::SETLE:  SSECC = 2; break;
13528   }
13529
13530   if (Swap)
13531     std::swap(Op0, Op1);
13532   if (Opc)
13533     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13534   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13535   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13536                      DAG.getConstant(SSECC, dl, MVT::i8));
13537 }
13538
13539 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13540 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13541 /// return an empty value.
13542 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13543 {
13544   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13545   if (!BV)
13546     return SDValue();
13547
13548   MVT VT = Op1.getSimpleValueType();
13549   MVT EVT = VT.getVectorElementType();
13550   unsigned n = VT.getVectorNumElements();
13551   SmallVector<SDValue, 8> ULTOp1;
13552
13553   for (unsigned i = 0; i < n; ++i) {
13554     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13555     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13556       return SDValue();
13557
13558     // Avoid underflow.
13559     APInt Val = Elt->getAPIntValue();
13560     if (Val == 0)
13561       return SDValue();
13562
13563     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13564   }
13565
13566   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13567 }
13568
13569 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13570                            SelectionDAG &DAG) {
13571   SDValue Op0 = Op.getOperand(0);
13572   SDValue Op1 = Op.getOperand(1);
13573   SDValue CC = Op.getOperand(2);
13574   MVT VT = Op.getSimpleValueType();
13575   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13576   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13577   SDLoc dl(Op);
13578
13579   if (isFP) {
13580 #ifndef NDEBUG
13581     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13582     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13583 #endif
13584
13585     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13586     unsigned Opc = X86ISD::CMPP;
13587     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13588       assert(VT.getVectorNumElements() <= 16);
13589       Opc = X86ISD::CMPM;
13590     }
13591     // In the two special cases we can't handle, emit two comparisons.
13592     if (SSECC == 8) {
13593       unsigned CC0, CC1;
13594       unsigned CombineOpc;
13595       if (SetCCOpcode == ISD::SETUEQ) {
13596         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13597       } else {
13598         assert(SetCCOpcode == ISD::SETONE);
13599         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13600       }
13601
13602       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13603                                  DAG.getConstant(CC0, dl, MVT::i8));
13604       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13605                                  DAG.getConstant(CC1, dl, MVT::i8));
13606       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13607     }
13608     // Handle all other FP comparisons here.
13609     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13610                        DAG.getConstant(SSECC, dl, MVT::i8));
13611   }
13612
13613   // Break 256-bit integer vector compare into smaller ones.
13614   if (VT.is256BitVector() && !Subtarget->hasInt256())
13615     return Lower256IntVSETCC(Op, DAG);
13616
13617   EVT OpVT = Op1.getValueType();
13618   if (OpVT.getVectorElementType() == MVT::i1)
13619     return LowerBoolVSETCC_AVX512(Op, DAG);
13620
13621   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13622   if (Subtarget->hasAVX512()) {
13623     if (Op1.getValueType().is512BitVector() ||
13624         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13625         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13626       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13627
13628     // In AVX-512 architecture setcc returns mask with i1 elements,
13629     // But there is no compare instruction for i8 and i16 elements in KNL.
13630     // We are not talking about 512-bit operands in this case, these
13631     // types are illegal.
13632     if (MaskResult &&
13633         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13634          OpVT.getVectorElementType().getSizeInBits() >= 8))
13635       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13636                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13637   }
13638
13639   // We are handling one of the integer comparisons here.  Since SSE only has
13640   // GT and EQ comparisons for integer, swapping operands and multiple
13641   // operations may be required for some comparisons.
13642   unsigned Opc;
13643   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13644   bool Subus = false;
13645
13646   switch (SetCCOpcode) {
13647   default: llvm_unreachable("Unexpected SETCC condition");
13648   case ISD::SETNE:  Invert = true;
13649   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13650   case ISD::SETLT:  Swap = true;
13651   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13652   case ISD::SETGE:  Swap = true;
13653   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13654                     Invert = true; break;
13655   case ISD::SETULT: Swap = true;
13656   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13657                     FlipSigns = true; break;
13658   case ISD::SETUGE: Swap = true;
13659   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13660                     FlipSigns = true; Invert = true; break;
13661   }
13662
13663   // Special case: Use min/max operations for SETULE/SETUGE
13664   MVT VET = VT.getVectorElementType();
13665   bool hasMinMax =
13666        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13667     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13668
13669   if (hasMinMax) {
13670     switch (SetCCOpcode) {
13671     default: break;
13672     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13673     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13674     }
13675
13676     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13677   }
13678
13679   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13680   if (!MinMax && hasSubus) {
13681     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13682     // Op0 u<= Op1:
13683     //   t = psubus Op0, Op1
13684     //   pcmpeq t, <0..0>
13685     switch (SetCCOpcode) {
13686     default: break;
13687     case ISD::SETULT: {
13688       // If the comparison is against a constant we can turn this into a
13689       // setule.  With psubus, setule does not require a swap.  This is
13690       // beneficial because the constant in the register is no longer
13691       // destructed as the destination so it can be hoisted out of a loop.
13692       // Only do this pre-AVX since vpcmp* is no longer destructive.
13693       if (Subtarget->hasAVX())
13694         break;
13695       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13696       if (ULEOp1.getNode()) {
13697         Op1 = ULEOp1;
13698         Subus = true; Invert = false; Swap = false;
13699       }
13700       break;
13701     }
13702     // Psubus is better than flip-sign because it requires no inversion.
13703     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13704     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13705     }
13706
13707     if (Subus) {
13708       Opc = X86ISD::SUBUS;
13709       FlipSigns = false;
13710     }
13711   }
13712
13713   if (Swap)
13714     std::swap(Op0, Op1);
13715
13716   // Check that the operation in question is available (most are plain SSE2,
13717   // but PCMPGTQ and PCMPEQQ have different requirements).
13718   if (VT == MVT::v2i64) {
13719     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13720       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13721
13722       // First cast everything to the right type.
13723       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13724       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13725
13726       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13727       // bits of the inputs before performing those operations. The lower
13728       // compare is always unsigned.
13729       SDValue SB;
13730       if (FlipSigns) {
13731         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13732       } else {
13733         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13734         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13735         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13736                          Sign, Zero, Sign, Zero);
13737       }
13738       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13739       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13740
13741       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13742       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13743       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13744
13745       // Create masks for only the low parts/high parts of the 64 bit integers.
13746       static const int MaskHi[] = { 1, 1, 3, 3 };
13747       static const int MaskLo[] = { 0, 0, 2, 2 };
13748       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13749       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13750       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13751
13752       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13753       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13754
13755       if (Invert)
13756         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13757
13758       return DAG.getBitcast(VT, Result);
13759     }
13760
13761     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13762       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13763       // pcmpeqd + pshufd + pand.
13764       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13765
13766       // First cast everything to the right type.
13767       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13768       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13769
13770       // Do the compare.
13771       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13772
13773       // Make sure the lower and upper halves are both all-ones.
13774       static const int Mask[] = { 1, 0, 3, 2 };
13775       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13776       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13777
13778       if (Invert)
13779         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13780
13781       return DAG.getBitcast(VT, Result);
13782     }
13783   }
13784
13785   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13786   // bits of the inputs before performing those operations.
13787   if (FlipSigns) {
13788     EVT EltVT = VT.getVectorElementType();
13789     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13790                                  VT);
13791     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13792     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13793   }
13794
13795   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13796
13797   // If the logical-not of the result is required, perform that now.
13798   if (Invert)
13799     Result = DAG.getNOT(dl, Result, VT);
13800
13801   if (MinMax)
13802     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13803
13804   if (Subus)
13805     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13806                          getZeroVector(VT, Subtarget, DAG, dl));
13807
13808   return Result;
13809 }
13810
13811 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13812
13813   MVT VT = Op.getSimpleValueType();
13814
13815   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13816
13817   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13818          && "SetCC type must be 8-bit or 1-bit integer");
13819   SDValue Op0 = Op.getOperand(0);
13820   SDValue Op1 = Op.getOperand(1);
13821   SDLoc dl(Op);
13822   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13823
13824   // Optimize to BT if possible.
13825   // Lower (X & (1 << N)) == 0 to BT(X, N).
13826   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13827   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13828   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13829       Op1.getOpcode() == ISD::Constant &&
13830       cast<ConstantSDNode>(Op1)->isNullValue() &&
13831       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13832     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13833     if (NewSetCC.getNode()) {
13834       if (VT == MVT::i1)
13835         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13836       return NewSetCC;
13837     }
13838   }
13839
13840   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13841   // these.
13842   if (Op1.getOpcode() == ISD::Constant &&
13843       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13844        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13845       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13846
13847     // If the input is a setcc, then reuse the input setcc or use a new one with
13848     // the inverted condition.
13849     if (Op0.getOpcode() == X86ISD::SETCC) {
13850       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13851       bool Invert = (CC == ISD::SETNE) ^
13852         cast<ConstantSDNode>(Op1)->isNullValue();
13853       if (!Invert)
13854         return Op0;
13855
13856       CCode = X86::GetOppositeBranchCondition(CCode);
13857       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13858                                   DAG.getConstant(CCode, dl, MVT::i8),
13859                                   Op0.getOperand(1));
13860       if (VT == MVT::i1)
13861         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13862       return SetCC;
13863     }
13864   }
13865   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13866       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13867       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13868
13869     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13870     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13871   }
13872
13873   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13874   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13875   if (X86CC == X86::COND_INVALID)
13876     return SDValue();
13877
13878   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13879   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13880   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13881                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13882   if (VT == MVT::i1)
13883     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13884   return SetCC;
13885 }
13886
13887 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13888 static bool isX86LogicalCmp(SDValue Op) {
13889   unsigned Opc = Op.getNode()->getOpcode();
13890   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13891       Opc == X86ISD::SAHF)
13892     return true;
13893   if (Op.getResNo() == 1 &&
13894       (Opc == X86ISD::ADD ||
13895        Opc == X86ISD::SUB ||
13896        Opc == X86ISD::ADC ||
13897        Opc == X86ISD::SBB ||
13898        Opc == X86ISD::SMUL ||
13899        Opc == X86ISD::UMUL ||
13900        Opc == X86ISD::INC ||
13901        Opc == X86ISD::DEC ||
13902        Opc == X86ISD::OR ||
13903        Opc == X86ISD::XOR ||
13904        Opc == X86ISD::AND))
13905     return true;
13906
13907   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13908     return true;
13909
13910   return false;
13911 }
13912
13913 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13914   if (V.getOpcode() != ISD::TRUNCATE)
13915     return false;
13916
13917   SDValue VOp0 = V.getOperand(0);
13918   unsigned InBits = VOp0.getValueSizeInBits();
13919   unsigned Bits = V.getValueSizeInBits();
13920   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13921 }
13922
13923 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13924   bool addTest = true;
13925   SDValue Cond  = Op.getOperand(0);
13926   SDValue Op1 = Op.getOperand(1);
13927   SDValue Op2 = Op.getOperand(2);
13928   SDLoc DL(Op);
13929   EVT VT = Op1.getValueType();
13930   SDValue CC;
13931
13932   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13933   // are available or VBLENDV if AVX is available.
13934   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13935   if (Cond.getOpcode() == ISD::SETCC &&
13936       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13937        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13938       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13939     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13940     int SSECC = translateX86FSETCC(
13941         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13942
13943     if (SSECC != 8) {
13944       if (Subtarget->hasAVX512()) {
13945         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13946                                   DAG.getConstant(SSECC, DL, MVT::i8));
13947         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13948       }
13949
13950       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13951                                 DAG.getConstant(SSECC, DL, MVT::i8));
13952
13953       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13954       // of 3 logic instructions for size savings and potentially speed.
13955       // Unfortunately, there is no scalar form of VBLENDV.
13956
13957       // If either operand is a constant, don't try this. We can expect to
13958       // optimize away at least one of the logic instructions later in that
13959       // case, so that sequence would be faster than a variable blend.
13960
13961       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13962       // uses XMM0 as the selection register. That may need just as many
13963       // instructions as the AND/ANDN/OR sequence due to register moves, so
13964       // don't bother.
13965
13966       if (Subtarget->hasAVX() &&
13967           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13968
13969         // Convert to vectors, do a VSELECT, and convert back to scalar.
13970         // All of the conversions should be optimized away.
13971
13972         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13973         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13974         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13975         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13976
13977         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13978         VCmp = DAG.getBitcast(VCmpVT, VCmp);
13979
13980         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13981
13982         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13983                            VSel, DAG.getIntPtrConstant(0, DL));
13984       }
13985       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13986       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13987       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13988     }
13989   }
13990
13991   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13992     SDValue Op1Scalar;
13993     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13994       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
13995     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13996       Op1Scalar = Op1.getOperand(0);
13997     SDValue Op2Scalar;
13998     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13999       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14000     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14001       Op2Scalar = Op2.getOperand(0);
14002     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14003       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14004                                       Op1Scalar.getValueType(),
14005                                       Cond, Op1Scalar, Op2Scalar);
14006       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14007         return DAG.getBitcast(VT, newSelect);
14008       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14009       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14010                          DAG.getIntPtrConstant(0, DL));
14011     }
14012   }
14013
14014   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14015     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14016     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14017                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14018     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14019                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14020     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14021                                     Cond, Op1, Op2);
14022     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14023   }
14024
14025   if (Cond.getOpcode() == ISD::SETCC) {
14026     SDValue NewCond = LowerSETCC(Cond, DAG);
14027     if (NewCond.getNode())
14028       Cond = NewCond;
14029   }
14030
14031   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14032   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14033   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14034   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14035   if (Cond.getOpcode() == X86ISD::SETCC &&
14036       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14037       isZero(Cond.getOperand(1).getOperand(1))) {
14038     SDValue Cmp = Cond.getOperand(1);
14039
14040     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14041
14042     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14043         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14044       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14045
14046       SDValue CmpOp0 = Cmp.getOperand(0);
14047       // Apply further optimizations for special cases
14048       // (select (x != 0), -1, 0) -> neg & sbb
14049       // (select (x == 0), 0, -1) -> neg & sbb
14050       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14051         if (YC->isNullValue() &&
14052             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14053           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14054           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14055                                     DAG.getConstant(0, DL,
14056                                                     CmpOp0.getValueType()),
14057                                     CmpOp0);
14058           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14059                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14060                                     SDValue(Neg.getNode(), 1));
14061           return Res;
14062         }
14063
14064       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14065                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14066       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14067
14068       SDValue Res =   // Res = 0 or -1.
14069         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14070                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14071
14072       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14073         Res = DAG.getNOT(DL, Res, Res.getValueType());
14074
14075       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14076       if (!N2C || !N2C->isNullValue())
14077         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14078       return Res;
14079     }
14080   }
14081
14082   // Look past (and (setcc_carry (cmp ...)), 1).
14083   if (Cond.getOpcode() == ISD::AND &&
14084       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14085     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14086     if (C && C->getAPIntValue() == 1)
14087       Cond = Cond.getOperand(0);
14088   }
14089
14090   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14091   // setting operand in place of the X86ISD::SETCC.
14092   unsigned CondOpcode = Cond.getOpcode();
14093   if (CondOpcode == X86ISD::SETCC ||
14094       CondOpcode == X86ISD::SETCC_CARRY) {
14095     CC = Cond.getOperand(0);
14096
14097     SDValue Cmp = Cond.getOperand(1);
14098     unsigned Opc = Cmp.getOpcode();
14099     MVT VT = Op.getSimpleValueType();
14100
14101     bool IllegalFPCMov = false;
14102     if (VT.isFloatingPoint() && !VT.isVector() &&
14103         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14104       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14105
14106     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14107         Opc == X86ISD::BT) { // FIXME
14108       Cond = Cmp;
14109       addTest = false;
14110     }
14111   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14112              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14113              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14114               Cond.getOperand(0).getValueType() != MVT::i8)) {
14115     SDValue LHS = Cond.getOperand(0);
14116     SDValue RHS = Cond.getOperand(1);
14117     unsigned X86Opcode;
14118     unsigned X86Cond;
14119     SDVTList VTs;
14120     switch (CondOpcode) {
14121     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14122     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14123     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14124     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14125     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14126     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14127     default: llvm_unreachable("unexpected overflowing operator");
14128     }
14129     if (CondOpcode == ISD::UMULO)
14130       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14131                           MVT::i32);
14132     else
14133       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14134
14135     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14136
14137     if (CondOpcode == ISD::UMULO)
14138       Cond = X86Op.getValue(2);
14139     else
14140       Cond = X86Op.getValue(1);
14141
14142     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14143     addTest = false;
14144   }
14145
14146   if (addTest) {
14147     // Look past the truncate if the high bits are known zero.
14148     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14149       Cond = Cond.getOperand(0);
14150
14151     // We know the result of AND is compared against zero. Try to match
14152     // it to BT.
14153     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14154       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14155       if (NewSetCC.getNode()) {
14156         CC = NewSetCC.getOperand(0);
14157         Cond = NewSetCC.getOperand(1);
14158         addTest = false;
14159       }
14160     }
14161   }
14162
14163   if (addTest) {
14164     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14165     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14166   }
14167
14168   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14169   // a <  b ?  0 : -1 -> RES = setcc_carry
14170   // a >= b ? -1 :  0 -> RES = setcc_carry
14171   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14172   if (Cond.getOpcode() == X86ISD::SUB) {
14173     Cond = ConvertCmpIfNecessary(Cond, DAG);
14174     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14175
14176     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14177         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14178       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14179                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14180                                 Cond);
14181       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14182         return DAG.getNOT(DL, Res, Res.getValueType());
14183       return Res;
14184     }
14185   }
14186
14187   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14188   // widen the cmov and push the truncate through. This avoids introducing a new
14189   // branch during isel and doesn't add any extensions.
14190   if (Op.getValueType() == MVT::i8 &&
14191       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14192     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14193     if (T1.getValueType() == T2.getValueType() &&
14194         // Blacklist CopyFromReg to avoid partial register stalls.
14195         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14196       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14197       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14198       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14199     }
14200   }
14201
14202   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14203   // condition is true.
14204   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14205   SDValue Ops[] = { Op2, Op1, CC, Cond };
14206   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14207 }
14208
14209 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14210                                        const X86Subtarget *Subtarget,
14211                                        SelectionDAG &DAG) {
14212   MVT VT = Op->getSimpleValueType(0);
14213   SDValue In = Op->getOperand(0);
14214   MVT InVT = In.getSimpleValueType();
14215   MVT VTElt = VT.getVectorElementType();
14216   MVT InVTElt = InVT.getVectorElementType();
14217   SDLoc dl(Op);
14218
14219   // SKX processor
14220   if ((InVTElt == MVT::i1) &&
14221       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14222         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14223
14224        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14225         VTElt.getSizeInBits() <= 16)) ||
14226
14227        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14228         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14229
14230        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14231         VTElt.getSizeInBits() >= 32))))
14232     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14233
14234   unsigned int NumElts = VT.getVectorNumElements();
14235
14236   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14237     return SDValue();
14238
14239   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14240     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14241       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14242     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14243   }
14244
14245   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14246   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14247   SDValue NegOne =
14248    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14249                    ExtVT);
14250   SDValue Zero =
14251    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14252
14253   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14254   if (VT.is512BitVector())
14255     return V;
14256   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14257 }
14258
14259 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14260                                              const X86Subtarget *Subtarget,
14261                                              SelectionDAG &DAG) {
14262   SDValue In = Op->getOperand(0);
14263   MVT VT = Op->getSimpleValueType(0);
14264   MVT InVT = In.getSimpleValueType();
14265   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14266
14267   MVT InSVT = InVT.getScalarType();
14268   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14269
14270   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14271     return SDValue();
14272   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14273     return SDValue();
14274
14275   SDLoc dl(Op);
14276
14277   // SSE41 targets can use the pmovsx* instructions directly.
14278   if (Subtarget->hasSSE41())
14279     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14280
14281   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14282   SDValue Curr = In;
14283   MVT CurrVT = InVT;
14284
14285   // As SRAI is only available on i16/i32 types, we expand only up to i32
14286   // and handle i64 separately.
14287   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14288     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14289     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14290     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14291     Curr = DAG.getBitcast(CurrVT, Curr);
14292   }
14293
14294   SDValue SignExt = Curr;
14295   if (CurrVT != InVT) {
14296     unsigned SignExtShift =
14297         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14298     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14299                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14300   }
14301
14302   if (CurrVT == VT)
14303     return SignExt;
14304
14305   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14306     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14307                                DAG.getConstant(31, dl, MVT::i8));
14308     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14309     return DAG.getBitcast(VT, Ext);
14310   }
14311
14312   return SDValue();
14313 }
14314
14315 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14316                                 SelectionDAG &DAG) {
14317   MVT VT = Op->getSimpleValueType(0);
14318   SDValue In = Op->getOperand(0);
14319   MVT InVT = In.getSimpleValueType();
14320   SDLoc dl(Op);
14321
14322   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14323     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14324
14325   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14326       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14327       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14328     return SDValue();
14329
14330   if (Subtarget->hasInt256())
14331     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14332
14333   // Optimize vectors in AVX mode
14334   // Sign extend  v8i16 to v8i32 and
14335   //              v4i32 to v4i64
14336   //
14337   // Divide input vector into two parts
14338   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14339   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14340   // concat the vectors to original VT
14341
14342   unsigned NumElems = InVT.getVectorNumElements();
14343   SDValue Undef = DAG.getUNDEF(InVT);
14344
14345   SmallVector<int,8> ShufMask1(NumElems, -1);
14346   for (unsigned i = 0; i != NumElems/2; ++i)
14347     ShufMask1[i] = i;
14348
14349   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14350
14351   SmallVector<int,8> ShufMask2(NumElems, -1);
14352   for (unsigned i = 0; i != NumElems/2; ++i)
14353     ShufMask2[i] = i + NumElems/2;
14354
14355   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14356
14357   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14358                                 VT.getVectorNumElements()/2);
14359
14360   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14361   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14362
14363   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14364 }
14365
14366 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14367 // may emit an illegal shuffle but the expansion is still better than scalar
14368 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14369 // we'll emit a shuffle and a arithmetic shift.
14370 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14371 // TODO: It is possible to support ZExt by zeroing the undef values during
14372 // the shuffle phase or after the shuffle.
14373 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14374                                  SelectionDAG &DAG) {
14375   MVT RegVT = Op.getSimpleValueType();
14376   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14377   assert(RegVT.isInteger() &&
14378          "We only custom lower integer vector sext loads.");
14379
14380   // Nothing useful we can do without SSE2 shuffles.
14381   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14382
14383   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14384   SDLoc dl(Ld);
14385   EVT MemVT = Ld->getMemoryVT();
14386   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14387   unsigned RegSz = RegVT.getSizeInBits();
14388
14389   ISD::LoadExtType Ext = Ld->getExtensionType();
14390
14391   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14392          && "Only anyext and sext are currently implemented.");
14393   assert(MemVT != RegVT && "Cannot extend to the same type");
14394   assert(MemVT.isVector() && "Must load a vector from memory");
14395
14396   unsigned NumElems = RegVT.getVectorNumElements();
14397   unsigned MemSz = MemVT.getSizeInBits();
14398   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14399
14400   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14401     // The only way in which we have a legal 256-bit vector result but not the
14402     // integer 256-bit operations needed to directly lower a sextload is if we
14403     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14404     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14405     // correctly legalized. We do this late to allow the canonical form of
14406     // sextload to persist throughout the rest of the DAG combiner -- it wants
14407     // to fold together any extensions it can, and so will fuse a sign_extend
14408     // of an sextload into a sextload targeting a wider value.
14409     SDValue Load;
14410     if (MemSz == 128) {
14411       // Just switch this to a normal load.
14412       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14413                                        "it must be a legal 128-bit vector "
14414                                        "type!");
14415       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14416                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14417                   Ld->isInvariant(), Ld->getAlignment());
14418     } else {
14419       assert(MemSz < 128 &&
14420              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14421       // Do an sext load to a 128-bit vector type. We want to use the same
14422       // number of elements, but elements half as wide. This will end up being
14423       // recursively lowered by this routine, but will succeed as we definitely
14424       // have all the necessary features if we're using AVX1.
14425       EVT HalfEltVT =
14426           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14427       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14428       Load =
14429           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14430                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14431                          Ld->isNonTemporal(), Ld->isInvariant(),
14432                          Ld->getAlignment());
14433     }
14434
14435     // Replace chain users with the new chain.
14436     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14437     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14438
14439     // Finally, do a normal sign-extend to the desired register.
14440     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14441   }
14442
14443   // All sizes must be a power of two.
14444   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14445          "Non-power-of-two elements are not custom lowered!");
14446
14447   // Attempt to load the original value using scalar loads.
14448   // Find the largest scalar type that divides the total loaded size.
14449   MVT SclrLoadTy = MVT::i8;
14450   for (MVT Tp : MVT::integer_valuetypes()) {
14451     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14452       SclrLoadTy = Tp;
14453     }
14454   }
14455
14456   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14457   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14458       (64 <= MemSz))
14459     SclrLoadTy = MVT::f64;
14460
14461   // Calculate the number of scalar loads that we need to perform
14462   // in order to load our vector from memory.
14463   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14464
14465   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14466          "Can only lower sext loads with a single scalar load!");
14467
14468   unsigned loadRegZize = RegSz;
14469   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14470     loadRegZize = 128;
14471
14472   // Represent our vector as a sequence of elements which are the
14473   // largest scalar that we can load.
14474   EVT LoadUnitVecVT = EVT::getVectorVT(
14475       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14476
14477   // Represent the data using the same element type that is stored in
14478   // memory. In practice, we ''widen'' MemVT.
14479   EVT WideVecVT =
14480       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14481                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14482
14483   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14484          "Invalid vector type");
14485
14486   // We can't shuffle using an illegal type.
14487   assert(TLI.isTypeLegal(WideVecVT) &&
14488          "We only lower types that form legal widened vector types");
14489
14490   SmallVector<SDValue, 8> Chains;
14491   SDValue Ptr = Ld->getBasePtr();
14492   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14493                                       TLI.getPointerTy(DAG.getDataLayout()));
14494   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14495
14496   for (unsigned i = 0; i < NumLoads; ++i) {
14497     // Perform a single load.
14498     SDValue ScalarLoad =
14499         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14500                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14501                     Ld->getAlignment());
14502     Chains.push_back(ScalarLoad.getValue(1));
14503     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14504     // another round of DAGCombining.
14505     if (i == 0)
14506       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14507     else
14508       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14509                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14510
14511     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14512   }
14513
14514   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14515
14516   // Bitcast the loaded value to a vector of the original element type, in
14517   // the size of the target vector type.
14518   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14519   unsigned SizeRatio = RegSz / MemSz;
14520
14521   if (Ext == ISD::SEXTLOAD) {
14522     // If we have SSE4.1, we can directly emit a VSEXT node.
14523     if (Subtarget->hasSSE41()) {
14524       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14525       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14526       return Sext;
14527     }
14528
14529     // Otherwise we'll shuffle the small elements in the high bits of the
14530     // larger type and perform an arithmetic shift. If the shift is not legal
14531     // it's better to scalarize.
14532     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14533            "We can't implement a sext load without an arithmetic right shift!");
14534
14535     // Redistribute the loaded elements into the different locations.
14536     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14537     for (unsigned i = 0; i != NumElems; ++i)
14538       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14539
14540     SDValue Shuff = DAG.getVectorShuffle(
14541         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14542
14543     Shuff = DAG.getBitcast(RegVT, Shuff);
14544
14545     // Build the arithmetic shift.
14546     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14547                    MemVT.getVectorElementType().getSizeInBits();
14548     Shuff =
14549         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14550                     DAG.getConstant(Amt, dl, RegVT));
14551
14552     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14553     return Shuff;
14554   }
14555
14556   // Redistribute the loaded elements into the different locations.
14557   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14558   for (unsigned i = 0; i != NumElems; ++i)
14559     ShuffleVec[i * SizeRatio] = i;
14560
14561   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14562                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14563
14564   // Bitcast to the requested type.
14565   Shuff = DAG.getBitcast(RegVT, Shuff);
14566   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14567   return Shuff;
14568 }
14569
14570 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14571 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14572 // from the AND / OR.
14573 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14574   Opc = Op.getOpcode();
14575   if (Opc != ISD::OR && Opc != ISD::AND)
14576     return false;
14577   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14578           Op.getOperand(0).hasOneUse() &&
14579           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14580           Op.getOperand(1).hasOneUse());
14581 }
14582
14583 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14584 // 1 and that the SETCC node has a single use.
14585 static bool isXor1OfSetCC(SDValue Op) {
14586   if (Op.getOpcode() != ISD::XOR)
14587     return false;
14588   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14589   if (N1C && N1C->getAPIntValue() == 1) {
14590     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14591       Op.getOperand(0).hasOneUse();
14592   }
14593   return false;
14594 }
14595
14596 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14597   bool addTest = true;
14598   SDValue Chain = Op.getOperand(0);
14599   SDValue Cond  = Op.getOperand(1);
14600   SDValue Dest  = Op.getOperand(2);
14601   SDLoc dl(Op);
14602   SDValue CC;
14603   bool Inverted = false;
14604
14605   if (Cond.getOpcode() == ISD::SETCC) {
14606     // Check for setcc([su]{add,sub,mul}o == 0).
14607     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14608         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14609         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14610         Cond.getOperand(0).getResNo() == 1 &&
14611         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14612          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14613          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14614          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14615          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14616          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14617       Inverted = true;
14618       Cond = Cond.getOperand(0);
14619     } else {
14620       SDValue NewCond = LowerSETCC(Cond, DAG);
14621       if (NewCond.getNode())
14622         Cond = NewCond;
14623     }
14624   }
14625 #if 0
14626   // FIXME: LowerXALUO doesn't handle these!!
14627   else if (Cond.getOpcode() == X86ISD::ADD  ||
14628            Cond.getOpcode() == X86ISD::SUB  ||
14629            Cond.getOpcode() == X86ISD::SMUL ||
14630            Cond.getOpcode() == X86ISD::UMUL)
14631     Cond = LowerXALUO(Cond, DAG);
14632 #endif
14633
14634   // Look pass (and (setcc_carry (cmp ...)), 1).
14635   if (Cond.getOpcode() == ISD::AND &&
14636       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14637     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14638     if (C && C->getAPIntValue() == 1)
14639       Cond = Cond.getOperand(0);
14640   }
14641
14642   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14643   // setting operand in place of the X86ISD::SETCC.
14644   unsigned CondOpcode = Cond.getOpcode();
14645   if (CondOpcode == X86ISD::SETCC ||
14646       CondOpcode == X86ISD::SETCC_CARRY) {
14647     CC = Cond.getOperand(0);
14648
14649     SDValue Cmp = Cond.getOperand(1);
14650     unsigned Opc = Cmp.getOpcode();
14651     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14652     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14653       Cond = Cmp;
14654       addTest = false;
14655     } else {
14656       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14657       default: break;
14658       case X86::COND_O:
14659       case X86::COND_B:
14660         // These can only come from an arithmetic instruction with overflow,
14661         // e.g. SADDO, UADDO.
14662         Cond = Cond.getNode()->getOperand(1);
14663         addTest = false;
14664         break;
14665       }
14666     }
14667   }
14668   CondOpcode = Cond.getOpcode();
14669   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14670       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14671       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14672        Cond.getOperand(0).getValueType() != MVT::i8)) {
14673     SDValue LHS = Cond.getOperand(0);
14674     SDValue RHS = Cond.getOperand(1);
14675     unsigned X86Opcode;
14676     unsigned X86Cond;
14677     SDVTList VTs;
14678     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14679     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14680     // X86ISD::INC).
14681     switch (CondOpcode) {
14682     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14683     case ISD::SADDO:
14684       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14685         if (C->isOne()) {
14686           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14687           break;
14688         }
14689       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14690     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14691     case ISD::SSUBO:
14692       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14693         if (C->isOne()) {
14694           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14695           break;
14696         }
14697       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14698     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14699     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14700     default: llvm_unreachable("unexpected overflowing operator");
14701     }
14702     if (Inverted)
14703       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14704     if (CondOpcode == ISD::UMULO)
14705       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14706                           MVT::i32);
14707     else
14708       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14709
14710     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14711
14712     if (CondOpcode == ISD::UMULO)
14713       Cond = X86Op.getValue(2);
14714     else
14715       Cond = X86Op.getValue(1);
14716
14717     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14718     addTest = false;
14719   } else {
14720     unsigned CondOpc;
14721     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14722       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14723       if (CondOpc == ISD::OR) {
14724         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14725         // two branches instead of an explicit OR instruction with a
14726         // separate test.
14727         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14728             isX86LogicalCmp(Cmp)) {
14729           CC = Cond.getOperand(0).getOperand(0);
14730           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14731                               Chain, Dest, CC, Cmp);
14732           CC = Cond.getOperand(1).getOperand(0);
14733           Cond = Cmp;
14734           addTest = false;
14735         }
14736       } else { // ISD::AND
14737         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14738         // two branches instead of an explicit AND instruction with a
14739         // separate test. However, we only do this if this block doesn't
14740         // have a fall-through edge, because this requires an explicit
14741         // jmp when the condition is false.
14742         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14743             isX86LogicalCmp(Cmp) &&
14744             Op.getNode()->hasOneUse()) {
14745           X86::CondCode CCode =
14746             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14747           CCode = X86::GetOppositeBranchCondition(CCode);
14748           CC = DAG.getConstant(CCode, dl, MVT::i8);
14749           SDNode *User = *Op.getNode()->use_begin();
14750           // Look for an unconditional branch following this conditional branch.
14751           // We need this because we need to reverse the successors in order
14752           // to implement FCMP_OEQ.
14753           if (User->getOpcode() == ISD::BR) {
14754             SDValue FalseBB = User->getOperand(1);
14755             SDNode *NewBR =
14756               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14757             assert(NewBR == User);
14758             (void)NewBR;
14759             Dest = FalseBB;
14760
14761             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14762                                 Chain, Dest, CC, Cmp);
14763             X86::CondCode CCode =
14764               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14765             CCode = X86::GetOppositeBranchCondition(CCode);
14766             CC = DAG.getConstant(CCode, dl, MVT::i8);
14767             Cond = Cmp;
14768             addTest = false;
14769           }
14770         }
14771       }
14772     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14773       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14774       // It should be transformed during dag combiner except when the condition
14775       // is set by a arithmetics with overflow node.
14776       X86::CondCode CCode =
14777         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14778       CCode = X86::GetOppositeBranchCondition(CCode);
14779       CC = DAG.getConstant(CCode, dl, MVT::i8);
14780       Cond = Cond.getOperand(0).getOperand(1);
14781       addTest = false;
14782     } else if (Cond.getOpcode() == ISD::SETCC &&
14783                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14784       // For FCMP_OEQ, we can emit
14785       // two branches instead of an explicit AND instruction with a
14786       // separate test. However, we only do this if this block doesn't
14787       // have a fall-through edge, because this requires an explicit
14788       // jmp when the condition is false.
14789       if (Op.getNode()->hasOneUse()) {
14790         SDNode *User = *Op.getNode()->use_begin();
14791         // Look for an unconditional branch following this conditional branch.
14792         // We need this because we need to reverse the successors in order
14793         // to implement FCMP_OEQ.
14794         if (User->getOpcode() == ISD::BR) {
14795           SDValue FalseBB = User->getOperand(1);
14796           SDNode *NewBR =
14797             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14798           assert(NewBR == User);
14799           (void)NewBR;
14800           Dest = FalseBB;
14801
14802           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14803                                     Cond.getOperand(0), Cond.getOperand(1));
14804           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14805           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14806           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14807                               Chain, Dest, CC, Cmp);
14808           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14809           Cond = Cmp;
14810           addTest = false;
14811         }
14812       }
14813     } else if (Cond.getOpcode() == ISD::SETCC &&
14814                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14815       // For FCMP_UNE, we can emit
14816       // two branches instead of an explicit AND instruction with a
14817       // separate test. However, we only do this if this block doesn't
14818       // have a fall-through edge, because this requires an explicit
14819       // jmp when the condition is false.
14820       if (Op.getNode()->hasOneUse()) {
14821         SDNode *User = *Op.getNode()->use_begin();
14822         // Look for an unconditional branch following this conditional branch.
14823         // We need this because we need to reverse the successors in order
14824         // to implement FCMP_UNE.
14825         if (User->getOpcode() == ISD::BR) {
14826           SDValue FalseBB = User->getOperand(1);
14827           SDNode *NewBR =
14828             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14829           assert(NewBR == User);
14830           (void)NewBR;
14831
14832           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14833                                     Cond.getOperand(0), Cond.getOperand(1));
14834           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14835           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14836           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14837                               Chain, Dest, CC, Cmp);
14838           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14839           Cond = Cmp;
14840           addTest = false;
14841           Dest = FalseBB;
14842         }
14843       }
14844     }
14845   }
14846
14847   if (addTest) {
14848     // Look pass the truncate if the high bits are known zero.
14849     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14850         Cond = Cond.getOperand(0);
14851
14852     // We know the result of AND is compared against zero. Try to match
14853     // it to BT.
14854     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14855       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14856       if (NewSetCC.getNode()) {
14857         CC = NewSetCC.getOperand(0);
14858         Cond = NewSetCC.getOperand(1);
14859         addTest = false;
14860       }
14861     }
14862   }
14863
14864   if (addTest) {
14865     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14866     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14867     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14868   }
14869   Cond = ConvertCmpIfNecessary(Cond, DAG);
14870   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14871                      Chain, Dest, CC, Cond);
14872 }
14873
14874 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14875 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14876 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14877 // that the guard pages used by the OS virtual memory manager are allocated in
14878 // correct sequence.
14879 SDValue
14880 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14881                                            SelectionDAG &DAG) const {
14882   MachineFunction &MF = DAG.getMachineFunction();
14883   bool SplitStack = MF.shouldSplitStack();
14884   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14885                SplitStack;
14886   SDLoc dl(Op);
14887
14888   if (!Lower) {
14889     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14890     SDNode* Node = Op.getNode();
14891
14892     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14893     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14894         " not tell us which reg is the stack pointer!");
14895     EVT VT = Node->getValueType(0);
14896     SDValue Tmp1 = SDValue(Node, 0);
14897     SDValue Tmp2 = SDValue(Node, 1);
14898     SDValue Tmp3 = Node->getOperand(2);
14899     SDValue Chain = Tmp1.getOperand(0);
14900
14901     // Chain the dynamic stack allocation so that it doesn't modify the stack
14902     // pointer when other instructions are using the stack.
14903     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14904         SDLoc(Node));
14905
14906     SDValue Size = Tmp2.getOperand(1);
14907     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14908     Chain = SP.getValue(1);
14909     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14910     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14911     unsigned StackAlign = TFI.getStackAlignment();
14912     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14913     if (Align > StackAlign)
14914       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14915           DAG.getConstant(-(uint64_t)Align, dl, VT));
14916     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14917
14918     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14919         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14920         SDLoc(Node));
14921
14922     SDValue Ops[2] = { Tmp1, Tmp2 };
14923     return DAG.getMergeValues(Ops, dl);
14924   }
14925
14926   // Get the inputs.
14927   SDValue Chain = Op.getOperand(0);
14928   SDValue Size  = Op.getOperand(1);
14929   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14930   EVT VT = Op.getNode()->getValueType(0);
14931
14932   bool Is64Bit = Subtarget->is64Bit();
14933   MVT SPTy = getPointerTy(DAG.getDataLayout());
14934
14935   if (SplitStack) {
14936     MachineRegisterInfo &MRI = MF.getRegInfo();
14937
14938     if (Is64Bit) {
14939       // The 64 bit implementation of segmented stacks needs to clobber both r10
14940       // r11. This makes it impossible to use it along with nested parameters.
14941       const Function *F = MF.getFunction();
14942
14943       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14944            I != E; ++I)
14945         if (I->hasNestAttr())
14946           report_fatal_error("Cannot use segmented stacks with functions that "
14947                              "have nested arguments.");
14948     }
14949
14950     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14951     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14952     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14953     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14954                                 DAG.getRegister(Vreg, SPTy));
14955     SDValue Ops1[2] = { Value, Chain };
14956     return DAG.getMergeValues(Ops1, dl);
14957   } else {
14958     SDValue Flag;
14959     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14960
14961     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14962     Flag = Chain.getValue(1);
14963     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14964
14965     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14966
14967     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14968     unsigned SPReg = RegInfo->getStackRegister();
14969     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14970     Chain = SP.getValue(1);
14971
14972     if (Align) {
14973       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14974                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14975       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14976     }
14977
14978     SDValue Ops1[2] = { SP, Chain };
14979     return DAG.getMergeValues(Ops1, dl);
14980   }
14981 }
14982
14983 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14984   MachineFunction &MF = DAG.getMachineFunction();
14985   auto PtrVT = getPointerTy(MF.getDataLayout());
14986   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14987
14988   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14989   SDLoc DL(Op);
14990
14991   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14992     // vastart just stores the address of the VarArgsFrameIndex slot into the
14993     // memory location argument.
14994     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14995     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14996                         MachinePointerInfo(SV), false, false, 0);
14997   }
14998
14999   // __va_list_tag:
15000   //   gp_offset         (0 - 6 * 8)
15001   //   fp_offset         (48 - 48 + 8 * 16)
15002   //   overflow_arg_area (point to parameters coming in memory).
15003   //   reg_save_area
15004   SmallVector<SDValue, 8> MemOps;
15005   SDValue FIN = Op.getOperand(1);
15006   // Store gp_offset
15007   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15008                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15009                                                DL, MVT::i32),
15010                                FIN, MachinePointerInfo(SV), false, false, 0);
15011   MemOps.push_back(Store);
15012
15013   // Store fp_offset
15014   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15015   Store = DAG.getStore(Op.getOperand(0), DL,
15016                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15017                                        MVT::i32),
15018                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15019   MemOps.push_back(Store);
15020
15021   // Store ptr to overflow_arg_area
15022   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15023   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15024   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15025                        MachinePointerInfo(SV, 8),
15026                        false, false, 0);
15027   MemOps.push_back(Store);
15028
15029   // Store ptr to reg_save_area.
15030   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15031   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15032   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15033                        MachinePointerInfo(SV, 16), false, false, 0);
15034   MemOps.push_back(Store);
15035   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15036 }
15037
15038 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15039   assert(Subtarget->is64Bit() &&
15040          "LowerVAARG only handles 64-bit va_arg!");
15041   assert((Subtarget->isTargetLinux() ||
15042           Subtarget->isTargetDarwin()) &&
15043           "Unhandled target in LowerVAARG");
15044   assert(Op.getNode()->getNumOperands() == 4);
15045   SDValue Chain = Op.getOperand(0);
15046   SDValue SrcPtr = Op.getOperand(1);
15047   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15048   unsigned Align = Op.getConstantOperandVal(3);
15049   SDLoc dl(Op);
15050
15051   EVT ArgVT = Op.getNode()->getValueType(0);
15052   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15053   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15054   uint8_t ArgMode;
15055
15056   // Decide which area this value should be read from.
15057   // TODO: Implement the AMD64 ABI in its entirety. This simple
15058   // selection mechanism works only for the basic types.
15059   if (ArgVT == MVT::f80) {
15060     llvm_unreachable("va_arg for f80 not yet implemented");
15061   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15062     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15063   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15064     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15065   } else {
15066     llvm_unreachable("Unhandled argument type in LowerVAARG");
15067   }
15068
15069   if (ArgMode == 2) {
15070     // Sanity Check: Make sure using fp_offset makes sense.
15071     assert(!Subtarget->useSoftFloat() &&
15072            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15073                Attribute::NoImplicitFloat)) &&
15074            Subtarget->hasSSE1());
15075   }
15076
15077   // Insert VAARG_64 node into the DAG
15078   // VAARG_64 returns two values: Variable Argument Address, Chain
15079   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15080                        DAG.getConstant(ArgMode, dl, MVT::i8),
15081                        DAG.getConstant(Align, dl, MVT::i32)};
15082   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15083   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15084                                           VTs, InstOps, MVT::i64,
15085                                           MachinePointerInfo(SV),
15086                                           /*Align=*/0,
15087                                           /*Volatile=*/false,
15088                                           /*ReadMem=*/true,
15089                                           /*WriteMem=*/true);
15090   Chain = VAARG.getValue(1);
15091
15092   // Load the next argument and return it
15093   return DAG.getLoad(ArgVT, dl,
15094                      Chain,
15095                      VAARG,
15096                      MachinePointerInfo(),
15097                      false, false, false, 0);
15098 }
15099
15100 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15101                            SelectionDAG &DAG) {
15102   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15103   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15104   SDValue Chain = Op.getOperand(0);
15105   SDValue DstPtr = Op.getOperand(1);
15106   SDValue SrcPtr = Op.getOperand(2);
15107   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15108   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15109   SDLoc DL(Op);
15110
15111   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15112                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15113                        false, false,
15114                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15115 }
15116
15117 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15118 // amount is a constant. Takes immediate version of shift as input.
15119 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15120                                           SDValue SrcOp, uint64_t ShiftAmt,
15121                                           SelectionDAG &DAG) {
15122   MVT ElementType = VT.getVectorElementType();
15123
15124   // Fold this packed shift into its first operand if ShiftAmt is 0.
15125   if (ShiftAmt == 0)
15126     return SrcOp;
15127
15128   // Check for ShiftAmt >= element width
15129   if (ShiftAmt >= ElementType.getSizeInBits()) {
15130     if (Opc == X86ISD::VSRAI)
15131       ShiftAmt = ElementType.getSizeInBits() - 1;
15132     else
15133       return DAG.getConstant(0, dl, VT);
15134   }
15135
15136   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15137          && "Unknown target vector shift-by-constant node");
15138
15139   // Fold this packed vector shift into a build vector if SrcOp is a
15140   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15141   if (VT == SrcOp.getSimpleValueType() &&
15142       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15143     SmallVector<SDValue, 8> Elts;
15144     unsigned NumElts = SrcOp->getNumOperands();
15145     ConstantSDNode *ND;
15146
15147     switch(Opc) {
15148     default: llvm_unreachable(nullptr);
15149     case X86ISD::VSHLI:
15150       for (unsigned i=0; i!=NumElts; ++i) {
15151         SDValue CurrentOp = SrcOp->getOperand(i);
15152         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15153           Elts.push_back(CurrentOp);
15154           continue;
15155         }
15156         ND = cast<ConstantSDNode>(CurrentOp);
15157         const APInt &C = ND->getAPIntValue();
15158         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15159       }
15160       break;
15161     case X86ISD::VSRLI:
15162       for (unsigned i=0; i!=NumElts; ++i) {
15163         SDValue CurrentOp = SrcOp->getOperand(i);
15164         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15165           Elts.push_back(CurrentOp);
15166           continue;
15167         }
15168         ND = cast<ConstantSDNode>(CurrentOp);
15169         const APInt &C = ND->getAPIntValue();
15170         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15171       }
15172       break;
15173     case X86ISD::VSRAI:
15174       for (unsigned i=0; i!=NumElts; ++i) {
15175         SDValue CurrentOp = SrcOp->getOperand(i);
15176         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15177           Elts.push_back(CurrentOp);
15178           continue;
15179         }
15180         ND = cast<ConstantSDNode>(CurrentOp);
15181         const APInt &C = ND->getAPIntValue();
15182         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15183       }
15184       break;
15185     }
15186
15187     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15188   }
15189
15190   return DAG.getNode(Opc, dl, VT, SrcOp,
15191                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15192 }
15193
15194 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15195 // may or may not be a constant. Takes immediate version of shift as input.
15196 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15197                                    SDValue SrcOp, SDValue ShAmt,
15198                                    SelectionDAG &DAG) {
15199   MVT SVT = ShAmt.getSimpleValueType();
15200   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15201
15202   // Catch shift-by-constant.
15203   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15204     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15205                                       CShAmt->getZExtValue(), DAG);
15206
15207   // Change opcode to non-immediate version
15208   switch (Opc) {
15209     default: llvm_unreachable("Unknown target vector shift node");
15210     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15211     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15212     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15213   }
15214
15215   const X86Subtarget &Subtarget =
15216       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15217   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15218       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15219     // Let the shuffle legalizer expand this shift amount node.
15220     SDValue Op0 = ShAmt.getOperand(0);
15221     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15222     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15223   } else {
15224     // Need to build a vector containing shift amount.
15225     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15226     SmallVector<SDValue, 4> ShOps;
15227     ShOps.push_back(ShAmt);
15228     if (SVT == MVT::i32) {
15229       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15230       ShOps.push_back(DAG.getUNDEF(SVT));
15231     }
15232     ShOps.push_back(DAG.getUNDEF(SVT));
15233
15234     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15235     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15236   }
15237
15238   // The return type has to be a 128-bit type with the same element
15239   // type as the input type.
15240   MVT EltVT = VT.getVectorElementType();
15241   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15242
15243   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15244   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15245 }
15246
15247 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15248 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15249 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15250 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15251                                     SDValue PreservedSrc,
15252                                     const X86Subtarget *Subtarget,
15253                                     SelectionDAG &DAG) {
15254     EVT VT = Op.getValueType();
15255     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15256                                   MVT::i1, VT.getVectorNumElements());
15257     SDValue VMask = SDValue();
15258     unsigned OpcodeSelect = ISD::VSELECT;
15259     SDLoc dl(Op);
15260
15261     assert(MaskVT.isSimple() && "invalid mask type");
15262
15263     if (isAllOnes(Mask))
15264       return Op;
15265
15266     if (MaskVT.bitsGT(Mask.getValueType())) {
15267       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15268                                          MaskVT.getSizeInBits());
15269       VMask = DAG.getBitcast(MaskVT,
15270                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15271     } else {
15272       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15273                                        Mask.getValueType().getSizeInBits());
15274       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15275       // are extracted by EXTRACT_SUBVECTOR.
15276       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15277                           DAG.getBitcast(BitcastVT, Mask),
15278                           DAG.getIntPtrConstant(0, dl));
15279     }
15280
15281     switch (Op.getOpcode()) {
15282       default: break;
15283       case X86ISD::PCMPEQM:
15284       case X86ISD::PCMPGTM:
15285       case X86ISD::CMPM:
15286       case X86ISD::CMPMU:
15287         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15288       case X86ISD::VTRUNC:
15289       case X86ISD::VTRUNCS:
15290       case X86ISD::VTRUNCUS:
15291         // We can't use ISD::VSELECT here because it is not always "Legal"
15292         // for the destination type. For example vpmovqb require only AVX512
15293         // and vselect that can operate on byte element type require BWI
15294         OpcodeSelect = X86ISD::SELECT;
15295         break;
15296     }
15297     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15298       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15299     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15300 }
15301
15302 /// \brief Creates an SDNode for a predicated scalar operation.
15303 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15304 /// The mask is comming as MVT::i8 and it should be truncated
15305 /// to MVT::i1 while lowering masking intrinsics.
15306 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15307 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15308 /// a scalar instruction.
15309 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15310                                     SDValue PreservedSrc,
15311                                     const X86Subtarget *Subtarget,
15312                                     SelectionDAG &DAG) {
15313     if (isAllOnes(Mask))
15314       return Op;
15315
15316     EVT VT = Op.getValueType();
15317     SDLoc dl(Op);
15318     // The mask should be of type MVT::i1
15319     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15320
15321     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15322       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15323     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15324 }
15325
15326 static int getSEHRegistrationNodeSize(const Function *Fn) {
15327   if (!Fn->hasPersonalityFn())
15328     report_fatal_error(
15329         "querying registration node size for function without personality");
15330   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15331   // WinEHStatePass for the full struct definition.
15332   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15333   case EHPersonality::MSVC_X86SEH: return 24;
15334   case EHPersonality::MSVC_CXX: return 16;
15335   default: break;
15336   }
15337   report_fatal_error("can only recover FP for MSVC EH personality functions");
15338 }
15339
15340 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15341 /// function or when returning to a parent frame after catching an exception, we
15342 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15343 /// Here's the math:
15344 ///   RegNodeBase = EntryEBP - RegNodeSize
15345 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15346 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15347 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15348 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15349                                    SDValue EntryEBP) {
15350   MachineFunction &MF = DAG.getMachineFunction();
15351   SDLoc dl;
15352
15353   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15354   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15355
15356   // It's possible that the parent function no longer has a personality function
15357   // if the exceptional code was optimized away, in which case we just return
15358   // the incoming EBP.
15359   if (!Fn->hasPersonalityFn())
15360     return EntryEBP;
15361
15362   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15363
15364   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15365   // registration.
15366   MCSymbol *OffsetSym =
15367       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15368           GlobalValue::getRealLinkageName(Fn->getName()));
15369   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15370   SDValue RegNodeFrameOffset =
15371       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15372
15373   // RegNodeBase = EntryEBP - RegNodeSize
15374   // ParentFP = RegNodeBase - RegNodeFrameOffset
15375   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15376                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15377   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15378 }
15379
15380 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15381                                        SelectionDAG &DAG) {
15382   SDLoc dl(Op);
15383   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15384   EVT VT = Op.getValueType();
15385   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15386   if (IntrData) {
15387     switch(IntrData->Type) {
15388     case INTR_TYPE_1OP:
15389       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15390     case INTR_TYPE_2OP:
15391       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15392         Op.getOperand(2));
15393     case INTR_TYPE_3OP:
15394       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15395         Op.getOperand(2), Op.getOperand(3));
15396     case INTR_TYPE_4OP:
15397       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15398         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15399     case INTR_TYPE_1OP_MASK_RM: {
15400       SDValue Src = Op.getOperand(1);
15401       SDValue PassThru = Op.getOperand(2);
15402       SDValue Mask = Op.getOperand(3);
15403       SDValue RoundingMode;
15404       // We allways add rounding mode to the Node.
15405       // If the rounding mode is not specified, we add the 
15406       // "current direction" mode.
15407       if (Op.getNumOperands() == 4)
15408         RoundingMode =
15409           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15410       else
15411         RoundingMode = Op.getOperand(4);
15412       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15413       if (IntrWithRoundingModeOpcode != 0)
15414         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15415             X86::STATIC_ROUNDING::CUR_DIRECTION)
15416           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15417                                       dl, Op.getValueType(), Src, RoundingMode),
15418                                       Mask, PassThru, Subtarget, DAG);
15419       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15420                                               RoundingMode),
15421                                   Mask, PassThru, Subtarget, DAG);
15422     }
15423     case INTR_TYPE_1OP_MASK: {
15424       SDValue Src = Op.getOperand(1);
15425       SDValue PassThru = Op.getOperand(2);
15426       SDValue Mask = Op.getOperand(3);
15427       // We add rounding mode to the Node when
15428       //   - RM Opcode is specified and
15429       //   - RM is not "current direction".
15430       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15431       if (IntrWithRoundingModeOpcode != 0) {
15432         SDValue Rnd = Op.getOperand(4);
15433         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15434         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15435           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15436                                       dl, Op.getValueType(),
15437                                       Src, Rnd),
15438                                       Mask, PassThru, Subtarget, DAG);
15439         }
15440       }
15441       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15442                                   Mask, PassThru, Subtarget, DAG);
15443     }
15444     case INTR_TYPE_SCALAR_MASK_RM: {
15445       SDValue Src1 = Op.getOperand(1);
15446       SDValue Src2 = Op.getOperand(2);
15447       SDValue Src0 = Op.getOperand(3);
15448       SDValue Mask = Op.getOperand(4);
15449       // There are 2 kinds of intrinsics in this group:
15450       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15451       // (2) With rounding mode and sae - 7 operands.
15452       if (Op.getNumOperands() == 6) {
15453         SDValue Sae  = Op.getOperand(5);
15454         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15455         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15456                                                 Sae),
15457                                     Mask, Src0, Subtarget, DAG);
15458       }
15459       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15460       SDValue RoundingMode  = Op.getOperand(5);
15461       SDValue Sae  = Op.getOperand(6);
15462       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15463                                               RoundingMode, Sae),
15464                                   Mask, Src0, Subtarget, DAG);
15465     }
15466     case INTR_TYPE_2OP_MASK: {
15467       SDValue Src1 = Op.getOperand(1);
15468       SDValue Src2 = Op.getOperand(2);
15469       SDValue PassThru = Op.getOperand(3);
15470       SDValue Mask = Op.getOperand(4);
15471       // We specify 2 possible opcodes for intrinsics with rounding modes.
15472       // First, we check if the intrinsic may have non-default rounding mode,
15473       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15474       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15475       if (IntrWithRoundingModeOpcode != 0) {
15476         SDValue Rnd = Op.getOperand(5);
15477         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15478         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15479           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15480                                       dl, Op.getValueType(),
15481                                       Src1, Src2, Rnd),
15482                                       Mask, PassThru, Subtarget, DAG);
15483         }
15484       }
15485       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15486                                               Src1,Src2),
15487                                   Mask, PassThru, Subtarget, DAG);
15488     }
15489     case INTR_TYPE_2OP_MASK_RM: {
15490       SDValue Src1 = Op.getOperand(1);
15491       SDValue Src2 = Op.getOperand(2);
15492       SDValue PassThru = Op.getOperand(3);
15493       SDValue Mask = Op.getOperand(4);
15494       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15495       // First, we check if the intrinsic have rounding mode (6 operands),
15496       // if not, we set rounding mode to "current".
15497       SDValue Rnd;
15498       if (Op.getNumOperands() == 6)
15499         Rnd = Op.getOperand(5);
15500       else
15501         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15502       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15503                                               Src1, Src2, Rnd),
15504                                   Mask, PassThru, Subtarget, DAG);
15505     }
15506     case INTR_TYPE_3OP_MASK_RM: {
15507       SDValue Src1 = Op.getOperand(1);
15508       SDValue Src2 = Op.getOperand(2);
15509       SDValue Imm = Op.getOperand(3);
15510       SDValue PassThru = Op.getOperand(4);
15511       SDValue Mask = Op.getOperand(5);
15512       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15513       // First, we check if the intrinsic have rounding mode (7 operands),
15514       // if not, we set rounding mode to "current".
15515       SDValue Rnd;
15516       if (Op.getNumOperands() == 7)
15517         Rnd = Op.getOperand(6);
15518       else
15519         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15520       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15521         Src1, Src2, Imm, Rnd),
15522         Mask, PassThru, Subtarget, DAG);
15523     }
15524     case INTR_TYPE_3OP_MASK: {
15525       SDValue Src1 = Op.getOperand(1);
15526       SDValue Src2 = Op.getOperand(2);
15527       SDValue Src3 = Op.getOperand(3);
15528       SDValue PassThru = Op.getOperand(4);
15529       SDValue Mask = Op.getOperand(5);
15530       // We specify 2 possible opcodes for intrinsics with rounding modes.
15531       // First, we check if the intrinsic may have non-default rounding mode,
15532       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15533       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15534       if (IntrWithRoundingModeOpcode != 0) {
15535         SDValue Rnd = Op.getOperand(6);
15536         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15537         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15538           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15539                                       dl, Op.getValueType(),
15540                                       Src1, Src2, Src3, Rnd),
15541                                       Mask, PassThru, Subtarget, DAG);
15542         }
15543       }
15544       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15545                                               Src1, Src2, Src3),
15546                                   Mask, PassThru, Subtarget, DAG);
15547     }
15548     case VPERM_3OP_MASKZ:
15549     case VPERM_3OP_MASK:
15550     case FMA_OP_MASK3:
15551     case FMA_OP_MASKZ:
15552     case FMA_OP_MASK: {
15553       SDValue Src1 = Op.getOperand(1);
15554       SDValue Src2 = Op.getOperand(2);
15555       SDValue Src3 = Op.getOperand(3);
15556       SDValue Mask = Op.getOperand(4);
15557       EVT VT = Op.getValueType();
15558       SDValue PassThru = SDValue();
15559
15560       // set PassThru element
15561       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15562         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15563       else if (IntrData->Type == FMA_OP_MASK3)
15564         PassThru = Src3;
15565       else
15566         PassThru = Src1;
15567
15568       // We specify 2 possible opcodes for intrinsics with rounding modes.
15569       // First, we check if the intrinsic may have non-default rounding mode,
15570       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15571       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15572       if (IntrWithRoundingModeOpcode != 0) {
15573         SDValue Rnd = Op.getOperand(5);
15574         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15575             X86::STATIC_ROUNDING::CUR_DIRECTION)
15576           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15577                                                   dl, Op.getValueType(),
15578                                                   Src1, Src2, Src3, Rnd),
15579                                       Mask, PassThru, Subtarget, DAG);
15580       }
15581       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15582                                               dl, Op.getValueType(),
15583                                               Src1, Src2, Src3),
15584                                   Mask, PassThru, Subtarget, DAG);
15585     }
15586     case CMP_MASK:
15587     case CMP_MASK_CC: {
15588       // Comparison intrinsics with masks.
15589       // Example of transformation:
15590       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15591       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15592       // (i8 (bitcast
15593       //   (v8i1 (insert_subvector undef,
15594       //           (v2i1 (and (PCMPEQM %a, %b),
15595       //                      (extract_subvector
15596       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15597       EVT VT = Op.getOperand(1).getValueType();
15598       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15599                                     VT.getVectorNumElements());
15600       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15601       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15602                                        Mask.getValueType().getSizeInBits());
15603       SDValue Cmp;
15604       if (IntrData->Type == CMP_MASK_CC) {
15605         SDValue CC = Op.getOperand(3);
15606         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15607         // We specify 2 possible opcodes for intrinsics with rounding modes.
15608         // First, we check if the intrinsic may have non-default rounding mode,
15609         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15610         if (IntrData->Opc1 != 0) {
15611           SDValue Rnd = Op.getOperand(5);
15612           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15613               X86::STATIC_ROUNDING::CUR_DIRECTION)
15614             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15615                               Op.getOperand(2), CC, Rnd);
15616         }
15617         //default rounding mode
15618         if(!Cmp.getNode())
15619             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15620                               Op.getOperand(2), CC);
15621
15622       } else {
15623         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15624         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15625                           Op.getOperand(2));
15626       }
15627       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15628                                              DAG.getTargetConstant(0, dl,
15629                                                                    MaskVT),
15630                                              Subtarget, DAG);
15631       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15632                                 DAG.getUNDEF(BitcastVT), CmpMask,
15633                                 DAG.getIntPtrConstant(0, dl));
15634       return DAG.getBitcast(Op.getValueType(), Res);
15635     }
15636     case COMI: { // Comparison intrinsics
15637       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15638       SDValue LHS = Op.getOperand(1);
15639       SDValue RHS = Op.getOperand(2);
15640       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15641       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15642       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15643       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15644                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15645       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15646     }
15647     case VSHIFT:
15648       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15649                                  Op.getOperand(1), Op.getOperand(2), DAG);
15650     case VSHIFT_MASK:
15651       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15652                                                       Op.getSimpleValueType(),
15653                                                       Op.getOperand(1),
15654                                                       Op.getOperand(2), DAG),
15655                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15656                                   DAG);
15657     case COMPRESS_EXPAND_IN_REG: {
15658       SDValue Mask = Op.getOperand(3);
15659       SDValue DataToCompress = Op.getOperand(1);
15660       SDValue PassThru = Op.getOperand(2);
15661       if (isAllOnes(Mask)) // return data as is
15662         return Op.getOperand(1);
15663
15664       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15665                                               DataToCompress),
15666                                   Mask, PassThru, Subtarget, DAG);
15667     }
15668     case BLEND: {
15669       SDValue Mask = Op.getOperand(3);
15670       EVT VT = Op.getValueType();
15671       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15672                                     VT.getVectorNumElements());
15673       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15674                                        Mask.getValueType().getSizeInBits());
15675       SDLoc dl(Op);
15676       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15677                                   DAG.getBitcast(BitcastVT, Mask),
15678                                   DAG.getIntPtrConstant(0, dl));
15679       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15680                          Op.getOperand(2));
15681     }
15682     default:
15683       break;
15684     }
15685   }
15686
15687   switch (IntNo) {
15688   default: return SDValue();    // Don't custom lower most intrinsics.
15689
15690   case Intrinsic::x86_avx2_permd:
15691   case Intrinsic::x86_avx2_permps:
15692     // Operands intentionally swapped. Mask is last operand to intrinsic,
15693     // but second operand for node/instruction.
15694     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15695                        Op.getOperand(2), Op.getOperand(1));
15696
15697   // ptest and testp intrinsics. The intrinsic these come from are designed to
15698   // return an integer value, not just an instruction so lower it to the ptest
15699   // or testp pattern and a setcc for the result.
15700   case Intrinsic::x86_sse41_ptestz:
15701   case Intrinsic::x86_sse41_ptestc:
15702   case Intrinsic::x86_sse41_ptestnzc:
15703   case Intrinsic::x86_avx_ptestz_256:
15704   case Intrinsic::x86_avx_ptestc_256:
15705   case Intrinsic::x86_avx_ptestnzc_256:
15706   case Intrinsic::x86_avx_vtestz_ps:
15707   case Intrinsic::x86_avx_vtestc_ps:
15708   case Intrinsic::x86_avx_vtestnzc_ps:
15709   case Intrinsic::x86_avx_vtestz_pd:
15710   case Intrinsic::x86_avx_vtestc_pd:
15711   case Intrinsic::x86_avx_vtestnzc_pd:
15712   case Intrinsic::x86_avx_vtestz_ps_256:
15713   case Intrinsic::x86_avx_vtestc_ps_256:
15714   case Intrinsic::x86_avx_vtestnzc_ps_256:
15715   case Intrinsic::x86_avx_vtestz_pd_256:
15716   case Intrinsic::x86_avx_vtestc_pd_256:
15717   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15718     bool IsTestPacked = false;
15719     unsigned X86CC;
15720     switch (IntNo) {
15721     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15722     case Intrinsic::x86_avx_vtestz_ps:
15723     case Intrinsic::x86_avx_vtestz_pd:
15724     case Intrinsic::x86_avx_vtestz_ps_256:
15725     case Intrinsic::x86_avx_vtestz_pd_256:
15726       IsTestPacked = true; // Fallthrough
15727     case Intrinsic::x86_sse41_ptestz:
15728     case Intrinsic::x86_avx_ptestz_256:
15729       // ZF = 1
15730       X86CC = X86::COND_E;
15731       break;
15732     case Intrinsic::x86_avx_vtestc_ps:
15733     case Intrinsic::x86_avx_vtestc_pd:
15734     case Intrinsic::x86_avx_vtestc_ps_256:
15735     case Intrinsic::x86_avx_vtestc_pd_256:
15736       IsTestPacked = true; // Fallthrough
15737     case Intrinsic::x86_sse41_ptestc:
15738     case Intrinsic::x86_avx_ptestc_256:
15739       // CF = 1
15740       X86CC = X86::COND_B;
15741       break;
15742     case Intrinsic::x86_avx_vtestnzc_ps:
15743     case Intrinsic::x86_avx_vtestnzc_pd:
15744     case Intrinsic::x86_avx_vtestnzc_ps_256:
15745     case Intrinsic::x86_avx_vtestnzc_pd_256:
15746       IsTestPacked = true; // Fallthrough
15747     case Intrinsic::x86_sse41_ptestnzc:
15748     case Intrinsic::x86_avx_ptestnzc_256:
15749       // ZF and CF = 0
15750       X86CC = X86::COND_A;
15751       break;
15752     }
15753
15754     SDValue LHS = Op.getOperand(1);
15755     SDValue RHS = Op.getOperand(2);
15756     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15757     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15758     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15759     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15760     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15761   }
15762   case Intrinsic::x86_avx512_kortestz_w:
15763   case Intrinsic::x86_avx512_kortestc_w: {
15764     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15765     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15766     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15767     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15768     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15769     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15770     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15771   }
15772
15773   case Intrinsic::x86_sse42_pcmpistria128:
15774   case Intrinsic::x86_sse42_pcmpestria128:
15775   case Intrinsic::x86_sse42_pcmpistric128:
15776   case Intrinsic::x86_sse42_pcmpestric128:
15777   case Intrinsic::x86_sse42_pcmpistrio128:
15778   case Intrinsic::x86_sse42_pcmpestrio128:
15779   case Intrinsic::x86_sse42_pcmpistris128:
15780   case Intrinsic::x86_sse42_pcmpestris128:
15781   case Intrinsic::x86_sse42_pcmpistriz128:
15782   case Intrinsic::x86_sse42_pcmpestriz128: {
15783     unsigned Opcode;
15784     unsigned X86CC;
15785     switch (IntNo) {
15786     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15787     case Intrinsic::x86_sse42_pcmpistria128:
15788       Opcode = X86ISD::PCMPISTRI;
15789       X86CC = X86::COND_A;
15790       break;
15791     case Intrinsic::x86_sse42_pcmpestria128:
15792       Opcode = X86ISD::PCMPESTRI;
15793       X86CC = X86::COND_A;
15794       break;
15795     case Intrinsic::x86_sse42_pcmpistric128:
15796       Opcode = X86ISD::PCMPISTRI;
15797       X86CC = X86::COND_B;
15798       break;
15799     case Intrinsic::x86_sse42_pcmpestric128:
15800       Opcode = X86ISD::PCMPESTRI;
15801       X86CC = X86::COND_B;
15802       break;
15803     case Intrinsic::x86_sse42_pcmpistrio128:
15804       Opcode = X86ISD::PCMPISTRI;
15805       X86CC = X86::COND_O;
15806       break;
15807     case Intrinsic::x86_sse42_pcmpestrio128:
15808       Opcode = X86ISD::PCMPESTRI;
15809       X86CC = X86::COND_O;
15810       break;
15811     case Intrinsic::x86_sse42_pcmpistris128:
15812       Opcode = X86ISD::PCMPISTRI;
15813       X86CC = X86::COND_S;
15814       break;
15815     case Intrinsic::x86_sse42_pcmpestris128:
15816       Opcode = X86ISD::PCMPESTRI;
15817       X86CC = X86::COND_S;
15818       break;
15819     case Intrinsic::x86_sse42_pcmpistriz128:
15820       Opcode = X86ISD::PCMPISTRI;
15821       X86CC = X86::COND_E;
15822       break;
15823     case Intrinsic::x86_sse42_pcmpestriz128:
15824       Opcode = X86ISD::PCMPESTRI;
15825       X86CC = X86::COND_E;
15826       break;
15827     }
15828     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15829     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15830     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15831     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15832                                 DAG.getConstant(X86CC, dl, MVT::i8),
15833                                 SDValue(PCMP.getNode(), 1));
15834     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15835   }
15836
15837   case Intrinsic::x86_sse42_pcmpistri128:
15838   case Intrinsic::x86_sse42_pcmpestri128: {
15839     unsigned Opcode;
15840     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15841       Opcode = X86ISD::PCMPISTRI;
15842     else
15843       Opcode = X86ISD::PCMPESTRI;
15844
15845     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15846     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15847     return DAG.getNode(Opcode, dl, VTs, NewOps);
15848   }
15849
15850   case Intrinsic::x86_seh_lsda: {
15851     // Compute the symbol for the LSDA. We know it'll get emitted later.
15852     MachineFunction &MF = DAG.getMachineFunction();
15853     SDValue Op1 = Op.getOperand(1);
15854     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15855     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15856         GlobalValue::getRealLinkageName(Fn->getName()));
15857
15858     // Generate a simple absolute symbol reference. This intrinsic is only
15859     // supported on 32-bit Windows, which isn't PIC.
15860     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15861     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15862   }
15863
15864   case Intrinsic::x86_seh_recoverfp: {
15865     SDValue FnOp = Op.getOperand(1);
15866     SDValue IncomingFPOp = Op.getOperand(2);
15867     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15868     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15869     if (!Fn)
15870       report_fatal_error(
15871           "llvm.x86.seh.recoverfp must take a function as the first argument");
15872     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15873   }
15874
15875   case Intrinsic::localaddress: {
15876     // Returns one of the stack, base, or frame pointer registers, depending on
15877     // which is used to reference local variables.
15878     MachineFunction &MF = DAG.getMachineFunction();
15879     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15880     unsigned Reg;
15881     if (RegInfo->hasBasePointer(MF))
15882       Reg = RegInfo->getBaseRegister();
15883     else // This function handles the SP or FP case.
15884       Reg = RegInfo->getPtrSizedFrameRegister(MF);
15885     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15886   }
15887   }
15888 }
15889
15890 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15891                               SDValue Src, SDValue Mask, SDValue Base,
15892                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15893                               const X86Subtarget * Subtarget) {
15894   SDLoc dl(Op);
15895   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15896   if (!C)
15897     llvm_unreachable("Invalid scale type");
15898   unsigned ScaleVal = C->getZExtValue();
15899   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15900     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15901
15902   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15903   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15904                              Index.getSimpleValueType().getVectorNumElements());
15905   SDValue MaskInReg;
15906   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15907   if (MaskC)
15908     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15909   else {
15910     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15911                                      Mask.getValueType().getSizeInBits());
15912
15913     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15914     // are extracted by EXTRACT_SUBVECTOR.
15915     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15916                             DAG.getBitcast(BitcastVT, Mask),
15917                             DAG.getIntPtrConstant(0, dl));
15918   }
15919   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15920   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15921   SDValue Segment = DAG.getRegister(0, MVT::i32);
15922   if (Src.getOpcode() == ISD::UNDEF)
15923     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15924   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15925   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15926   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15927   return DAG.getMergeValues(RetOps, dl);
15928 }
15929
15930 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15931                                SDValue Src, SDValue Mask, SDValue Base,
15932                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15933   SDLoc dl(Op);
15934   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15935   if (!C)
15936     llvm_unreachable("Invalid scale type");
15937   unsigned ScaleVal = C->getZExtValue();
15938   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15939     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15940
15941   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15942   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15943   SDValue Segment = DAG.getRegister(0, MVT::i32);
15944   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15945                              Index.getSimpleValueType().getVectorNumElements());
15946   SDValue MaskInReg;
15947   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15948   if (MaskC)
15949     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15950   else {
15951     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15952                                      Mask.getValueType().getSizeInBits());
15953
15954     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15955     // are extracted by EXTRACT_SUBVECTOR.
15956     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15957                             DAG.getBitcast(BitcastVT, Mask),
15958                             DAG.getIntPtrConstant(0, dl));
15959   }
15960   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15961   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15962   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15963   return SDValue(Res, 1);
15964 }
15965
15966 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15967                                SDValue Mask, SDValue Base, SDValue Index,
15968                                SDValue ScaleOp, SDValue Chain) {
15969   SDLoc dl(Op);
15970   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15971   assert(C && "Invalid scale type");
15972   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15973   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15974   SDValue Segment = DAG.getRegister(0, MVT::i32);
15975   EVT MaskVT =
15976     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15977   SDValue MaskInReg;
15978   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15979   if (MaskC)
15980     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15981   else
15982     MaskInReg = DAG.getBitcast(MaskVT, Mask);
15983   //SDVTList VTs = DAG.getVTList(MVT::Other);
15984   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15985   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15986   return SDValue(Res, 0);
15987 }
15988
15989 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15990 // read performance monitor counters (x86_rdpmc).
15991 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15992                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15993                               SmallVectorImpl<SDValue> &Results) {
15994   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15995   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15996   SDValue LO, HI;
15997
15998   // The ECX register is used to select the index of the performance counter
15999   // to read.
16000   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16001                                    N->getOperand(2));
16002   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16003
16004   // Reads the content of a 64-bit performance counter and returns it in the
16005   // registers EDX:EAX.
16006   if (Subtarget->is64Bit()) {
16007     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16008     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16009                             LO.getValue(2));
16010   } else {
16011     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16012     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16013                             LO.getValue(2));
16014   }
16015   Chain = HI.getValue(1);
16016
16017   if (Subtarget->is64Bit()) {
16018     // The EAX register is loaded with the low-order 32 bits. The EDX register
16019     // is loaded with the supported high-order bits of the counter.
16020     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16021                               DAG.getConstant(32, DL, MVT::i8));
16022     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16023     Results.push_back(Chain);
16024     return;
16025   }
16026
16027   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16028   SDValue Ops[] = { LO, HI };
16029   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16030   Results.push_back(Pair);
16031   Results.push_back(Chain);
16032 }
16033
16034 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16035 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16036 // also used to custom lower READCYCLECOUNTER nodes.
16037 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16038                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16039                               SmallVectorImpl<SDValue> &Results) {
16040   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16041   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16042   SDValue LO, HI;
16043
16044   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16045   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16046   // and the EAX register is loaded with the low-order 32 bits.
16047   if (Subtarget->is64Bit()) {
16048     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16049     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16050                             LO.getValue(2));
16051   } else {
16052     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16053     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16054                             LO.getValue(2));
16055   }
16056   SDValue Chain = HI.getValue(1);
16057
16058   if (Opcode == X86ISD::RDTSCP_DAG) {
16059     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16060
16061     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16062     // the ECX register. Add 'ecx' explicitly to the chain.
16063     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16064                                      HI.getValue(2));
16065     // Explicitly store the content of ECX at the location passed in input
16066     // to the 'rdtscp' intrinsic.
16067     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16068                          MachinePointerInfo(), false, false, 0);
16069   }
16070
16071   if (Subtarget->is64Bit()) {
16072     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16073     // the EAX register is loaded with the low-order 32 bits.
16074     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16075                               DAG.getConstant(32, DL, MVT::i8));
16076     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16077     Results.push_back(Chain);
16078     return;
16079   }
16080
16081   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16082   SDValue Ops[] = { LO, HI };
16083   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16084   Results.push_back(Pair);
16085   Results.push_back(Chain);
16086 }
16087
16088 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16089                                      SelectionDAG &DAG) {
16090   SmallVector<SDValue, 2> Results;
16091   SDLoc DL(Op);
16092   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16093                           Results);
16094   return DAG.getMergeValues(Results, DL);
16095 }
16096
16097 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16098                                     SelectionDAG &DAG) {
16099   MachineFunction &MF = DAG.getMachineFunction();
16100   const Function *Fn = MF.getFunction();
16101   SDLoc dl(Op);
16102   SDValue Chain = Op.getOperand(0);
16103
16104   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16105          "using llvm.x86.seh.restoreframe requires a frame pointer");
16106
16107   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16108   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16109
16110   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16111   unsigned FrameReg =
16112       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16113   unsigned SPReg = RegInfo->getStackRegister();
16114   unsigned SlotSize = RegInfo->getSlotSize();
16115
16116   // Get incoming EBP.
16117   SDValue IncomingEBP =
16118       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16119
16120   // SP is saved in the first field of every registration node, so load
16121   // [EBP-RegNodeSize] into SP.
16122   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16123   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16124                                DAG.getConstant(-RegNodeSize, dl, VT));
16125   SDValue NewSP =
16126       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16127                   false, VT.getScalarSizeInBits() / 8);
16128   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16129
16130   if (!RegInfo->needsStackRealignment(MF)) {
16131     // Adjust EBP to point back to the original frame position.
16132     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16133     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16134   } else {
16135     assert(RegInfo->hasBasePointer(MF) &&
16136            "functions with Win32 EH must use frame or base pointer register");
16137
16138     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16139     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16140     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16141
16142     // Reload the spilled EBP value, now that the stack and base pointers are
16143     // set up.
16144     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16145     X86FI->setHasSEHFramePtrSave(true);
16146     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16147     X86FI->setSEHFramePtrSaveIndex(FI);
16148     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16149                                 MachinePointerInfo(), false, false, false,
16150                                 VT.getScalarSizeInBits() / 8);
16151     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16152   }
16153
16154   return Chain;
16155 }
16156
16157 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16158 /// return truncate Store/MaskedStore Node
16159 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16160                                                SelectionDAG &DAG,
16161                                                MVT ElementType) {
16162   SDLoc dl(Op);
16163   SDValue Mask = Op.getOperand(4);
16164   SDValue DataToTruncate = Op.getOperand(3);
16165   SDValue Addr = Op.getOperand(2);
16166   SDValue Chain = Op.getOperand(0);
16167
16168   EVT VT  = DataToTruncate.getValueType();
16169   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16170                              ElementType, VT.getVectorNumElements());
16171
16172   if (isAllOnes(Mask)) // return just a truncate store
16173     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16174                              MachinePointerInfo(), SVT, false, false,
16175                              SVT.getScalarSizeInBits()/8);
16176
16177   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16178                                 MVT::i1, VT.getVectorNumElements());
16179   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16180                                    Mask.getValueType().getSizeInBits());
16181   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16182   // are extracted by EXTRACT_SUBVECTOR.
16183   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16184                               DAG.getBitcast(BitcastVT, Mask),
16185                               DAG.getIntPtrConstant(0, dl));
16186
16187   MachineMemOperand *MMO = DAG.getMachineFunction().
16188     getMachineMemOperand(MachinePointerInfo(),
16189                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16190                          SVT.getScalarSizeInBits()/8);
16191
16192   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16193                             VMask, SVT, MMO, true);
16194 }
16195
16196 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16197                                       SelectionDAG &DAG) {
16198   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16199
16200   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16201   if (!IntrData) {
16202     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16203       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16204     return SDValue();
16205   }
16206
16207   SDLoc dl(Op);
16208   switch(IntrData->Type) {
16209   default:
16210     llvm_unreachable("Unknown Intrinsic Type");
16211     break;
16212   case RDSEED:
16213   case RDRAND: {
16214     // Emit the node with the right value type.
16215     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16216     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16217
16218     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16219     // Otherwise return the value from Rand, which is always 0, casted to i32.
16220     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16221                       DAG.getConstant(1, dl, Op->getValueType(1)),
16222                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16223                       SDValue(Result.getNode(), 1) };
16224     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16225                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16226                                   Ops);
16227
16228     // Return { result, isValid, chain }.
16229     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16230                        SDValue(Result.getNode(), 2));
16231   }
16232   case GATHER: {
16233   //gather(v1, mask, index, base, scale);
16234     SDValue Chain = Op.getOperand(0);
16235     SDValue Src   = Op.getOperand(2);
16236     SDValue Base  = Op.getOperand(3);
16237     SDValue Index = Op.getOperand(4);
16238     SDValue Mask  = Op.getOperand(5);
16239     SDValue Scale = Op.getOperand(6);
16240     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16241                          Chain, Subtarget);
16242   }
16243   case SCATTER: {
16244   //scatter(base, mask, index, v1, scale);
16245     SDValue Chain = Op.getOperand(0);
16246     SDValue Base  = Op.getOperand(2);
16247     SDValue Mask  = Op.getOperand(3);
16248     SDValue Index = Op.getOperand(4);
16249     SDValue Src   = Op.getOperand(5);
16250     SDValue Scale = Op.getOperand(6);
16251     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16252                           Scale, Chain);
16253   }
16254   case PREFETCH: {
16255     SDValue Hint = Op.getOperand(6);
16256     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16257     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16258     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16259     SDValue Chain = Op.getOperand(0);
16260     SDValue Mask  = Op.getOperand(2);
16261     SDValue Index = Op.getOperand(3);
16262     SDValue Base  = Op.getOperand(4);
16263     SDValue Scale = Op.getOperand(5);
16264     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16265   }
16266   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16267   case RDTSC: {
16268     SmallVector<SDValue, 2> Results;
16269     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16270                             Results);
16271     return DAG.getMergeValues(Results, dl);
16272   }
16273   // Read Performance Monitoring Counters.
16274   case RDPMC: {
16275     SmallVector<SDValue, 2> Results;
16276     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16277     return DAG.getMergeValues(Results, dl);
16278   }
16279   // XTEST intrinsics.
16280   case XTEST: {
16281     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16282     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16283     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16284                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16285                                 InTrans);
16286     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16287     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16288                        Ret, SDValue(InTrans.getNode(), 1));
16289   }
16290   // ADC/ADCX/SBB
16291   case ADX: {
16292     SmallVector<SDValue, 2> Results;
16293     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16294     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16295     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16296                                 DAG.getConstant(-1, dl, MVT::i8));
16297     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16298                               Op.getOperand(4), GenCF.getValue(1));
16299     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16300                                  Op.getOperand(5), MachinePointerInfo(),
16301                                  false, false, 0);
16302     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16303                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16304                                 Res.getValue(1));
16305     Results.push_back(SetCC);
16306     Results.push_back(Store);
16307     return DAG.getMergeValues(Results, dl);
16308   }
16309   case COMPRESS_TO_MEM: {
16310     SDLoc dl(Op);
16311     SDValue Mask = Op.getOperand(4);
16312     SDValue DataToCompress = Op.getOperand(3);
16313     SDValue Addr = Op.getOperand(2);
16314     SDValue Chain = Op.getOperand(0);
16315
16316     EVT VT = DataToCompress.getValueType();
16317     if (isAllOnes(Mask)) // return just a store
16318       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16319                           MachinePointerInfo(), false, false,
16320                           VT.getScalarSizeInBits()/8);
16321
16322     SDValue Compressed =
16323       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16324                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16325     return DAG.getStore(Chain, dl, Compressed, Addr,
16326                         MachinePointerInfo(), false, false,
16327                         VT.getScalarSizeInBits()/8);
16328   }
16329   case TRUNCATE_TO_MEM_VI8:
16330     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16331   case TRUNCATE_TO_MEM_VI16:
16332     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16333   case TRUNCATE_TO_MEM_VI32:
16334     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16335   case EXPAND_FROM_MEM: {
16336     SDLoc dl(Op);
16337     SDValue Mask = Op.getOperand(4);
16338     SDValue PassThru = Op.getOperand(3);
16339     SDValue Addr = Op.getOperand(2);
16340     SDValue Chain = Op.getOperand(0);
16341     EVT VT = Op.getValueType();
16342
16343     if (isAllOnes(Mask)) // return just a load
16344       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16345                          false, VT.getScalarSizeInBits()/8);
16346
16347     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16348                                        false, false, false,
16349                                        VT.getScalarSizeInBits()/8);
16350
16351     SDValue Results[] = {
16352       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16353                            Mask, PassThru, Subtarget, DAG), Chain};
16354     return DAG.getMergeValues(Results, dl);
16355   }
16356   }
16357 }
16358
16359 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16360                                            SelectionDAG &DAG) const {
16361   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16362   MFI->setReturnAddressIsTaken(true);
16363
16364   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16365     return SDValue();
16366
16367   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16368   SDLoc dl(Op);
16369   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16370
16371   if (Depth > 0) {
16372     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16373     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16374     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16375     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16376                        DAG.getNode(ISD::ADD, dl, PtrVT,
16377                                    FrameAddr, Offset),
16378                        MachinePointerInfo(), false, false, false, 0);
16379   }
16380
16381   // Just load the return address.
16382   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16383   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16384                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16385 }
16386
16387 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16388   MachineFunction &MF = DAG.getMachineFunction();
16389   MachineFrameInfo *MFI = MF.getFrameInfo();
16390   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16391   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16392   EVT VT = Op.getValueType();
16393
16394   MFI->setFrameAddressIsTaken(true);
16395
16396   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16397     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16398     // is not possible to crawl up the stack without looking at the unwind codes
16399     // simultaneously.
16400     int FrameAddrIndex = FuncInfo->getFAIndex();
16401     if (!FrameAddrIndex) {
16402       // Set up a frame object for the return address.
16403       unsigned SlotSize = RegInfo->getSlotSize();
16404       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16405           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16406       FuncInfo->setFAIndex(FrameAddrIndex);
16407     }
16408     return DAG.getFrameIndex(FrameAddrIndex, VT);
16409   }
16410
16411   unsigned FrameReg =
16412       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16413   SDLoc dl(Op);  // FIXME probably not meaningful
16414   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16415   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16416           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16417          "Invalid Frame Register!");
16418   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16419   while (Depth--)
16420     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16421                             MachinePointerInfo(),
16422                             false, false, false, 0);
16423   return FrameAddr;
16424 }
16425
16426 // FIXME? Maybe this could be a TableGen attribute on some registers and
16427 // this table could be generated automatically from RegInfo.
16428 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16429                                               SelectionDAG &DAG) const {
16430   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16431   const MachineFunction &MF = DAG.getMachineFunction();
16432
16433   unsigned Reg = StringSwitch<unsigned>(RegName)
16434                        .Case("esp", X86::ESP)
16435                        .Case("rsp", X86::RSP)
16436                        .Case("ebp", X86::EBP)
16437                        .Case("rbp", X86::RBP)
16438                        .Default(0);
16439
16440   if (Reg == X86::EBP || Reg == X86::RBP) {
16441     if (!TFI.hasFP(MF))
16442       report_fatal_error("register " + StringRef(RegName) +
16443                          " is allocatable: function has no frame pointer");
16444 #ifndef NDEBUG
16445     else {
16446       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16447       unsigned FrameReg =
16448           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16449       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16450              "Invalid Frame Register!");
16451     }
16452 #endif
16453   }
16454
16455   if (Reg)
16456     return Reg;
16457
16458   report_fatal_error("Invalid register name global variable");
16459 }
16460
16461 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16462                                                      SelectionDAG &DAG) const {
16463   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16464   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16465 }
16466
16467 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16468   SDValue Chain     = Op.getOperand(0);
16469   SDValue Offset    = Op.getOperand(1);
16470   SDValue Handler   = Op.getOperand(2);
16471   SDLoc dl      (Op);
16472
16473   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16474   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16475   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16476   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16477           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16478          "Invalid Frame Register!");
16479   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16480   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16481
16482   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16483                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16484                                                        dl));
16485   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16486   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16487                        false, false, 0);
16488   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16489
16490   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16491                      DAG.getRegister(StoreAddrReg, PtrVT));
16492 }
16493
16494 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16495                                                SelectionDAG &DAG) const {
16496   SDLoc DL(Op);
16497   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16498                      DAG.getVTList(MVT::i32, MVT::Other),
16499                      Op.getOperand(0), Op.getOperand(1));
16500 }
16501
16502 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16503                                                 SelectionDAG &DAG) const {
16504   SDLoc DL(Op);
16505   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16506                      Op.getOperand(0), Op.getOperand(1));
16507 }
16508
16509 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16510   return Op.getOperand(0);
16511 }
16512
16513 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16514                                                 SelectionDAG &DAG) const {
16515   SDValue Root = Op.getOperand(0);
16516   SDValue Trmp = Op.getOperand(1); // trampoline
16517   SDValue FPtr = Op.getOperand(2); // nested function
16518   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16519   SDLoc dl (Op);
16520
16521   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16522   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16523
16524   if (Subtarget->is64Bit()) {
16525     SDValue OutChains[6];
16526
16527     // Large code-model.
16528     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16529     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16530
16531     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16532     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16533
16534     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16535
16536     // Load the pointer to the nested function into R11.
16537     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16538     SDValue Addr = Trmp;
16539     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16540                                 Addr, MachinePointerInfo(TrmpAddr),
16541                                 false, false, 0);
16542
16543     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16544                        DAG.getConstant(2, dl, MVT::i64));
16545     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16546                                 MachinePointerInfo(TrmpAddr, 2),
16547                                 false, false, 2);
16548
16549     // Load the 'nest' parameter value into R10.
16550     // R10 is specified in X86CallingConv.td
16551     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16552     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16553                        DAG.getConstant(10, dl, MVT::i64));
16554     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16555                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16556                                 false, false, 0);
16557
16558     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16559                        DAG.getConstant(12, dl, MVT::i64));
16560     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16561                                 MachinePointerInfo(TrmpAddr, 12),
16562                                 false, false, 2);
16563
16564     // Jump to the nested function.
16565     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16566     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16567                        DAG.getConstant(20, dl, MVT::i64));
16568     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16569                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16570                                 false, false, 0);
16571
16572     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16573     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16574                        DAG.getConstant(22, dl, MVT::i64));
16575     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16576                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16577                                 false, false, 0);
16578
16579     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16580   } else {
16581     const Function *Func =
16582       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16583     CallingConv::ID CC = Func->getCallingConv();
16584     unsigned NestReg;
16585
16586     switch (CC) {
16587     default:
16588       llvm_unreachable("Unsupported calling convention");
16589     case CallingConv::C:
16590     case CallingConv::X86_StdCall: {
16591       // Pass 'nest' parameter in ECX.
16592       // Must be kept in sync with X86CallingConv.td
16593       NestReg = X86::ECX;
16594
16595       // Check that ECX wasn't needed by an 'inreg' parameter.
16596       FunctionType *FTy = Func->getFunctionType();
16597       const AttributeSet &Attrs = Func->getAttributes();
16598
16599       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16600         unsigned InRegCount = 0;
16601         unsigned Idx = 1;
16602
16603         for (FunctionType::param_iterator I = FTy->param_begin(),
16604              E = FTy->param_end(); I != E; ++I, ++Idx)
16605           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16606             auto &DL = DAG.getDataLayout();
16607             // FIXME: should only count parameters that are lowered to integers.
16608             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16609           }
16610
16611         if (InRegCount > 2) {
16612           report_fatal_error("Nest register in use - reduce number of inreg"
16613                              " parameters!");
16614         }
16615       }
16616       break;
16617     }
16618     case CallingConv::X86_FastCall:
16619     case CallingConv::X86_ThisCall:
16620     case CallingConv::Fast:
16621       // Pass 'nest' parameter in EAX.
16622       // Must be kept in sync with X86CallingConv.td
16623       NestReg = X86::EAX;
16624       break;
16625     }
16626
16627     SDValue OutChains[4];
16628     SDValue Addr, Disp;
16629
16630     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16631                        DAG.getConstant(10, dl, MVT::i32));
16632     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16633
16634     // This is storing the opcode for MOV32ri.
16635     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16636     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16637     OutChains[0] = DAG.getStore(Root, dl,
16638                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16639                                 Trmp, MachinePointerInfo(TrmpAddr),
16640                                 false, false, 0);
16641
16642     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16643                        DAG.getConstant(1, dl, MVT::i32));
16644     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16645                                 MachinePointerInfo(TrmpAddr, 1),
16646                                 false, false, 1);
16647
16648     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16649     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16650                        DAG.getConstant(5, dl, MVT::i32));
16651     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16652                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16653                                 false, false, 1);
16654
16655     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16656                        DAG.getConstant(6, dl, MVT::i32));
16657     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16658                                 MachinePointerInfo(TrmpAddr, 6),
16659                                 false, false, 1);
16660
16661     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16662   }
16663 }
16664
16665 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16666                                             SelectionDAG &DAG) const {
16667   /*
16668    The rounding mode is in bits 11:10 of FPSR, and has the following
16669    settings:
16670      00 Round to nearest
16671      01 Round to -inf
16672      10 Round to +inf
16673      11 Round to 0
16674
16675   FLT_ROUNDS, on the other hand, expects the following:
16676     -1 Undefined
16677      0 Round to 0
16678      1 Round to nearest
16679      2 Round to +inf
16680      3 Round to -inf
16681
16682   To perform the conversion, we do:
16683     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16684   */
16685
16686   MachineFunction &MF = DAG.getMachineFunction();
16687   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16688   unsigned StackAlignment = TFI.getStackAlignment();
16689   MVT VT = Op.getSimpleValueType();
16690   SDLoc DL(Op);
16691
16692   // Save FP Control Word to stack slot
16693   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16694   SDValue StackSlot =
16695       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16696
16697   MachineMemOperand *MMO =
16698    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16699                            MachineMemOperand::MOStore, 2, 2);
16700
16701   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16702   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16703                                           DAG.getVTList(MVT::Other),
16704                                           Ops, MVT::i16, MMO);
16705
16706   // Load FP Control Word from stack slot
16707   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16708                             MachinePointerInfo(), false, false, false, 0);
16709
16710   // Transform as necessary
16711   SDValue CWD1 =
16712     DAG.getNode(ISD::SRL, DL, MVT::i16,
16713                 DAG.getNode(ISD::AND, DL, MVT::i16,
16714                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16715                 DAG.getConstant(11, DL, MVT::i8));
16716   SDValue CWD2 =
16717     DAG.getNode(ISD::SRL, DL, MVT::i16,
16718                 DAG.getNode(ISD::AND, DL, MVT::i16,
16719                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16720                 DAG.getConstant(9, DL, MVT::i8));
16721
16722   SDValue RetVal =
16723     DAG.getNode(ISD::AND, DL, MVT::i16,
16724                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16725                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16726                             DAG.getConstant(1, DL, MVT::i16)),
16727                 DAG.getConstant(3, DL, MVT::i16));
16728
16729   return DAG.getNode((VT.getSizeInBits() < 16 ?
16730                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16731 }
16732
16733 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16734   MVT VT = Op.getSimpleValueType();
16735   EVT OpVT = VT;
16736   unsigned NumBits = VT.getSizeInBits();
16737   SDLoc dl(Op);
16738
16739   Op = Op.getOperand(0);
16740   if (VT == MVT::i8) {
16741     // Zero extend to i32 since there is not an i8 bsr.
16742     OpVT = MVT::i32;
16743     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16744   }
16745
16746   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16747   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16748   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16749
16750   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16751   SDValue Ops[] = {
16752     Op,
16753     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16754     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16755     Op.getValue(1)
16756   };
16757   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16758
16759   // Finally xor with NumBits-1.
16760   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16761                    DAG.getConstant(NumBits - 1, dl, OpVT));
16762
16763   if (VT == MVT::i8)
16764     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16765   return Op;
16766 }
16767
16768 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16769   MVT VT = Op.getSimpleValueType();
16770   EVT OpVT = VT;
16771   unsigned NumBits = VT.getSizeInBits();
16772   SDLoc dl(Op);
16773
16774   Op = Op.getOperand(0);
16775   if (VT == MVT::i8) {
16776     // Zero extend to i32 since there is not an i8 bsr.
16777     OpVT = MVT::i32;
16778     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16779   }
16780
16781   // Issue a bsr (scan bits in reverse).
16782   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16783   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16784
16785   // And xor with NumBits-1.
16786   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16787                    DAG.getConstant(NumBits - 1, dl, OpVT));
16788
16789   if (VT == MVT::i8)
16790     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16791   return Op;
16792 }
16793
16794 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16795   MVT VT = Op.getSimpleValueType();
16796   unsigned NumBits = VT.getSizeInBits();
16797   SDLoc dl(Op);
16798   Op = Op.getOperand(0);
16799
16800   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16801   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16802   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16803
16804   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16805   SDValue Ops[] = {
16806     Op,
16807     DAG.getConstant(NumBits, dl, VT),
16808     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16809     Op.getValue(1)
16810   };
16811   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16812 }
16813
16814 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16815 // ones, and then concatenate the result back.
16816 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16817   MVT VT = Op.getSimpleValueType();
16818
16819   assert(VT.is256BitVector() && VT.isInteger() &&
16820          "Unsupported value type for operation");
16821
16822   unsigned NumElems = VT.getVectorNumElements();
16823   SDLoc dl(Op);
16824
16825   // Extract the LHS vectors
16826   SDValue LHS = Op.getOperand(0);
16827   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16828   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16829
16830   // Extract the RHS vectors
16831   SDValue RHS = Op.getOperand(1);
16832   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16833   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16834
16835   MVT EltVT = VT.getVectorElementType();
16836   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16837
16838   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16839                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16840                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16841 }
16842
16843 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16844   if (Op.getValueType() == MVT::i1)
16845     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16846                        Op.getOperand(0), Op.getOperand(1));
16847   assert(Op.getSimpleValueType().is256BitVector() &&
16848          Op.getSimpleValueType().isInteger() &&
16849          "Only handle AVX 256-bit vector integer operation");
16850   return Lower256IntArith(Op, DAG);
16851 }
16852
16853 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16854   if (Op.getValueType() == MVT::i1)
16855     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16856                        Op.getOperand(0), Op.getOperand(1));
16857   assert(Op.getSimpleValueType().is256BitVector() &&
16858          Op.getSimpleValueType().isInteger() &&
16859          "Only handle AVX 256-bit vector integer operation");
16860   return Lower256IntArith(Op, DAG);
16861 }
16862
16863 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16864                         SelectionDAG &DAG) {
16865   SDLoc dl(Op);
16866   MVT VT = Op.getSimpleValueType();
16867
16868   if (VT == MVT::i1)
16869     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16870
16871   // Decompose 256-bit ops into smaller 128-bit ops.
16872   if (VT.is256BitVector() && !Subtarget->hasInt256())
16873     return Lower256IntArith(Op, DAG);
16874
16875   SDValue A = Op.getOperand(0);
16876   SDValue B = Op.getOperand(1);
16877
16878   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16879   // pairs, multiply and truncate.
16880   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16881     if (Subtarget->hasInt256()) {
16882       if (VT == MVT::v32i8) {
16883         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16884         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16885         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16886         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16887         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16888         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16889         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16890         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16891                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16892                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16893       }
16894
16895       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16896       return DAG.getNode(
16897           ISD::TRUNCATE, dl, VT,
16898           DAG.getNode(ISD::MUL, dl, ExVT,
16899                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16900                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16901     }
16902
16903     assert(VT == MVT::v16i8 &&
16904            "Pre-AVX2 support only supports v16i8 multiplication");
16905     MVT ExVT = MVT::v8i16;
16906
16907     // Extract the lo parts and sign extend to i16
16908     SDValue ALo, BLo;
16909     if (Subtarget->hasSSE41()) {
16910       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16911       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16912     } else {
16913       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16914                               -1, 4, -1, 5, -1, 6, -1, 7};
16915       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16916       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16917       ALo = DAG.getBitcast(ExVT, ALo);
16918       BLo = DAG.getBitcast(ExVT, BLo);
16919       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16920       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16921     }
16922
16923     // Extract the hi parts and sign extend to i16
16924     SDValue AHi, BHi;
16925     if (Subtarget->hasSSE41()) {
16926       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16927                               -1, -1, -1, -1, -1, -1, -1, -1};
16928       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16929       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16930       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16931       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16932     } else {
16933       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16934                               -1, 12, -1, 13, -1, 14, -1, 15};
16935       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16936       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16937       AHi = DAG.getBitcast(ExVT, AHi);
16938       BHi = DAG.getBitcast(ExVT, BHi);
16939       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16940       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16941     }
16942
16943     // Multiply, mask the lower 8bits of the lo/hi results and pack
16944     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16945     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16946     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16947     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16948     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16949   }
16950
16951   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16952   if (VT == MVT::v4i32) {
16953     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16954            "Should not custom lower when pmuldq is available!");
16955
16956     // Extract the odd parts.
16957     static const int UnpackMask[] = { 1, -1, 3, -1 };
16958     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16959     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16960
16961     // Multiply the even parts.
16962     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16963     // Now multiply odd parts.
16964     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16965
16966     Evens = DAG.getBitcast(VT, Evens);
16967     Odds = DAG.getBitcast(VT, Odds);
16968
16969     // Merge the two vectors back together with a shuffle. This expands into 2
16970     // shuffles.
16971     static const int ShufMask[] = { 0, 4, 2, 6 };
16972     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16973   }
16974
16975   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16976          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16977
16978   //  Ahi = psrlqi(a, 32);
16979   //  Bhi = psrlqi(b, 32);
16980   //
16981   //  AloBlo = pmuludq(a, b);
16982   //  AloBhi = pmuludq(a, Bhi);
16983   //  AhiBlo = pmuludq(Ahi, b);
16984
16985   //  AloBhi = psllqi(AloBhi, 32);
16986   //  AhiBlo = psllqi(AhiBlo, 32);
16987   //  return AloBlo + AloBhi + AhiBlo;
16988
16989   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16990   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16991
16992   SDValue AhiBlo = Ahi;
16993   SDValue AloBhi = Bhi;
16994   // Bit cast to 32-bit vectors for MULUDQ
16995   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16996                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16997   A = DAG.getBitcast(MulVT, A);
16998   B = DAG.getBitcast(MulVT, B);
16999   Ahi = DAG.getBitcast(MulVT, Ahi);
17000   Bhi = DAG.getBitcast(MulVT, Bhi);
17001
17002   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17003   // After shifting right const values the result may be all-zero.
17004   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17005     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17006     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17007   }
17008   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17009     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17010     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17011   }
17012
17013   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17014   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17015 }
17016
17017 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17018   assert(Subtarget->isTargetWin64() && "Unexpected target");
17019   EVT VT = Op.getValueType();
17020   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17021          "Unexpected return type for lowering");
17022
17023   RTLIB::Libcall LC;
17024   bool isSigned;
17025   switch (Op->getOpcode()) {
17026   default: llvm_unreachable("Unexpected request for libcall!");
17027   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17028   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17029   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17030   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17031   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17032   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17033   }
17034
17035   SDLoc dl(Op);
17036   SDValue InChain = DAG.getEntryNode();
17037
17038   TargetLowering::ArgListTy Args;
17039   TargetLowering::ArgListEntry Entry;
17040   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17041     EVT ArgVT = Op->getOperand(i).getValueType();
17042     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17043            "Unexpected argument type for lowering");
17044     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17045     Entry.Node = StackPtr;
17046     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17047                            false, false, 16);
17048     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17049     Entry.Ty = PointerType::get(ArgTy,0);
17050     Entry.isSExt = false;
17051     Entry.isZExt = false;
17052     Args.push_back(Entry);
17053   }
17054
17055   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17056                                          getPointerTy(DAG.getDataLayout()));
17057
17058   TargetLowering::CallLoweringInfo CLI(DAG);
17059   CLI.setDebugLoc(dl).setChain(InChain)
17060     .setCallee(getLibcallCallingConv(LC),
17061                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17062                Callee, std::move(Args), 0)
17063     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17064
17065   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17066   return DAG.getBitcast(VT, CallInfo.first);
17067 }
17068
17069 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17070                              SelectionDAG &DAG) {
17071   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17072   EVT VT = Op0.getValueType();
17073   SDLoc dl(Op);
17074
17075   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17076          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17077
17078   // PMULxD operations multiply each even value (starting at 0) of LHS with
17079   // the related value of RHS and produce a widen result.
17080   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17081   // => <2 x i64> <ae|cg>
17082   //
17083   // In other word, to have all the results, we need to perform two PMULxD:
17084   // 1. one with the even values.
17085   // 2. one with the odd values.
17086   // To achieve #2, with need to place the odd values at an even position.
17087   //
17088   // Place the odd value at an even position (basically, shift all values 1
17089   // step to the left):
17090   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17091   // <a|b|c|d> => <b|undef|d|undef>
17092   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17093   // <e|f|g|h> => <f|undef|h|undef>
17094   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17095
17096   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17097   // ints.
17098   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17099   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17100   unsigned Opcode =
17101       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17102   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17103   // => <2 x i64> <ae|cg>
17104   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17105   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17106   // => <2 x i64> <bf|dh>
17107   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17108
17109   // Shuffle it back into the right order.
17110   SDValue Highs, Lows;
17111   if (VT == MVT::v8i32) {
17112     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17113     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17114     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17115     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17116   } else {
17117     const int HighMask[] = {1, 5, 3, 7};
17118     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17119     const int LowMask[] = {0, 4, 2, 6};
17120     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17121   }
17122
17123   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17124   // unsigned multiply.
17125   if (IsSigned && !Subtarget->hasSSE41()) {
17126     SDValue ShAmt = DAG.getConstant(
17127         31, dl,
17128         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17129     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17130                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17131     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17132                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17133
17134     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17135     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17136   }
17137
17138   // The first result of MUL_LOHI is actually the low value, followed by the
17139   // high value.
17140   SDValue Ops[] = {Lows, Highs};
17141   return DAG.getMergeValues(Ops, dl);
17142 }
17143
17144 // Return true if the required (according to Opcode) shift-imm form is natively
17145 // supported by the Subtarget
17146 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17147                                         unsigned Opcode) {
17148   if (VT.getScalarSizeInBits() < 16)
17149     return false;
17150
17151   if (VT.is512BitVector() &&
17152       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17153     return true;
17154
17155   bool LShift = VT.is128BitVector() ||
17156     (VT.is256BitVector() && Subtarget->hasInt256());
17157
17158   bool AShift = LShift && (Subtarget->hasVLX() ||
17159     (VT != MVT::v2i64 && VT != MVT::v4i64));
17160   return (Opcode == ISD::SRA) ? AShift : LShift;
17161 }
17162
17163 // The shift amount is a variable, but it is the same for all vector lanes.
17164 // These instructions are defined together with shift-immediate.
17165 static
17166 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17167                                       unsigned Opcode) {
17168   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17169 }
17170
17171 // Return true if the required (according to Opcode) variable-shift form is
17172 // natively supported by the Subtarget
17173 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17174                                     unsigned Opcode) {
17175
17176   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17177     return false;
17178
17179   // vXi16 supported only on AVX-512, BWI
17180   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17181     return false;
17182
17183   if (VT.is512BitVector() || Subtarget->hasVLX())
17184     return true;
17185
17186   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17187   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17188   return (Opcode == ISD::SRA) ? AShift : LShift;
17189 }
17190
17191 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17192                                          const X86Subtarget *Subtarget) {
17193   MVT VT = Op.getSimpleValueType();
17194   SDLoc dl(Op);
17195   SDValue R = Op.getOperand(0);
17196   SDValue Amt = Op.getOperand(1);
17197
17198   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17199     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17200
17201   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17202     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17203     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17204     SDValue Ex = DAG.getBitcast(ExVT, R);
17205
17206     if (ShiftAmt >= 32) {
17207       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17208       SDValue Upper =
17209           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17210       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17211                                                  ShiftAmt - 32, DAG);
17212       if (VT == MVT::v2i64)
17213         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17214       if (VT == MVT::v4i64)
17215         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17216                                   {9, 1, 11, 3, 13, 5, 15, 7});
17217     } else {
17218       // SRA upper i32, SHL whole i64 and select lower i32.
17219       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17220                                                  ShiftAmt, DAG);
17221       SDValue Lower =
17222           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17223       Lower = DAG.getBitcast(ExVT, Lower);
17224       if (VT == MVT::v2i64)
17225         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17226       if (VT == MVT::v4i64)
17227         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17228                                   {8, 1, 10, 3, 12, 5, 14, 7});
17229     }
17230     return DAG.getBitcast(VT, Ex);
17231   };
17232
17233   // Optimize shl/srl/sra with constant shift amount.
17234   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17235     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17236       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17237
17238       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17239         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17240
17241       // i64 SRA needs to be performed as partial shifts.
17242       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17243           Op.getOpcode() == ISD::SRA)
17244         return ArithmeticShiftRight64(ShiftAmt);
17245
17246       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17247         unsigned NumElts = VT.getVectorNumElements();
17248         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17249
17250         if (Op.getOpcode() == ISD::SHL) {
17251           // Simple i8 add case
17252           if (ShiftAmt == 1)
17253             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17254
17255           // Make a large shift.
17256           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17257                                                    R, ShiftAmt, DAG);
17258           SHL = DAG.getBitcast(VT, SHL);
17259           // Zero out the rightmost bits.
17260           SmallVector<SDValue, 32> V(
17261               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17262           return DAG.getNode(ISD::AND, dl, VT, SHL,
17263                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17264         }
17265         if (Op.getOpcode() == ISD::SRL) {
17266           // Make a large shift.
17267           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17268                                                    R, ShiftAmt, DAG);
17269           SRL = DAG.getBitcast(VT, SRL);
17270           // Zero out the leftmost bits.
17271           SmallVector<SDValue, 32> V(
17272               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17273           return DAG.getNode(ISD::AND, dl, VT, SRL,
17274                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17275         }
17276         if (Op.getOpcode() == ISD::SRA) {
17277           if (ShiftAmt == 7) {
17278             // R s>> 7  ===  R s< 0
17279             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17280             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17281           }
17282
17283           // R s>> a === ((R u>> a) ^ m) - m
17284           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17285           SmallVector<SDValue, 32> V(NumElts,
17286                                      DAG.getConstant(128 >> ShiftAmt, dl,
17287                                                      MVT::i8));
17288           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17289           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17290           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17291           return Res;
17292         }
17293         llvm_unreachable("Unknown shift opcode.");
17294       }
17295     }
17296   }
17297
17298   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17299   if (!Subtarget->is64Bit() &&
17300       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17301       Amt.getOpcode() == ISD::BITCAST &&
17302       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17303     Amt = Amt.getOperand(0);
17304     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17305                      VT.getVectorNumElements();
17306     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17307     uint64_t ShiftAmt = 0;
17308     for (unsigned i = 0; i != Ratio; ++i) {
17309       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17310       if (!C)
17311         return SDValue();
17312       // 6 == Log2(64)
17313       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17314     }
17315     // Check remaining shift amounts.
17316     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17317       uint64_t ShAmt = 0;
17318       for (unsigned j = 0; j != Ratio; ++j) {
17319         ConstantSDNode *C =
17320           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17321         if (!C)
17322           return SDValue();
17323         // 6 == Log2(64)
17324         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17325       }
17326       if (ShAmt != ShiftAmt)
17327         return SDValue();
17328     }
17329
17330     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17331       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17332
17333     if (Op.getOpcode() == ISD::SRA)
17334       return ArithmeticShiftRight64(ShiftAmt);
17335   }
17336
17337   return SDValue();
17338 }
17339
17340 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17341                                         const X86Subtarget* Subtarget) {
17342   MVT VT = Op.getSimpleValueType();
17343   SDLoc dl(Op);
17344   SDValue R = Op.getOperand(0);
17345   SDValue Amt = Op.getOperand(1);
17346
17347   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17348     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17349
17350   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17351     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17352
17353   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17354     SDValue BaseShAmt;
17355     EVT EltVT = VT.getVectorElementType();
17356
17357     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17358       // Check if this build_vector node is doing a splat.
17359       // If so, then set BaseShAmt equal to the splat value.
17360       BaseShAmt = BV->getSplatValue();
17361       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17362         BaseShAmt = SDValue();
17363     } else {
17364       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17365         Amt = Amt.getOperand(0);
17366
17367       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17368       if (SVN && SVN->isSplat()) {
17369         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17370         SDValue InVec = Amt.getOperand(0);
17371         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17372           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17373                  "Unexpected shuffle index found!");
17374           BaseShAmt = InVec.getOperand(SplatIdx);
17375         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17376            if (ConstantSDNode *C =
17377                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17378              if (C->getZExtValue() == SplatIdx)
17379                BaseShAmt = InVec.getOperand(1);
17380            }
17381         }
17382
17383         if (!BaseShAmt)
17384           // Avoid introducing an extract element from a shuffle.
17385           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17386                                   DAG.getIntPtrConstant(SplatIdx, dl));
17387       }
17388     }
17389
17390     if (BaseShAmt.getNode()) {
17391       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17392       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17393         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17394       else if (EltVT.bitsLT(MVT::i32))
17395         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17396
17397       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17398     }
17399   }
17400
17401   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17402   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17403       Amt.getOpcode() == ISD::BITCAST &&
17404       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17405     Amt = Amt.getOperand(0);
17406     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17407                      VT.getVectorNumElements();
17408     std::vector<SDValue> Vals(Ratio);
17409     for (unsigned i = 0; i != Ratio; ++i)
17410       Vals[i] = Amt.getOperand(i);
17411     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17412       for (unsigned j = 0; j != Ratio; ++j)
17413         if (Vals[j] != Amt.getOperand(i + j))
17414           return SDValue();
17415     }
17416
17417     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17418       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17419   }
17420   return SDValue();
17421 }
17422
17423 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17424                           SelectionDAG &DAG) {
17425   MVT VT = Op.getSimpleValueType();
17426   SDLoc dl(Op);
17427   SDValue R = Op.getOperand(0);
17428   SDValue Amt = Op.getOperand(1);
17429
17430   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17431   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17432
17433   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17434     return V;
17435
17436   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17437       return V;
17438
17439   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17440     return Op;
17441
17442   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17443   // shifts per-lane and then shuffle the partial results back together.
17444   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17445     // Splat the shift amounts so the scalar shifts above will catch it.
17446     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17447     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17448     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17449     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17450     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17451   }
17452
17453   // If possible, lower this packed shift into a vector multiply instead of
17454   // expanding it into a sequence of scalar shifts.
17455   // Do this only if the vector shift count is a constant build_vector.
17456   if (Op.getOpcode() == ISD::SHL &&
17457       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17458        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17459       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17460     SmallVector<SDValue, 8> Elts;
17461     EVT SVT = VT.getScalarType();
17462     unsigned SVTBits = SVT.getSizeInBits();
17463     const APInt &One = APInt(SVTBits, 1);
17464     unsigned NumElems = VT.getVectorNumElements();
17465
17466     for (unsigned i=0; i !=NumElems; ++i) {
17467       SDValue Op = Amt->getOperand(i);
17468       if (Op->getOpcode() == ISD::UNDEF) {
17469         Elts.push_back(Op);
17470         continue;
17471       }
17472
17473       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17474       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17475       uint64_t ShAmt = C.getZExtValue();
17476       if (ShAmt >= SVTBits) {
17477         Elts.push_back(DAG.getUNDEF(SVT));
17478         continue;
17479       }
17480       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17481     }
17482     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17483     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17484   }
17485
17486   // Lower SHL with variable shift amount.
17487   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17488     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17489
17490     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17491                      DAG.getConstant(0x3f800000U, dl, VT));
17492     Op = DAG.getBitcast(MVT::v4f32, Op);
17493     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17494     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17495   }
17496
17497   // If possible, lower this shift as a sequence of two shifts by
17498   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17499   // Example:
17500   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17501   //
17502   // Could be rewritten as:
17503   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17504   //
17505   // The advantage is that the two shifts from the example would be
17506   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17507   // the vector shift into four scalar shifts plus four pairs of vector
17508   // insert/extract.
17509   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17510       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17511     unsigned TargetOpcode = X86ISD::MOVSS;
17512     bool CanBeSimplified;
17513     // The splat value for the first packed shift (the 'X' from the example).
17514     SDValue Amt1 = Amt->getOperand(0);
17515     // The splat value for the second packed shift (the 'Y' from the example).
17516     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17517                                         Amt->getOperand(2);
17518
17519     // See if it is possible to replace this node with a sequence of
17520     // two shifts followed by a MOVSS/MOVSD
17521     if (VT == MVT::v4i32) {
17522       // Check if it is legal to use a MOVSS.
17523       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17524                         Amt2 == Amt->getOperand(3);
17525       if (!CanBeSimplified) {
17526         // Otherwise, check if we can still simplify this node using a MOVSD.
17527         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17528                           Amt->getOperand(2) == Amt->getOperand(3);
17529         TargetOpcode = X86ISD::MOVSD;
17530         Amt2 = Amt->getOperand(2);
17531       }
17532     } else {
17533       // Do similar checks for the case where the machine value type
17534       // is MVT::v8i16.
17535       CanBeSimplified = Amt1 == Amt->getOperand(1);
17536       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17537         CanBeSimplified = Amt2 == Amt->getOperand(i);
17538
17539       if (!CanBeSimplified) {
17540         TargetOpcode = X86ISD::MOVSD;
17541         CanBeSimplified = true;
17542         Amt2 = Amt->getOperand(4);
17543         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17544           CanBeSimplified = Amt1 == Amt->getOperand(i);
17545         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17546           CanBeSimplified = Amt2 == Amt->getOperand(j);
17547       }
17548     }
17549
17550     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17551         isa<ConstantSDNode>(Amt2)) {
17552       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17553       EVT CastVT = MVT::v4i32;
17554       SDValue Splat1 =
17555         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17556       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17557       SDValue Splat2 =
17558         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17559       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17560       if (TargetOpcode == X86ISD::MOVSD)
17561         CastVT = MVT::v2i64;
17562       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17563       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17564       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17565                                             BitCast1, DAG);
17566       return DAG.getBitcast(VT, Result);
17567     }
17568   }
17569
17570   // v4i32 Non Uniform Shifts.
17571   // If the shift amount is constant we can shift each lane using the SSE2
17572   // immediate shifts, else we need to zero-extend each lane to the lower i64
17573   // and shift using the SSE2 variable shifts.
17574   // The separate results can then be blended together.
17575   if (VT == MVT::v4i32) {
17576     unsigned Opc = Op.getOpcode();
17577     SDValue Amt0, Amt1, Amt2, Amt3;
17578     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17579       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17580       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17581       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17582       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17583     } else {
17584       // ISD::SHL is handled above but we include it here for completeness.
17585       switch (Opc) {
17586       default:
17587         llvm_unreachable("Unknown target vector shift node");
17588       case ISD::SHL:
17589         Opc = X86ISD::VSHL;
17590         break;
17591       case ISD::SRL:
17592         Opc = X86ISD::VSRL;
17593         break;
17594       case ISD::SRA:
17595         Opc = X86ISD::VSRA;
17596         break;
17597       }
17598       // The SSE2 shifts use the lower i64 as the same shift amount for
17599       // all lanes and the upper i64 is ignored. These shuffle masks
17600       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17601       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17602       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17603       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17604       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17605       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17606     }
17607
17608     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17609     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17610     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17611     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17612     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17613     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17614     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17615   }
17616
17617   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17618     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17619     unsigned ShiftOpcode = Op->getOpcode();
17620
17621     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17622       // On SSE41 targets we make use of the fact that VSELECT lowers
17623       // to PBLENDVB which selects bytes based just on the sign bit.
17624       if (Subtarget->hasSSE41()) {
17625         V0 = DAG.getBitcast(VT, V0);
17626         V1 = DAG.getBitcast(VT, V1);
17627         Sel = DAG.getBitcast(VT, Sel);
17628         return DAG.getBitcast(SelVT,
17629                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17630       }
17631       // On pre-SSE41 targets we test for the sign bit by comparing to
17632       // zero - a negative value will set all bits of the lanes to true
17633       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17634       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17635       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17636       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17637     };
17638
17639     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17640     // We can safely do this using i16 shifts as we're only interested in
17641     // the 3 lower bits of each byte.
17642     Amt = DAG.getBitcast(ExtVT, Amt);
17643     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17644     Amt = DAG.getBitcast(VT, Amt);
17645
17646     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17647       // r = VSELECT(r, shift(r, 4), a);
17648       SDValue M =
17649           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17650       R = SignBitSelect(VT, Amt, M, R);
17651
17652       // a += a
17653       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17654
17655       // r = VSELECT(r, shift(r, 2), a);
17656       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17657       R = SignBitSelect(VT, Amt, M, R);
17658
17659       // a += a
17660       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17661
17662       // return VSELECT(r, shift(r, 1), a);
17663       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17664       R = SignBitSelect(VT, Amt, M, R);
17665       return R;
17666     }
17667
17668     if (Op->getOpcode() == ISD::SRA) {
17669       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17670       // so we can correctly sign extend. We don't care what happens to the
17671       // lower byte.
17672       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17673       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17674       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17675       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17676       ALo = DAG.getBitcast(ExtVT, ALo);
17677       AHi = DAG.getBitcast(ExtVT, AHi);
17678       RLo = DAG.getBitcast(ExtVT, RLo);
17679       RHi = DAG.getBitcast(ExtVT, RHi);
17680
17681       // r = VSELECT(r, shift(r, 4), a);
17682       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17683                                 DAG.getConstant(4, dl, ExtVT));
17684       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17685                                 DAG.getConstant(4, dl, ExtVT));
17686       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17687       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17688
17689       // a += a
17690       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17691       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17692
17693       // r = VSELECT(r, shift(r, 2), a);
17694       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17695                         DAG.getConstant(2, dl, ExtVT));
17696       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17697                         DAG.getConstant(2, dl, ExtVT));
17698       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17699       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17700
17701       // a += a
17702       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17703       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17704
17705       // r = VSELECT(r, shift(r, 1), a);
17706       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17707                         DAG.getConstant(1, dl, ExtVT));
17708       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17709                         DAG.getConstant(1, dl, ExtVT));
17710       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17711       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17712
17713       // Logical shift the result back to the lower byte, leaving a zero upper
17714       // byte
17715       // meaning that we can safely pack with PACKUSWB.
17716       RLo =
17717           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17718       RHi =
17719           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17720       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17721     }
17722   }
17723
17724   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17725   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17726   // solution better.
17727   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17728     MVT ExtVT = MVT::v8i32;
17729     unsigned ExtOpc =
17730         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17731     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17732     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17733     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17734                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17735   }
17736
17737   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17738     MVT ExtVT = MVT::v8i32;
17739     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17740     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17741     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17742     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17743     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17744     ALo = DAG.getBitcast(ExtVT, ALo);
17745     AHi = DAG.getBitcast(ExtVT, AHi);
17746     RLo = DAG.getBitcast(ExtVT, RLo);
17747     RHi = DAG.getBitcast(ExtVT, RHi);
17748     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17749     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17750     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17751     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17752     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17753   }
17754
17755   if (VT == MVT::v8i16) {
17756     unsigned ShiftOpcode = Op->getOpcode();
17757
17758     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17759       // On SSE41 targets we make use of the fact that VSELECT lowers
17760       // to PBLENDVB which selects bytes based just on the sign bit.
17761       if (Subtarget->hasSSE41()) {
17762         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17763         V0 = DAG.getBitcast(ExtVT, V0);
17764         V1 = DAG.getBitcast(ExtVT, V1);
17765         Sel = DAG.getBitcast(ExtVT, Sel);
17766         return DAG.getBitcast(
17767             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17768       }
17769       // On pre-SSE41 targets we splat the sign bit - a negative value will
17770       // set all bits of the lanes to true and VSELECT uses that in
17771       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17772       SDValue C =
17773           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17774       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17775     };
17776
17777     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17778     if (Subtarget->hasSSE41()) {
17779       // On SSE41 targets we need to replicate the shift mask in both
17780       // bytes for PBLENDVB.
17781       Amt = DAG.getNode(
17782           ISD::OR, dl, VT,
17783           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17784           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17785     } else {
17786       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17787     }
17788
17789     // r = VSELECT(r, shift(r, 8), a);
17790     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17791     R = SignBitSelect(Amt, M, R);
17792
17793     // a += a
17794     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17795
17796     // r = VSELECT(r, shift(r, 4), a);
17797     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17798     R = SignBitSelect(Amt, M, R);
17799
17800     // a += a
17801     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17802
17803     // r = VSELECT(r, shift(r, 2), a);
17804     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17805     R = SignBitSelect(Amt, M, R);
17806
17807     // a += a
17808     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17809
17810     // return VSELECT(r, shift(r, 1), a);
17811     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17812     R = SignBitSelect(Amt, M, R);
17813     return R;
17814   }
17815
17816   // Decompose 256-bit shifts into smaller 128-bit shifts.
17817   if (VT.is256BitVector()) {
17818     unsigned NumElems = VT.getVectorNumElements();
17819     MVT EltVT = VT.getVectorElementType();
17820     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17821
17822     // Extract the two vectors
17823     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17824     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17825
17826     // Recreate the shift amount vectors
17827     SDValue Amt1, Amt2;
17828     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17829       // Constant shift amount
17830       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17831       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17832       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17833
17834       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17835       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17836     } else {
17837       // Variable shift amount
17838       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17839       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17840     }
17841
17842     // Issue new vector shifts for the smaller types
17843     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17844     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17845
17846     // Concatenate the result back
17847     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17848   }
17849
17850   return SDValue();
17851 }
17852
17853 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17854   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17855   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17856   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17857   // has only one use.
17858   SDNode *N = Op.getNode();
17859   SDValue LHS = N->getOperand(0);
17860   SDValue RHS = N->getOperand(1);
17861   unsigned BaseOp = 0;
17862   unsigned Cond = 0;
17863   SDLoc DL(Op);
17864   switch (Op.getOpcode()) {
17865   default: llvm_unreachable("Unknown ovf instruction!");
17866   case ISD::SADDO:
17867     // A subtract of one will be selected as a INC. Note that INC doesn't
17868     // set CF, so we can't do this for UADDO.
17869     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17870       if (C->isOne()) {
17871         BaseOp = X86ISD::INC;
17872         Cond = X86::COND_O;
17873         break;
17874       }
17875     BaseOp = X86ISD::ADD;
17876     Cond = X86::COND_O;
17877     break;
17878   case ISD::UADDO:
17879     BaseOp = X86ISD::ADD;
17880     Cond = X86::COND_B;
17881     break;
17882   case ISD::SSUBO:
17883     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17884     // set CF, so we can't do this for USUBO.
17885     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17886       if (C->isOne()) {
17887         BaseOp = X86ISD::DEC;
17888         Cond = X86::COND_O;
17889         break;
17890       }
17891     BaseOp = X86ISD::SUB;
17892     Cond = X86::COND_O;
17893     break;
17894   case ISD::USUBO:
17895     BaseOp = X86ISD::SUB;
17896     Cond = X86::COND_B;
17897     break;
17898   case ISD::SMULO:
17899     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17900     Cond = X86::COND_O;
17901     break;
17902   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17903     if (N->getValueType(0) == MVT::i8) {
17904       BaseOp = X86ISD::UMUL8;
17905       Cond = X86::COND_O;
17906       break;
17907     }
17908     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17909                                  MVT::i32);
17910     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17911
17912     SDValue SetCC =
17913       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17914                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17915                   SDValue(Sum.getNode(), 2));
17916
17917     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17918   }
17919   }
17920
17921   // Also sets EFLAGS.
17922   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17923   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17924
17925   SDValue SetCC =
17926     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17927                 DAG.getConstant(Cond, DL, MVT::i32),
17928                 SDValue(Sum.getNode(), 1));
17929
17930   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17931 }
17932
17933 /// Returns true if the operand type is exactly twice the native width, and
17934 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17935 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17936 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17937 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17938   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17939
17940   if (OpWidth == 64)
17941     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17942   else if (OpWidth == 128)
17943     return Subtarget->hasCmpxchg16b();
17944   else
17945     return false;
17946 }
17947
17948 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17949   return needsCmpXchgNb(SI->getValueOperand()->getType());
17950 }
17951
17952 // Note: this turns large loads into lock cmpxchg8b/16b.
17953 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17954 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17955   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17956   return needsCmpXchgNb(PTy->getElementType());
17957 }
17958
17959 TargetLoweringBase::AtomicRMWExpansionKind
17960 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17961   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17962   const Type *MemType = AI->getType();
17963
17964   // If the operand is too big, we must see if cmpxchg8/16b is available
17965   // and default to library calls otherwise.
17966   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17967     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17968                                    : AtomicRMWExpansionKind::None;
17969   }
17970
17971   AtomicRMWInst::BinOp Op = AI->getOperation();
17972   switch (Op) {
17973   default:
17974     llvm_unreachable("Unknown atomic operation");
17975   case AtomicRMWInst::Xchg:
17976   case AtomicRMWInst::Add:
17977   case AtomicRMWInst::Sub:
17978     // It's better to use xadd, xsub or xchg for these in all cases.
17979     return AtomicRMWExpansionKind::None;
17980   case AtomicRMWInst::Or:
17981   case AtomicRMWInst::And:
17982   case AtomicRMWInst::Xor:
17983     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17984     // prefix to a normal instruction for these operations.
17985     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17986                             : AtomicRMWExpansionKind::None;
17987   case AtomicRMWInst::Nand:
17988   case AtomicRMWInst::Max:
17989   case AtomicRMWInst::Min:
17990   case AtomicRMWInst::UMax:
17991   case AtomicRMWInst::UMin:
17992     // These always require a non-trivial set of data operations on x86. We must
17993     // use a cmpxchg loop.
17994     return AtomicRMWExpansionKind::CmpXChg;
17995   }
17996 }
17997
17998 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17999   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18000   // no-sse2). There isn't any reason to disable it if the target processor
18001   // supports it.
18002   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18003 }
18004
18005 LoadInst *
18006 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18007   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18008   const Type *MemType = AI->getType();
18009   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18010   // there is no benefit in turning such RMWs into loads, and it is actually
18011   // harmful as it introduces a mfence.
18012   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18013     return nullptr;
18014
18015   auto Builder = IRBuilder<>(AI);
18016   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18017   auto SynchScope = AI->getSynchScope();
18018   // We must restrict the ordering to avoid generating loads with Release or
18019   // ReleaseAcquire orderings.
18020   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18021   auto Ptr = AI->getPointerOperand();
18022
18023   // Before the load we need a fence. Here is an example lifted from
18024   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18025   // is required:
18026   // Thread 0:
18027   //   x.store(1, relaxed);
18028   //   r1 = y.fetch_add(0, release);
18029   // Thread 1:
18030   //   y.fetch_add(42, acquire);
18031   //   r2 = x.load(relaxed);
18032   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18033   // lowered to just a load without a fence. A mfence flushes the store buffer,
18034   // making the optimization clearly correct.
18035   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18036   // otherwise, we might be able to be more agressive on relaxed idempotent
18037   // rmw. In practice, they do not look useful, so we don't try to be
18038   // especially clever.
18039   if (SynchScope == SingleThread)
18040     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18041     // the IR level, so we must wrap it in an intrinsic.
18042     return nullptr;
18043
18044   if (!hasMFENCE(*Subtarget))
18045     // FIXME: it might make sense to use a locked operation here but on a
18046     // different cache-line to prevent cache-line bouncing. In practice it
18047     // is probably a small win, and x86 processors without mfence are rare
18048     // enough that we do not bother.
18049     return nullptr;
18050
18051   Function *MFence =
18052       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18053   Builder.CreateCall(MFence, {});
18054
18055   // Finally we can emit the atomic load.
18056   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18057           AI->getType()->getPrimitiveSizeInBits());
18058   Loaded->setAtomic(Order, SynchScope);
18059   AI->replaceAllUsesWith(Loaded);
18060   AI->eraseFromParent();
18061   return Loaded;
18062 }
18063
18064 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18065                                  SelectionDAG &DAG) {
18066   SDLoc dl(Op);
18067   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18068     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18069   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18070     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18071
18072   // The only fence that needs an instruction is a sequentially-consistent
18073   // cross-thread fence.
18074   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18075     if (hasMFENCE(*Subtarget))
18076       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18077
18078     SDValue Chain = Op.getOperand(0);
18079     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18080     SDValue Ops[] = {
18081       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18082       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18083       DAG.getRegister(0, MVT::i32),            // Index
18084       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18085       DAG.getRegister(0, MVT::i32),            // Segment.
18086       Zero,
18087       Chain
18088     };
18089     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18090     return SDValue(Res, 0);
18091   }
18092
18093   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18094   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18095 }
18096
18097 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18098                              SelectionDAG &DAG) {
18099   MVT T = Op.getSimpleValueType();
18100   SDLoc DL(Op);
18101   unsigned Reg = 0;
18102   unsigned size = 0;
18103   switch(T.SimpleTy) {
18104   default: llvm_unreachable("Invalid value type!");
18105   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18106   case MVT::i16: Reg = X86::AX;  size = 2; break;
18107   case MVT::i32: Reg = X86::EAX; size = 4; break;
18108   case MVT::i64:
18109     assert(Subtarget->is64Bit() && "Node not type legal!");
18110     Reg = X86::RAX; size = 8;
18111     break;
18112   }
18113   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18114                                   Op.getOperand(2), SDValue());
18115   SDValue Ops[] = { cpIn.getValue(0),
18116                     Op.getOperand(1),
18117                     Op.getOperand(3),
18118                     DAG.getTargetConstant(size, DL, MVT::i8),
18119                     cpIn.getValue(1) };
18120   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18121   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18122   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18123                                            Ops, T, MMO);
18124
18125   SDValue cpOut =
18126     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18127   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18128                                       MVT::i32, cpOut.getValue(2));
18129   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18130                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18131                                 EFLAGS);
18132
18133   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18134   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18135   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18136   return SDValue();
18137 }
18138
18139 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18140                             SelectionDAG &DAG) {
18141   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18142   MVT DstVT = Op.getSimpleValueType();
18143
18144   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18145     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18146     if (DstVT != MVT::f64)
18147       // This conversion needs to be expanded.
18148       return SDValue();
18149
18150     SDValue InVec = Op->getOperand(0);
18151     SDLoc dl(Op);
18152     unsigned NumElts = SrcVT.getVectorNumElements();
18153     EVT SVT = SrcVT.getVectorElementType();
18154
18155     // Widen the vector in input in the case of MVT::v2i32.
18156     // Example: from MVT::v2i32 to MVT::v4i32.
18157     SmallVector<SDValue, 16> Elts;
18158     for (unsigned i = 0, e = NumElts; i != e; ++i)
18159       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18160                                  DAG.getIntPtrConstant(i, dl)));
18161
18162     // Explicitly mark the extra elements as Undef.
18163     Elts.append(NumElts, DAG.getUNDEF(SVT));
18164
18165     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18166     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18167     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18168     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18169                        DAG.getIntPtrConstant(0, dl));
18170   }
18171
18172   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18173          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18174   assert((DstVT == MVT::i64 ||
18175           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18176          "Unexpected custom BITCAST");
18177   // i64 <=> MMX conversions are Legal.
18178   if (SrcVT==MVT::i64 && DstVT.isVector())
18179     return Op;
18180   if (DstVT==MVT::i64 && SrcVT.isVector())
18181     return Op;
18182   // MMX <=> MMX conversions are Legal.
18183   if (SrcVT.isVector() && DstVT.isVector())
18184     return Op;
18185   // All other conversions need to be expanded.
18186   return SDValue();
18187 }
18188
18189 /// Compute the horizontal sum of bytes in V for the elements of VT.
18190 ///
18191 /// Requires V to be a byte vector and VT to be an integer vector type with
18192 /// wider elements than V's type. The width of the elements of VT determines
18193 /// how many bytes of V are summed horizontally to produce each element of the
18194 /// result.
18195 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18196                                       const X86Subtarget *Subtarget,
18197                                       SelectionDAG &DAG) {
18198   SDLoc DL(V);
18199   MVT ByteVecVT = V.getSimpleValueType();
18200   MVT EltVT = VT.getVectorElementType();
18201   int NumElts = VT.getVectorNumElements();
18202   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18203          "Expected value to have byte element type.");
18204   assert(EltVT != MVT::i8 &&
18205          "Horizontal byte sum only makes sense for wider elements!");
18206   unsigned VecSize = VT.getSizeInBits();
18207   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18208
18209   // PSADBW instruction horizontally add all bytes and leave the result in i64
18210   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18211   if (EltVT == MVT::i64) {
18212     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18213     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18214     return DAG.getBitcast(VT, V);
18215   }
18216
18217   if (EltVT == MVT::i32) {
18218     // We unpack the low half and high half into i32s interleaved with zeros so
18219     // that we can use PSADBW to horizontally sum them. The most useful part of
18220     // this is that it lines up the results of two PSADBW instructions to be
18221     // two v2i64 vectors which concatenated are the 4 population counts. We can
18222     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18223     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18224     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18225     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18226
18227     // Do the horizontal sums into two v2i64s.
18228     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18229     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18230                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18231     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18232                        DAG.getBitcast(ByteVecVT, High), Zeros);
18233
18234     // Merge them together.
18235     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18236     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18237                     DAG.getBitcast(ShortVecVT, Low),
18238                     DAG.getBitcast(ShortVecVT, High));
18239
18240     return DAG.getBitcast(VT, V);
18241   }
18242
18243   // The only element type left is i16.
18244   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18245
18246   // To obtain pop count for each i16 element starting from the pop count for
18247   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18248   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18249   // directly supported.
18250   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18251   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18252   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18253   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18254                   DAG.getBitcast(ByteVecVT, V));
18255   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18256 }
18257
18258 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18259                                         const X86Subtarget *Subtarget,
18260                                         SelectionDAG &DAG) {
18261   MVT VT = Op.getSimpleValueType();
18262   MVT EltVT = VT.getVectorElementType();
18263   unsigned VecSize = VT.getSizeInBits();
18264
18265   // Implement a lookup table in register by using an algorithm based on:
18266   // http://wm.ite.pl/articles/sse-popcount.html
18267   //
18268   // The general idea is that every lower byte nibble in the input vector is an
18269   // index into a in-register pre-computed pop count table. We then split up the
18270   // input vector in two new ones: (1) a vector with only the shifted-right
18271   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18272   // masked out higher ones) for each byte. PSHUB is used separately with both
18273   // to index the in-register table. Next, both are added and the result is a
18274   // i8 vector where each element contains the pop count for input byte.
18275   //
18276   // To obtain the pop count for elements != i8, we follow up with the same
18277   // approach and use additional tricks as described below.
18278   //
18279   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18280                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18281                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18282                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18283
18284   int NumByteElts = VecSize / 8;
18285   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18286   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18287   SmallVector<SDValue, 16> LUTVec;
18288   for (int i = 0; i < NumByteElts; ++i)
18289     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18290   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18291   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18292                                   DAG.getConstant(0x0F, DL, MVT::i8));
18293   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18294
18295   // High nibbles
18296   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18297   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18298   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18299
18300   // Low nibbles
18301   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18302
18303   // The input vector is used as the shuffle mask that index elements into the
18304   // LUT. After counting low and high nibbles, add the vector to obtain the
18305   // final pop count per i8 element.
18306   SDValue HighPopCnt =
18307       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18308   SDValue LowPopCnt =
18309       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18310   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18311
18312   if (EltVT == MVT::i8)
18313     return PopCnt;
18314
18315   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18316 }
18317
18318 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18319                                        const X86Subtarget *Subtarget,
18320                                        SelectionDAG &DAG) {
18321   MVT VT = Op.getSimpleValueType();
18322   assert(VT.is128BitVector() &&
18323          "Only 128-bit vector bitmath lowering supported.");
18324
18325   int VecSize = VT.getSizeInBits();
18326   MVT EltVT = VT.getVectorElementType();
18327   int Len = EltVT.getSizeInBits();
18328
18329   // This is the vectorized version of the "best" algorithm from
18330   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18331   // with a minor tweak to use a series of adds + shifts instead of vector
18332   // multiplications. Implemented for all integer vector types. We only use
18333   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18334   // much faster, even faster than using native popcnt instructions.
18335
18336   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18337     MVT VT = V.getSimpleValueType();
18338     SmallVector<SDValue, 32> Shifters(
18339         VT.getVectorNumElements(),
18340         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18341     return DAG.getNode(OpCode, DL, VT, V,
18342                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18343   };
18344   auto GetMask = [&](SDValue V, APInt Mask) {
18345     MVT VT = V.getSimpleValueType();
18346     SmallVector<SDValue, 32> Masks(
18347         VT.getVectorNumElements(),
18348         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18349     return DAG.getNode(ISD::AND, DL, VT, V,
18350                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18351   };
18352
18353   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18354   // x86, so set the SRL type to have elements at least i16 wide. This is
18355   // correct because all of our SRLs are followed immediately by a mask anyways
18356   // that handles any bits that sneak into the high bits of the byte elements.
18357   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18358
18359   SDValue V = Op;
18360
18361   // v = v - ((v >> 1) & 0x55555555...)
18362   SDValue Srl =
18363       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18364   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18365   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18366
18367   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18368   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18369   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18370   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18371   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18372
18373   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18374   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18375   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18376   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18377
18378   // At this point, V contains the byte-wise population count, and we are
18379   // merely doing a horizontal sum if necessary to get the wider element
18380   // counts.
18381   if (EltVT == MVT::i8)
18382     return V;
18383
18384   return LowerHorizontalByteSum(
18385       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18386       DAG);
18387 }
18388
18389 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18390                                 SelectionDAG &DAG) {
18391   MVT VT = Op.getSimpleValueType();
18392   // FIXME: Need to add AVX-512 support here!
18393   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18394          "Unknown CTPOP type to handle");
18395   SDLoc DL(Op.getNode());
18396   SDValue Op0 = Op.getOperand(0);
18397
18398   if (!Subtarget->hasSSSE3()) {
18399     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18400     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18401     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18402   }
18403
18404   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18405     unsigned NumElems = VT.getVectorNumElements();
18406
18407     // Extract each 128-bit vector, compute pop count and concat the result.
18408     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18409     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18410
18411     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18412                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18413                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18414   }
18415
18416   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18417 }
18418
18419 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18420                           SelectionDAG &DAG) {
18421   assert(Op.getValueType().isVector() &&
18422          "We only do custom lowering for vector population count.");
18423   return LowerVectorCTPOP(Op, Subtarget, DAG);
18424 }
18425
18426 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18427   SDNode *Node = Op.getNode();
18428   SDLoc dl(Node);
18429   EVT T = Node->getValueType(0);
18430   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18431                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18432   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18433                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18434                        Node->getOperand(0),
18435                        Node->getOperand(1), negOp,
18436                        cast<AtomicSDNode>(Node)->getMemOperand(),
18437                        cast<AtomicSDNode>(Node)->getOrdering(),
18438                        cast<AtomicSDNode>(Node)->getSynchScope());
18439 }
18440
18441 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18442   SDNode *Node = Op.getNode();
18443   SDLoc dl(Node);
18444   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18445
18446   // Convert seq_cst store -> xchg
18447   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18448   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18449   //        (The only way to get a 16-byte store is cmpxchg16b)
18450   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18451   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18452       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18453     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18454                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18455                                  Node->getOperand(0),
18456                                  Node->getOperand(1), Node->getOperand(2),
18457                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18458                                  cast<AtomicSDNode>(Node)->getOrdering(),
18459                                  cast<AtomicSDNode>(Node)->getSynchScope());
18460     return Swap.getValue(1);
18461   }
18462   // Other atomic stores have a simple pattern.
18463   return Op;
18464 }
18465
18466 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18467   EVT VT = Op.getNode()->getSimpleValueType(0);
18468
18469   // Let legalize expand this if it isn't a legal type yet.
18470   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18471     return SDValue();
18472
18473   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18474
18475   unsigned Opc;
18476   bool ExtraOp = false;
18477   switch (Op.getOpcode()) {
18478   default: llvm_unreachable("Invalid code");
18479   case ISD::ADDC: Opc = X86ISD::ADD; break;
18480   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18481   case ISD::SUBC: Opc = X86ISD::SUB; break;
18482   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18483   }
18484
18485   if (!ExtraOp)
18486     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18487                        Op.getOperand(1));
18488   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18489                      Op.getOperand(1), Op.getOperand(2));
18490 }
18491
18492 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18493                             SelectionDAG &DAG) {
18494   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18495
18496   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18497   // which returns the values as { float, float } (in XMM0) or
18498   // { double, double } (which is returned in XMM0, XMM1).
18499   SDLoc dl(Op);
18500   SDValue Arg = Op.getOperand(0);
18501   EVT ArgVT = Arg.getValueType();
18502   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18503
18504   TargetLowering::ArgListTy Args;
18505   TargetLowering::ArgListEntry Entry;
18506
18507   Entry.Node = Arg;
18508   Entry.Ty = ArgTy;
18509   Entry.isSExt = false;
18510   Entry.isZExt = false;
18511   Args.push_back(Entry);
18512
18513   bool isF64 = ArgVT == MVT::f64;
18514   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18515   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18516   // the results are returned via SRet in memory.
18517   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18518   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18519   SDValue Callee =
18520       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18521
18522   Type *RetTy = isF64
18523     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18524     : (Type*)VectorType::get(ArgTy, 4);
18525
18526   TargetLowering::CallLoweringInfo CLI(DAG);
18527   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18528     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18529
18530   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18531
18532   if (isF64)
18533     // Returned in xmm0 and xmm1.
18534     return CallResult.first;
18535
18536   // Returned in bits 0:31 and 32:64 xmm0.
18537   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18538                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18539   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18540                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18541   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18542   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18543 }
18544
18545 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18546                              SelectionDAG &DAG) {
18547   assert(Subtarget->hasAVX512() &&
18548          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18549
18550   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18551   EVT VT = N->getValue().getValueType();
18552   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18553   SDLoc dl(Op);
18554
18555   // X86 scatter kills mask register, so its type should be added to
18556   // the list of return values
18557   if (N->getNumValues() == 1) {
18558     SDValue Index = N->getIndex();
18559     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18560         !Index.getValueType().is512BitVector())
18561       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18562
18563     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18564     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18565                       N->getOperand(3), Index };
18566
18567     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18568     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18569     return SDValue(NewScatter.getNode(), 0);
18570   }
18571   return Op;
18572 }
18573
18574 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18575                             SelectionDAG &DAG) {
18576   assert(Subtarget->hasAVX512() &&
18577          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18578
18579   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18580   EVT VT = Op.getValueType();
18581   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18582   SDLoc dl(Op);
18583
18584   SDValue Index = N->getIndex();
18585   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18586       !Index.getValueType().is512BitVector()) {
18587     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18588     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18589                       N->getOperand(3), Index };
18590     DAG.UpdateNodeOperands(N, Ops);
18591   }
18592   return Op;
18593 }
18594
18595 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18596                                                     SelectionDAG &DAG) const {
18597   // TODO: Eventually, the lowering of these nodes should be informed by or
18598   // deferred to the GC strategy for the function in which they appear. For
18599   // now, however, they must be lowered to something. Since they are logically
18600   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18601   // require special handling for these nodes), lower them as literal NOOPs for
18602   // the time being.
18603   SmallVector<SDValue, 2> Ops;
18604
18605   Ops.push_back(Op.getOperand(0));
18606   if (Op->getGluedNode())
18607     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18608
18609   SDLoc OpDL(Op);
18610   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18611   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18612
18613   return NOOP;
18614 }
18615
18616 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18617                                                   SelectionDAG &DAG) const {
18618   // TODO: Eventually, the lowering of these nodes should be informed by or
18619   // deferred to the GC strategy for the function in which they appear. For
18620   // now, however, they must be lowered to something. Since they are logically
18621   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18622   // require special handling for these nodes), lower them as literal NOOPs for
18623   // the time being.
18624   SmallVector<SDValue, 2> Ops;
18625
18626   Ops.push_back(Op.getOperand(0));
18627   if (Op->getGluedNode())
18628     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18629
18630   SDLoc OpDL(Op);
18631   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18632   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18633
18634   return NOOP;
18635 }
18636
18637 /// LowerOperation - Provide custom lowering hooks for some operations.
18638 ///
18639 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18640   switch (Op.getOpcode()) {
18641   default: llvm_unreachable("Should not custom lower this!");
18642   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18643   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18644     return LowerCMP_SWAP(Op, Subtarget, DAG);
18645   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18646   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18647   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18648   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18649   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18650   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18651   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18652   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18653   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18654   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18655   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18656   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18657   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18658   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18659   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18660   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18661   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18662   case ISD::SHL_PARTS:
18663   case ISD::SRA_PARTS:
18664   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18665   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18666   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18667   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18668   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18669   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18670   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18671   case ISD::SIGN_EXTEND_VECTOR_INREG:
18672     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18673   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18674   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18675   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18676   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18677   case ISD::FABS:
18678   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18679   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18680   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18681   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18682   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18683   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18684   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18685   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18686   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18687   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18688   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18689   case ISD::INTRINSIC_VOID:
18690   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18691   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18692   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18693   case ISD::FRAME_TO_ARGS_OFFSET:
18694                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18695   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18696   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18697   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18698   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18699   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18700   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18701   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18702   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18703   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18704   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18705   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18706   case ISD::UMUL_LOHI:
18707   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18708   case ISD::SRA:
18709   case ISD::SRL:
18710   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18711   case ISD::SADDO:
18712   case ISD::UADDO:
18713   case ISD::SSUBO:
18714   case ISD::USUBO:
18715   case ISD::SMULO:
18716   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18717   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18718   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18719   case ISD::ADDC:
18720   case ISD::ADDE:
18721   case ISD::SUBC:
18722   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18723   case ISD::ADD:                return LowerADD(Op, DAG);
18724   case ISD::SUB:                return LowerSUB(Op, DAG);
18725   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18726   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18727   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18728   case ISD::GC_TRANSITION_START:
18729                                 return LowerGC_TRANSITION_START(Op, DAG);
18730   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18731   }
18732 }
18733
18734 /// ReplaceNodeResults - Replace a node with an illegal result type
18735 /// with a new node built out of custom code.
18736 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18737                                            SmallVectorImpl<SDValue>&Results,
18738                                            SelectionDAG &DAG) const {
18739   SDLoc dl(N);
18740   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18741   switch (N->getOpcode()) {
18742   default:
18743     llvm_unreachable("Do not know how to custom type legalize this operation!");
18744   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18745   case X86ISD::FMINC:
18746   case X86ISD::FMIN:
18747   case X86ISD::FMAXC:
18748   case X86ISD::FMAX: {
18749     EVT VT = N->getValueType(0);
18750     if (VT != MVT::v2f32)
18751       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18752     SDValue UNDEF = DAG.getUNDEF(VT);
18753     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18754                               N->getOperand(0), UNDEF);
18755     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18756                               N->getOperand(1), UNDEF);
18757     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18758     return;
18759   }
18760   case ISD::SIGN_EXTEND_INREG:
18761   case ISD::ADDC:
18762   case ISD::ADDE:
18763   case ISD::SUBC:
18764   case ISD::SUBE:
18765     // We don't want to expand or promote these.
18766     return;
18767   case ISD::SDIV:
18768   case ISD::UDIV:
18769   case ISD::SREM:
18770   case ISD::UREM:
18771   case ISD::SDIVREM:
18772   case ISD::UDIVREM: {
18773     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18774     Results.push_back(V);
18775     return;
18776   }
18777   case ISD::FP_TO_SINT:
18778     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18779     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18780     if (N->getOperand(0).getValueType() == MVT::f16)
18781       break;
18782     // fallthrough
18783   case ISD::FP_TO_UINT: {
18784     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18785
18786     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18787       return;
18788
18789     std::pair<SDValue,SDValue> Vals =
18790         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18791     SDValue FIST = Vals.first, StackSlot = Vals.second;
18792     if (FIST.getNode()) {
18793       EVT VT = N->getValueType(0);
18794       // Return a load from the stack slot.
18795       if (StackSlot.getNode())
18796         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18797                                       MachinePointerInfo(),
18798                                       false, false, false, 0));
18799       else
18800         Results.push_back(FIST);
18801     }
18802     return;
18803   }
18804   case ISD::UINT_TO_FP: {
18805     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18806     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18807         N->getValueType(0) != MVT::v2f32)
18808       return;
18809     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18810                                  N->getOperand(0));
18811     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18812                                      MVT::f64);
18813     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18814     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18815                              DAG.getBitcast(MVT::v2i64, VBias));
18816     Or = DAG.getBitcast(MVT::v2f64, Or);
18817     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18818     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18819     return;
18820   }
18821   case ISD::FP_ROUND: {
18822     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18823         return;
18824     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18825     Results.push_back(V);
18826     return;
18827   }
18828   case ISD::FP_EXTEND: {
18829     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18830     // No other ValueType for FP_EXTEND should reach this point.
18831     assert(N->getValueType(0) == MVT::v2f32 &&
18832            "Do not know how to legalize this Node");
18833     return;
18834   }
18835   case ISD::INTRINSIC_W_CHAIN: {
18836     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18837     switch (IntNo) {
18838     default : llvm_unreachable("Do not know how to custom type "
18839                                "legalize this intrinsic operation!");
18840     case Intrinsic::x86_rdtsc:
18841       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18842                                      Results);
18843     case Intrinsic::x86_rdtscp:
18844       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18845                                      Results);
18846     case Intrinsic::x86_rdpmc:
18847       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18848     }
18849   }
18850   case ISD::READCYCLECOUNTER: {
18851     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18852                                    Results);
18853   }
18854   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18855     EVT T = N->getValueType(0);
18856     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18857     bool Regs64bit = T == MVT::i128;
18858     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18859     SDValue cpInL, cpInH;
18860     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18861                         DAG.getConstant(0, dl, HalfT));
18862     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18863                         DAG.getConstant(1, dl, HalfT));
18864     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18865                              Regs64bit ? X86::RAX : X86::EAX,
18866                              cpInL, SDValue());
18867     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18868                              Regs64bit ? X86::RDX : X86::EDX,
18869                              cpInH, cpInL.getValue(1));
18870     SDValue swapInL, swapInH;
18871     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18872                           DAG.getConstant(0, dl, HalfT));
18873     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18874                           DAG.getConstant(1, dl, HalfT));
18875     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18876                                Regs64bit ? X86::RBX : X86::EBX,
18877                                swapInL, cpInH.getValue(1));
18878     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18879                                Regs64bit ? X86::RCX : X86::ECX,
18880                                swapInH, swapInL.getValue(1));
18881     SDValue Ops[] = { swapInH.getValue(0),
18882                       N->getOperand(1),
18883                       swapInH.getValue(1) };
18884     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18885     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18886     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18887                                   X86ISD::LCMPXCHG8_DAG;
18888     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18889     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18890                                         Regs64bit ? X86::RAX : X86::EAX,
18891                                         HalfT, Result.getValue(1));
18892     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18893                                         Regs64bit ? X86::RDX : X86::EDX,
18894                                         HalfT, cpOutL.getValue(2));
18895     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18896
18897     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18898                                         MVT::i32, cpOutH.getValue(2));
18899     SDValue Success =
18900         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18901                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18902     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18903
18904     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18905     Results.push_back(Success);
18906     Results.push_back(EFLAGS.getValue(1));
18907     return;
18908   }
18909   case ISD::ATOMIC_SWAP:
18910   case ISD::ATOMIC_LOAD_ADD:
18911   case ISD::ATOMIC_LOAD_SUB:
18912   case ISD::ATOMIC_LOAD_AND:
18913   case ISD::ATOMIC_LOAD_OR:
18914   case ISD::ATOMIC_LOAD_XOR:
18915   case ISD::ATOMIC_LOAD_NAND:
18916   case ISD::ATOMIC_LOAD_MIN:
18917   case ISD::ATOMIC_LOAD_MAX:
18918   case ISD::ATOMIC_LOAD_UMIN:
18919   case ISD::ATOMIC_LOAD_UMAX:
18920   case ISD::ATOMIC_LOAD: {
18921     // Delegate to generic TypeLegalization. Situations we can really handle
18922     // should have already been dealt with by AtomicExpandPass.cpp.
18923     break;
18924   }
18925   case ISD::BITCAST: {
18926     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18927     EVT DstVT = N->getValueType(0);
18928     EVT SrcVT = N->getOperand(0)->getValueType(0);
18929
18930     if (SrcVT != MVT::f64 ||
18931         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18932       return;
18933
18934     unsigned NumElts = DstVT.getVectorNumElements();
18935     EVT SVT = DstVT.getVectorElementType();
18936     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18937     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18938                                    MVT::v2f64, N->getOperand(0));
18939     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18940
18941     if (ExperimentalVectorWideningLegalization) {
18942       // If we are legalizing vectors by widening, we already have the desired
18943       // legal vector type, just return it.
18944       Results.push_back(ToVecInt);
18945       return;
18946     }
18947
18948     SmallVector<SDValue, 8> Elts;
18949     for (unsigned i = 0, e = NumElts; i != e; ++i)
18950       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18951                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18952
18953     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18954   }
18955   }
18956 }
18957
18958 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18959   switch ((X86ISD::NodeType)Opcode) {
18960   case X86ISD::FIRST_NUMBER:       break;
18961   case X86ISD::BSF:                return "X86ISD::BSF";
18962   case X86ISD::BSR:                return "X86ISD::BSR";
18963   case X86ISD::SHLD:               return "X86ISD::SHLD";
18964   case X86ISD::SHRD:               return "X86ISD::SHRD";
18965   case X86ISD::FAND:               return "X86ISD::FAND";
18966   case X86ISD::FANDN:              return "X86ISD::FANDN";
18967   case X86ISD::FOR:                return "X86ISD::FOR";
18968   case X86ISD::FXOR:               return "X86ISD::FXOR";
18969   case X86ISD::FILD:               return "X86ISD::FILD";
18970   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18971   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18972   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18973   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18974   case X86ISD::FLD:                return "X86ISD::FLD";
18975   case X86ISD::FST:                return "X86ISD::FST";
18976   case X86ISD::CALL:               return "X86ISD::CALL";
18977   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18978   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18979   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18980   case X86ISD::BT:                 return "X86ISD::BT";
18981   case X86ISD::CMP:                return "X86ISD::CMP";
18982   case X86ISD::COMI:               return "X86ISD::COMI";
18983   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18984   case X86ISD::CMPM:               return "X86ISD::CMPM";
18985   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18986   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18987   case X86ISD::SETCC:              return "X86ISD::SETCC";
18988   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18989   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18990   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18991   case X86ISD::CMOV:               return "X86ISD::CMOV";
18992   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18993   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18994   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18995   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18996   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18997   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18998   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18999   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19000   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19001   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19002   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19003   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19004   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19005   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19006   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19007   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19008   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19009   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19010   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19011   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19012   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19013   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19014   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19015   case X86ISD::HADD:               return "X86ISD::HADD";
19016   case X86ISD::HSUB:               return "X86ISD::HSUB";
19017   case X86ISD::FHADD:              return "X86ISD::FHADD";
19018   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19019   case X86ISD::ABS:                return "X86ISD::ABS";
19020   case X86ISD::FMAX:               return "X86ISD::FMAX";
19021   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19022   case X86ISD::FMIN:               return "X86ISD::FMIN";
19023   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19024   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19025   case X86ISD::FMINC:              return "X86ISD::FMINC";
19026   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19027   case X86ISD::FRCP:               return "X86ISD::FRCP";
19028   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19029   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19030   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19031   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19032   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19033   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19034   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19035   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19036   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19037   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19038   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19039   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19040   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19041   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19042   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19043   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19044   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19045   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19046   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19047   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19048   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19049   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19050   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19051   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19052   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19053   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19054   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19055   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19056   case X86ISD::VSHL:               return "X86ISD::VSHL";
19057   case X86ISD::VSRL:               return "X86ISD::VSRL";
19058   case X86ISD::VSRA:               return "X86ISD::VSRA";
19059   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19060   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19061   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19062   case X86ISD::CMPP:               return "X86ISD::CMPP";
19063   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19064   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19065   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19066   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19067   case X86ISD::ADD:                return "X86ISD::ADD";
19068   case X86ISD::SUB:                return "X86ISD::SUB";
19069   case X86ISD::ADC:                return "X86ISD::ADC";
19070   case X86ISD::SBB:                return "X86ISD::SBB";
19071   case X86ISD::SMUL:               return "X86ISD::SMUL";
19072   case X86ISD::UMUL:               return "X86ISD::UMUL";
19073   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19074   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19075   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19076   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19077   case X86ISD::INC:                return "X86ISD::INC";
19078   case X86ISD::DEC:                return "X86ISD::DEC";
19079   case X86ISD::OR:                 return "X86ISD::OR";
19080   case X86ISD::XOR:                return "X86ISD::XOR";
19081   case X86ISD::AND:                return "X86ISD::AND";
19082   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19083   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19084   case X86ISD::PTEST:              return "X86ISD::PTEST";
19085   case X86ISD::TESTP:              return "X86ISD::TESTP";
19086   case X86ISD::TESTM:              return "X86ISD::TESTM";
19087   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19088   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19089   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19090   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19091   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19092   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19093   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19094   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19095   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19096   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19097   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19098   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19099   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19100   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19101   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19102   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19103   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19104   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19105   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19106   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19107   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19108   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19109   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19110   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19111   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19112   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19113   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19114   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19115   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19116   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19117   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19118   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19119   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19120   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19121   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19122   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19123   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19124   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19125   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19126   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19127   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19128   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19129   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19130   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19131   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19132   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19133   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19134   case X86ISD::SAHF:               return "X86ISD::SAHF";
19135   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19136   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19137   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19138   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19139   case X86ISD::FMADD:              return "X86ISD::FMADD";
19140   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19141   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19142   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19143   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19144   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19145   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19146   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19147   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19148   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19149   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19150   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19151   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19152   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19153   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19154   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19155   case X86ISD::XTEST:              return "X86ISD::XTEST";
19156   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19157   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19158   case X86ISD::SELECT:             return "X86ISD::SELECT";
19159   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19160   case X86ISD::RCP28:              return "X86ISD::RCP28";
19161   case X86ISD::EXP2:               return "X86ISD::EXP2";
19162   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19163   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19164   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19165   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19166   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19167   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19168   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19169   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19170   case X86ISD::ADDS:               return "X86ISD::ADDS";
19171   case X86ISD::SUBS:               return "X86ISD::SUBS";
19172   case X86ISD::AVG:                return "X86ISD::AVG";
19173   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19174   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19175   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19176   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19177   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19178   }
19179   return nullptr;
19180 }
19181
19182 // isLegalAddressingMode - Return true if the addressing mode represented
19183 // by AM is legal for this target, for a load/store of the specified type.
19184 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19185                                               const AddrMode &AM, Type *Ty,
19186                                               unsigned AS) const {
19187   // X86 supports extremely general addressing modes.
19188   CodeModel::Model M = getTargetMachine().getCodeModel();
19189   Reloc::Model R = getTargetMachine().getRelocationModel();
19190
19191   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19192   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19193     return false;
19194
19195   if (AM.BaseGV) {
19196     unsigned GVFlags =
19197       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19198
19199     // If a reference to this global requires an extra load, we can't fold it.
19200     if (isGlobalStubReference(GVFlags))
19201       return false;
19202
19203     // If BaseGV requires a register for the PIC base, we cannot also have a
19204     // BaseReg specified.
19205     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19206       return false;
19207
19208     // If lower 4G is not available, then we must use rip-relative addressing.
19209     if ((M != CodeModel::Small || R != Reloc::Static) &&
19210         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19211       return false;
19212   }
19213
19214   switch (AM.Scale) {
19215   case 0:
19216   case 1:
19217   case 2:
19218   case 4:
19219   case 8:
19220     // These scales always work.
19221     break;
19222   case 3:
19223   case 5:
19224   case 9:
19225     // These scales are formed with basereg+scalereg.  Only accept if there is
19226     // no basereg yet.
19227     if (AM.HasBaseReg)
19228       return false;
19229     break;
19230   default:  // Other stuff never works.
19231     return false;
19232   }
19233
19234   return true;
19235 }
19236
19237 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19238   unsigned Bits = Ty->getScalarSizeInBits();
19239
19240   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19241   // particularly cheaper than those without.
19242   if (Bits == 8)
19243     return false;
19244
19245   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19246   // variable shifts just as cheap as scalar ones.
19247   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19248     return false;
19249
19250   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19251   // fully general vector.
19252   return true;
19253 }
19254
19255 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19256   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19257     return false;
19258   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19259   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19260   return NumBits1 > NumBits2;
19261 }
19262
19263 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19264   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19265     return false;
19266
19267   if (!isTypeLegal(EVT::getEVT(Ty1)))
19268     return false;
19269
19270   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19271
19272   // Assuming the caller doesn't have a zeroext or signext return parameter,
19273   // truncation all the way down to i1 is valid.
19274   return true;
19275 }
19276
19277 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19278   return isInt<32>(Imm);
19279 }
19280
19281 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19282   // Can also use sub to handle negated immediates.
19283   return isInt<32>(Imm);
19284 }
19285
19286 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19287   if (!VT1.isInteger() || !VT2.isInteger())
19288     return false;
19289   unsigned NumBits1 = VT1.getSizeInBits();
19290   unsigned NumBits2 = VT2.getSizeInBits();
19291   return NumBits1 > NumBits2;
19292 }
19293
19294 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19295   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19296   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19297 }
19298
19299 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19300   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19301   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19302 }
19303
19304 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19305   EVT VT1 = Val.getValueType();
19306   if (isZExtFree(VT1, VT2))
19307     return true;
19308
19309   if (Val.getOpcode() != ISD::LOAD)
19310     return false;
19311
19312   if (!VT1.isSimple() || !VT1.isInteger() ||
19313       !VT2.isSimple() || !VT2.isInteger())
19314     return false;
19315
19316   switch (VT1.getSimpleVT().SimpleTy) {
19317   default: break;
19318   case MVT::i8:
19319   case MVT::i16:
19320   case MVT::i32:
19321     // X86 has 8, 16, and 32-bit zero-extending loads.
19322     return true;
19323   }
19324
19325   return false;
19326 }
19327
19328 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19329
19330 bool
19331 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19332   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19333     return false;
19334
19335   VT = VT.getScalarType();
19336
19337   if (!VT.isSimple())
19338     return false;
19339
19340   switch (VT.getSimpleVT().SimpleTy) {
19341   case MVT::f32:
19342   case MVT::f64:
19343     return true;
19344   default:
19345     break;
19346   }
19347
19348   return false;
19349 }
19350
19351 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19352   // i16 instructions are longer (0x66 prefix) and potentially slower.
19353   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19354 }
19355
19356 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19357 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19358 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19359 /// are assumed to be legal.
19360 bool
19361 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19362                                       EVT VT) const {
19363   if (!VT.isSimple())
19364     return false;
19365
19366   // Not for i1 vectors
19367   if (VT.getScalarType() == MVT::i1)
19368     return false;
19369
19370   // Very little shuffling can be done for 64-bit vectors right now.
19371   if (VT.getSizeInBits() == 64)
19372     return false;
19373
19374   // We only care that the types being shuffled are legal. The lowering can
19375   // handle any possible shuffle mask that results.
19376   return isTypeLegal(VT.getSimpleVT());
19377 }
19378
19379 bool
19380 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19381                                           EVT VT) const {
19382   // Just delegate to the generic legality, clear masks aren't special.
19383   return isShuffleMaskLegal(Mask, VT);
19384 }
19385
19386 //===----------------------------------------------------------------------===//
19387 //                           X86 Scheduler Hooks
19388 //===----------------------------------------------------------------------===//
19389
19390 /// Utility function to emit xbegin specifying the start of an RTM region.
19391 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19392                                      const TargetInstrInfo *TII) {
19393   DebugLoc DL = MI->getDebugLoc();
19394
19395   const BasicBlock *BB = MBB->getBasicBlock();
19396   MachineFunction::iterator I = MBB;
19397   ++I;
19398
19399   // For the v = xbegin(), we generate
19400   //
19401   // thisMBB:
19402   //  xbegin sinkMBB
19403   //
19404   // mainMBB:
19405   //  eax = -1
19406   //
19407   // sinkMBB:
19408   //  v = eax
19409
19410   MachineBasicBlock *thisMBB = MBB;
19411   MachineFunction *MF = MBB->getParent();
19412   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19413   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19414   MF->insert(I, mainMBB);
19415   MF->insert(I, sinkMBB);
19416
19417   // Transfer the remainder of BB and its successor edges to sinkMBB.
19418   sinkMBB->splice(sinkMBB->begin(), MBB,
19419                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19420   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19421
19422   // thisMBB:
19423   //  xbegin sinkMBB
19424   //  # fallthrough to mainMBB
19425   //  # abortion to sinkMBB
19426   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19427   thisMBB->addSuccessor(mainMBB);
19428   thisMBB->addSuccessor(sinkMBB);
19429
19430   // mainMBB:
19431   //  EAX = -1
19432   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19433   mainMBB->addSuccessor(sinkMBB);
19434
19435   // sinkMBB:
19436   // EAX is live into the sinkMBB
19437   sinkMBB->addLiveIn(X86::EAX);
19438   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19439           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19440     .addReg(X86::EAX);
19441
19442   MI->eraseFromParent();
19443   return sinkMBB;
19444 }
19445
19446 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19447 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19448 // in the .td file.
19449 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19450                                        const TargetInstrInfo *TII) {
19451   unsigned Opc;
19452   switch (MI->getOpcode()) {
19453   default: llvm_unreachable("illegal opcode!");
19454   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19455   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19456   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19457   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19458   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19459   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19460   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19461   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19462   }
19463
19464   DebugLoc dl = MI->getDebugLoc();
19465   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19466
19467   unsigned NumArgs = MI->getNumOperands();
19468   for (unsigned i = 1; i < NumArgs; ++i) {
19469     MachineOperand &Op = MI->getOperand(i);
19470     if (!(Op.isReg() && Op.isImplicit()))
19471       MIB.addOperand(Op);
19472   }
19473   if (MI->hasOneMemOperand())
19474     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19475
19476   BuildMI(*BB, MI, dl,
19477     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19478     .addReg(X86::XMM0);
19479
19480   MI->eraseFromParent();
19481   return BB;
19482 }
19483
19484 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19485 // defs in an instruction pattern
19486 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19487                                        const TargetInstrInfo *TII) {
19488   unsigned Opc;
19489   switch (MI->getOpcode()) {
19490   default: llvm_unreachable("illegal opcode!");
19491   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19492   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19493   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19494   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19495   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19496   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19497   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19498   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19499   }
19500
19501   DebugLoc dl = MI->getDebugLoc();
19502   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19503
19504   unsigned NumArgs = MI->getNumOperands(); // remove the results
19505   for (unsigned i = 1; i < NumArgs; ++i) {
19506     MachineOperand &Op = MI->getOperand(i);
19507     if (!(Op.isReg() && Op.isImplicit()))
19508       MIB.addOperand(Op);
19509   }
19510   if (MI->hasOneMemOperand())
19511     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19512
19513   BuildMI(*BB, MI, dl,
19514     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19515     .addReg(X86::ECX);
19516
19517   MI->eraseFromParent();
19518   return BB;
19519 }
19520
19521 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19522                                       const X86Subtarget *Subtarget) {
19523   DebugLoc dl = MI->getDebugLoc();
19524   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19525   // Address into RAX/EAX, other two args into ECX, EDX.
19526   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19527   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19528   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19529   for (int i = 0; i < X86::AddrNumOperands; ++i)
19530     MIB.addOperand(MI->getOperand(i));
19531
19532   unsigned ValOps = X86::AddrNumOperands;
19533   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19534     .addReg(MI->getOperand(ValOps).getReg());
19535   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19536     .addReg(MI->getOperand(ValOps+1).getReg());
19537
19538   // The instruction doesn't actually take any operands though.
19539   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19540
19541   MI->eraseFromParent(); // The pseudo is gone now.
19542   return BB;
19543 }
19544
19545 MachineBasicBlock *
19546 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19547                                                  MachineBasicBlock *MBB) const {
19548   // Emit va_arg instruction on X86-64.
19549
19550   // Operands to this pseudo-instruction:
19551   // 0  ) Output        : destination address (reg)
19552   // 1-5) Input         : va_list address (addr, i64mem)
19553   // 6  ) ArgSize       : Size (in bytes) of vararg type
19554   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19555   // 8  ) Align         : Alignment of type
19556   // 9  ) EFLAGS (implicit-def)
19557
19558   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19559   static_assert(X86::AddrNumOperands == 5,
19560                 "VAARG_64 assumes 5 address operands");
19561
19562   unsigned DestReg = MI->getOperand(0).getReg();
19563   MachineOperand &Base = MI->getOperand(1);
19564   MachineOperand &Scale = MI->getOperand(2);
19565   MachineOperand &Index = MI->getOperand(3);
19566   MachineOperand &Disp = MI->getOperand(4);
19567   MachineOperand &Segment = MI->getOperand(5);
19568   unsigned ArgSize = MI->getOperand(6).getImm();
19569   unsigned ArgMode = MI->getOperand(7).getImm();
19570   unsigned Align = MI->getOperand(8).getImm();
19571
19572   // Memory Reference
19573   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19574   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19575   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19576
19577   // Machine Information
19578   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19579   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19580   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19581   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19582   DebugLoc DL = MI->getDebugLoc();
19583
19584   // struct va_list {
19585   //   i32   gp_offset
19586   //   i32   fp_offset
19587   //   i64   overflow_area (address)
19588   //   i64   reg_save_area (address)
19589   // }
19590   // sizeof(va_list) = 24
19591   // alignment(va_list) = 8
19592
19593   unsigned TotalNumIntRegs = 6;
19594   unsigned TotalNumXMMRegs = 8;
19595   bool UseGPOffset = (ArgMode == 1);
19596   bool UseFPOffset = (ArgMode == 2);
19597   unsigned MaxOffset = TotalNumIntRegs * 8 +
19598                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19599
19600   /* Align ArgSize to a multiple of 8 */
19601   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19602   bool NeedsAlign = (Align > 8);
19603
19604   MachineBasicBlock *thisMBB = MBB;
19605   MachineBasicBlock *overflowMBB;
19606   MachineBasicBlock *offsetMBB;
19607   MachineBasicBlock *endMBB;
19608
19609   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19610   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19611   unsigned OffsetReg = 0;
19612
19613   if (!UseGPOffset && !UseFPOffset) {
19614     // If we only pull from the overflow region, we don't create a branch.
19615     // We don't need to alter control flow.
19616     OffsetDestReg = 0; // unused
19617     OverflowDestReg = DestReg;
19618
19619     offsetMBB = nullptr;
19620     overflowMBB = thisMBB;
19621     endMBB = thisMBB;
19622   } else {
19623     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19624     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19625     // If not, pull from overflow_area. (branch to overflowMBB)
19626     //
19627     //       thisMBB
19628     //         |     .
19629     //         |        .
19630     //     offsetMBB   overflowMBB
19631     //         |        .
19632     //         |     .
19633     //        endMBB
19634
19635     // Registers for the PHI in endMBB
19636     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19637     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19638
19639     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19640     MachineFunction *MF = MBB->getParent();
19641     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19642     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19643     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19644
19645     MachineFunction::iterator MBBIter = MBB;
19646     ++MBBIter;
19647
19648     // Insert the new basic blocks
19649     MF->insert(MBBIter, offsetMBB);
19650     MF->insert(MBBIter, overflowMBB);
19651     MF->insert(MBBIter, endMBB);
19652
19653     // Transfer the remainder of MBB and its successor edges to endMBB.
19654     endMBB->splice(endMBB->begin(), thisMBB,
19655                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19656     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19657
19658     // Make offsetMBB and overflowMBB successors of thisMBB
19659     thisMBB->addSuccessor(offsetMBB);
19660     thisMBB->addSuccessor(overflowMBB);
19661
19662     // endMBB is a successor of both offsetMBB and overflowMBB
19663     offsetMBB->addSuccessor(endMBB);
19664     overflowMBB->addSuccessor(endMBB);
19665
19666     // Load the offset value into a register
19667     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19668     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19669       .addOperand(Base)
19670       .addOperand(Scale)
19671       .addOperand(Index)
19672       .addDisp(Disp, UseFPOffset ? 4 : 0)
19673       .addOperand(Segment)
19674       .setMemRefs(MMOBegin, MMOEnd);
19675
19676     // Check if there is enough room left to pull this argument.
19677     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19678       .addReg(OffsetReg)
19679       .addImm(MaxOffset + 8 - ArgSizeA8);
19680
19681     // Branch to "overflowMBB" if offset >= max
19682     // Fall through to "offsetMBB" otherwise
19683     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19684       .addMBB(overflowMBB);
19685   }
19686
19687   // In offsetMBB, emit code to use the reg_save_area.
19688   if (offsetMBB) {
19689     assert(OffsetReg != 0);
19690
19691     // Read the reg_save_area address.
19692     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19693     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19694       .addOperand(Base)
19695       .addOperand(Scale)
19696       .addOperand(Index)
19697       .addDisp(Disp, 16)
19698       .addOperand(Segment)
19699       .setMemRefs(MMOBegin, MMOEnd);
19700
19701     // Zero-extend the offset
19702     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19703       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19704         .addImm(0)
19705         .addReg(OffsetReg)
19706         .addImm(X86::sub_32bit);
19707
19708     // Add the offset to the reg_save_area to get the final address.
19709     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19710       .addReg(OffsetReg64)
19711       .addReg(RegSaveReg);
19712
19713     // Compute the offset for the next argument
19714     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19715     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19716       .addReg(OffsetReg)
19717       .addImm(UseFPOffset ? 16 : 8);
19718
19719     // Store it back into the va_list.
19720     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19721       .addOperand(Base)
19722       .addOperand(Scale)
19723       .addOperand(Index)
19724       .addDisp(Disp, UseFPOffset ? 4 : 0)
19725       .addOperand(Segment)
19726       .addReg(NextOffsetReg)
19727       .setMemRefs(MMOBegin, MMOEnd);
19728
19729     // Jump to endMBB
19730     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19731       .addMBB(endMBB);
19732   }
19733
19734   //
19735   // Emit code to use overflow area
19736   //
19737
19738   // Load the overflow_area address into a register.
19739   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19740   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19741     .addOperand(Base)
19742     .addOperand(Scale)
19743     .addOperand(Index)
19744     .addDisp(Disp, 8)
19745     .addOperand(Segment)
19746     .setMemRefs(MMOBegin, MMOEnd);
19747
19748   // If we need to align it, do so. Otherwise, just copy the address
19749   // to OverflowDestReg.
19750   if (NeedsAlign) {
19751     // Align the overflow address
19752     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19753     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19754
19755     // aligned_addr = (addr + (align-1)) & ~(align-1)
19756     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19757       .addReg(OverflowAddrReg)
19758       .addImm(Align-1);
19759
19760     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19761       .addReg(TmpReg)
19762       .addImm(~(uint64_t)(Align-1));
19763   } else {
19764     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19765       .addReg(OverflowAddrReg);
19766   }
19767
19768   // Compute the next overflow address after this argument.
19769   // (the overflow address should be kept 8-byte aligned)
19770   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19771   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19772     .addReg(OverflowDestReg)
19773     .addImm(ArgSizeA8);
19774
19775   // Store the new overflow address.
19776   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19777     .addOperand(Base)
19778     .addOperand(Scale)
19779     .addOperand(Index)
19780     .addDisp(Disp, 8)
19781     .addOperand(Segment)
19782     .addReg(NextAddrReg)
19783     .setMemRefs(MMOBegin, MMOEnd);
19784
19785   // If we branched, emit the PHI to the front of endMBB.
19786   if (offsetMBB) {
19787     BuildMI(*endMBB, endMBB->begin(), DL,
19788             TII->get(X86::PHI), DestReg)
19789       .addReg(OffsetDestReg).addMBB(offsetMBB)
19790       .addReg(OverflowDestReg).addMBB(overflowMBB);
19791   }
19792
19793   // Erase the pseudo instruction
19794   MI->eraseFromParent();
19795
19796   return endMBB;
19797 }
19798
19799 MachineBasicBlock *
19800 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19801                                                  MachineInstr *MI,
19802                                                  MachineBasicBlock *MBB) const {
19803   // Emit code to save XMM registers to the stack. The ABI says that the
19804   // number of registers to save is given in %al, so it's theoretically
19805   // possible to do an indirect jump trick to avoid saving all of them,
19806   // however this code takes a simpler approach and just executes all
19807   // of the stores if %al is non-zero. It's less code, and it's probably
19808   // easier on the hardware branch predictor, and stores aren't all that
19809   // expensive anyway.
19810
19811   // Create the new basic blocks. One block contains all the XMM stores,
19812   // and one block is the final destination regardless of whether any
19813   // stores were performed.
19814   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19815   MachineFunction *F = MBB->getParent();
19816   MachineFunction::iterator MBBIter = MBB;
19817   ++MBBIter;
19818   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19819   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19820   F->insert(MBBIter, XMMSaveMBB);
19821   F->insert(MBBIter, EndMBB);
19822
19823   // Transfer the remainder of MBB and its successor edges to EndMBB.
19824   EndMBB->splice(EndMBB->begin(), MBB,
19825                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19826   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19827
19828   // The original block will now fall through to the XMM save block.
19829   MBB->addSuccessor(XMMSaveMBB);
19830   // The XMMSaveMBB will fall through to the end block.
19831   XMMSaveMBB->addSuccessor(EndMBB);
19832
19833   // Now add the instructions.
19834   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19835   DebugLoc DL = MI->getDebugLoc();
19836
19837   unsigned CountReg = MI->getOperand(0).getReg();
19838   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19839   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19840
19841   if (!Subtarget->isTargetWin64()) {
19842     // If %al is 0, branch around the XMM save block.
19843     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19844     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19845     MBB->addSuccessor(EndMBB);
19846   }
19847
19848   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19849   // that was just emitted, but clearly shouldn't be "saved".
19850   assert((MI->getNumOperands() <= 3 ||
19851           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19852           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19853          && "Expected last argument to be EFLAGS");
19854   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19855   // In the XMM save block, save all the XMM argument registers.
19856   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19857     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19858     MachineMemOperand *MMO =
19859       F->getMachineMemOperand(
19860           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19861         MachineMemOperand::MOStore,
19862         /*Size=*/16, /*Align=*/16);
19863     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19864       .addFrameIndex(RegSaveFrameIndex)
19865       .addImm(/*Scale=*/1)
19866       .addReg(/*IndexReg=*/0)
19867       .addImm(/*Disp=*/Offset)
19868       .addReg(/*Segment=*/0)
19869       .addReg(MI->getOperand(i).getReg())
19870       .addMemOperand(MMO);
19871   }
19872
19873   MI->eraseFromParent();   // The pseudo instruction is gone now.
19874
19875   return EndMBB;
19876 }
19877
19878 // The EFLAGS operand of SelectItr might be missing a kill marker
19879 // because there were multiple uses of EFLAGS, and ISel didn't know
19880 // which to mark. Figure out whether SelectItr should have had a
19881 // kill marker, and set it if it should. Returns the correct kill
19882 // marker value.
19883 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19884                                      MachineBasicBlock* BB,
19885                                      const TargetRegisterInfo* TRI) {
19886   // Scan forward through BB for a use/def of EFLAGS.
19887   MachineBasicBlock::iterator miI(std::next(SelectItr));
19888   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19889     const MachineInstr& mi = *miI;
19890     if (mi.readsRegister(X86::EFLAGS))
19891       return false;
19892     if (mi.definesRegister(X86::EFLAGS))
19893       break; // Should have kill-flag - update below.
19894   }
19895
19896   // If we hit the end of the block, check whether EFLAGS is live into a
19897   // successor.
19898   if (miI == BB->end()) {
19899     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19900                                           sEnd = BB->succ_end();
19901          sItr != sEnd; ++sItr) {
19902       MachineBasicBlock* succ = *sItr;
19903       if (succ->isLiveIn(X86::EFLAGS))
19904         return false;
19905     }
19906   }
19907
19908   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19909   // out. SelectMI should have a kill flag on EFLAGS.
19910   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19911   return true;
19912 }
19913
19914 MachineBasicBlock *
19915 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19916                                      MachineBasicBlock *BB) const {
19917   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19918   DebugLoc DL = MI->getDebugLoc();
19919
19920   // To "insert" a SELECT_CC instruction, we actually have to insert the
19921   // diamond control-flow pattern.  The incoming instruction knows the
19922   // destination vreg to set, the condition code register to branch on, the
19923   // true/false values to select between, and a branch opcode to use.
19924   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19925   MachineFunction::iterator It = BB;
19926   ++It;
19927
19928   //  thisMBB:
19929   //  ...
19930   //   TrueVal = ...
19931   //   cmpTY ccX, r1, r2
19932   //   bCC copy1MBB
19933   //   fallthrough --> copy0MBB
19934   MachineBasicBlock *thisMBB = BB;
19935   MachineFunction *F = BB->getParent();
19936
19937   // We also lower double CMOVs:
19938   //   (CMOV (CMOV F, T, cc1), T, cc2)
19939   // to two successives branches.  For that, we look for another CMOV as the
19940   // following instruction.
19941   //
19942   // Without this, we would add a PHI between the two jumps, which ends up
19943   // creating a few copies all around. For instance, for
19944   //
19945   //    (sitofp (zext (fcmp une)))
19946   //
19947   // we would generate:
19948   //
19949   //         ucomiss %xmm1, %xmm0
19950   //         movss  <1.0f>, %xmm0
19951   //         movaps  %xmm0, %xmm1
19952   //         jne     .LBB5_2
19953   //         xorps   %xmm1, %xmm1
19954   // .LBB5_2:
19955   //         jp      .LBB5_4
19956   //         movaps  %xmm1, %xmm0
19957   // .LBB5_4:
19958   //         retq
19959   //
19960   // because this custom-inserter would have generated:
19961   //
19962   //   A
19963   //   | \
19964   //   |  B
19965   //   | /
19966   //   C
19967   //   | \
19968   //   |  D
19969   //   | /
19970   //   E
19971   //
19972   // A: X = ...; Y = ...
19973   // B: empty
19974   // C: Z = PHI [X, A], [Y, B]
19975   // D: empty
19976   // E: PHI [X, C], [Z, D]
19977   //
19978   // If we lower both CMOVs in a single step, we can instead generate:
19979   //
19980   //   A
19981   //   | \
19982   //   |  C
19983   //   | /|
19984   //   |/ |
19985   //   |  |
19986   //   |  D
19987   //   | /
19988   //   E
19989   //
19990   // A: X = ...; Y = ...
19991   // D: empty
19992   // E: PHI [X, A], [X, C], [Y, D]
19993   //
19994   // Which, in our sitofp/fcmp example, gives us something like:
19995   //
19996   //         ucomiss %xmm1, %xmm0
19997   //         movss  <1.0f>, %xmm0
19998   //         jne     .LBB5_4
19999   //         jp      .LBB5_4
20000   //         xorps   %xmm0, %xmm0
20001   // .LBB5_4:
20002   //         retq
20003   //
20004   MachineInstr *NextCMOV = nullptr;
20005   MachineBasicBlock::iterator NextMIIt =
20006       std::next(MachineBasicBlock::iterator(MI));
20007   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20008       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20009       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
20010     NextCMOV = &*NextMIIt;
20011
20012   MachineBasicBlock *jcc1MBB = nullptr;
20013
20014   // If we have a double CMOV, we lower it to two successive branches to
20015   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20016   if (NextCMOV) {
20017     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20018     F->insert(It, jcc1MBB);
20019     jcc1MBB->addLiveIn(X86::EFLAGS);
20020   }
20021
20022   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20023   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20024   F->insert(It, copy0MBB);
20025   F->insert(It, sinkMBB);
20026
20027   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20028   // live into the sink and copy blocks.
20029   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20030
20031   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
20032   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20033       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20034     copy0MBB->addLiveIn(X86::EFLAGS);
20035     sinkMBB->addLiveIn(X86::EFLAGS);
20036   }
20037
20038   // Transfer the remainder of BB and its successor edges to sinkMBB.
20039   sinkMBB->splice(sinkMBB->begin(), BB,
20040                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
20041   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20042
20043   // Add the true and fallthrough blocks as its successors.
20044   if (NextCMOV) {
20045     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
20046     BB->addSuccessor(jcc1MBB);
20047
20048     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20049     // jump to the sinkMBB.
20050     jcc1MBB->addSuccessor(copy0MBB);
20051     jcc1MBB->addSuccessor(sinkMBB);
20052   } else {
20053     BB->addSuccessor(copy0MBB);
20054   }
20055
20056   // The true block target of the first (or only) branch is always sinkMBB.
20057   BB->addSuccessor(sinkMBB);
20058
20059   // Create the conditional branch instruction.
20060   unsigned Opc =
20061     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
20062   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20063
20064   if (NextCMOV) {
20065     unsigned Opc2 = X86::GetCondBranchFromCond(
20066         (X86::CondCode)NextCMOV->getOperand(3).getImm());
20067     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20068   }
20069
20070   //  copy0MBB:
20071   //   %FalseValue = ...
20072   //   # fallthrough to sinkMBB
20073   copy0MBB->addSuccessor(sinkMBB);
20074
20075   //  sinkMBB:
20076   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20077   //  ...
20078   MachineInstrBuilder MIB =
20079       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
20080               MI->getOperand(0).getReg())
20081           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
20082           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
20083
20084   // If we have a double CMOV, the second Jcc provides the same incoming
20085   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20086   if (NextCMOV) {
20087     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20088     // Copy the PHI result to the register defined by the second CMOV.
20089     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20090             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
20091         .addReg(MI->getOperand(0).getReg());
20092     NextCMOV->eraseFromParent();
20093   }
20094
20095   MI->eraseFromParent();   // The pseudo instruction is gone now.
20096   return sinkMBB;
20097 }
20098
20099 MachineBasicBlock *
20100 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20101                                         MachineBasicBlock *BB) const {
20102   MachineFunction *MF = BB->getParent();
20103   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20104   DebugLoc DL = MI->getDebugLoc();
20105   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20106
20107   assert(MF->shouldSplitStack());
20108
20109   const bool Is64Bit = Subtarget->is64Bit();
20110   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20111
20112   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20113   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20114
20115   // BB:
20116   //  ... [Till the alloca]
20117   // If stacklet is not large enough, jump to mallocMBB
20118   //
20119   // bumpMBB:
20120   //  Allocate by subtracting from RSP
20121   //  Jump to continueMBB
20122   //
20123   // mallocMBB:
20124   //  Allocate by call to runtime
20125   //
20126   // continueMBB:
20127   //  ...
20128   //  [rest of original BB]
20129   //
20130
20131   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20132   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20133   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20134
20135   MachineRegisterInfo &MRI = MF->getRegInfo();
20136   const TargetRegisterClass *AddrRegClass =
20137       getRegClassFor(getPointerTy(MF->getDataLayout()));
20138
20139   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20140     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20141     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20142     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20143     sizeVReg = MI->getOperand(1).getReg(),
20144     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20145
20146   MachineFunction::iterator MBBIter = BB;
20147   ++MBBIter;
20148
20149   MF->insert(MBBIter, bumpMBB);
20150   MF->insert(MBBIter, mallocMBB);
20151   MF->insert(MBBIter, continueMBB);
20152
20153   continueMBB->splice(continueMBB->begin(), BB,
20154                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20155   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20156
20157   // Add code to the main basic block to check if the stack limit has been hit,
20158   // and if so, jump to mallocMBB otherwise to bumpMBB.
20159   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20160   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20161     .addReg(tmpSPVReg).addReg(sizeVReg);
20162   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20163     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20164     .addReg(SPLimitVReg);
20165   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20166
20167   // bumpMBB simply decreases the stack pointer, since we know the current
20168   // stacklet has enough space.
20169   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20170     .addReg(SPLimitVReg);
20171   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20172     .addReg(SPLimitVReg);
20173   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20174
20175   // Calls into a routine in libgcc to allocate more space from the heap.
20176   const uint32_t *RegMask =
20177       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20178   if (IsLP64) {
20179     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20180       .addReg(sizeVReg);
20181     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20182       .addExternalSymbol("__morestack_allocate_stack_space")
20183       .addRegMask(RegMask)
20184       .addReg(X86::RDI, RegState::Implicit)
20185       .addReg(X86::RAX, RegState::ImplicitDefine);
20186   } else if (Is64Bit) {
20187     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20188       .addReg(sizeVReg);
20189     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20190       .addExternalSymbol("__morestack_allocate_stack_space")
20191       .addRegMask(RegMask)
20192       .addReg(X86::EDI, RegState::Implicit)
20193       .addReg(X86::EAX, RegState::ImplicitDefine);
20194   } else {
20195     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20196       .addImm(12);
20197     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20198     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20199       .addExternalSymbol("__morestack_allocate_stack_space")
20200       .addRegMask(RegMask)
20201       .addReg(X86::EAX, RegState::ImplicitDefine);
20202   }
20203
20204   if (!Is64Bit)
20205     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20206       .addImm(16);
20207
20208   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20209     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20210   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20211
20212   // Set up the CFG correctly.
20213   BB->addSuccessor(bumpMBB);
20214   BB->addSuccessor(mallocMBB);
20215   mallocMBB->addSuccessor(continueMBB);
20216   bumpMBB->addSuccessor(continueMBB);
20217
20218   // Take care of the PHI nodes.
20219   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20220           MI->getOperand(0).getReg())
20221     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20222     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20223
20224   // Delete the original pseudo instruction.
20225   MI->eraseFromParent();
20226
20227   // And we're done.
20228   return continueMBB;
20229 }
20230
20231 MachineBasicBlock *
20232 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20233                                         MachineBasicBlock *BB) const {
20234   DebugLoc DL = MI->getDebugLoc();
20235
20236   assert(!Subtarget->isTargetMachO());
20237
20238   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20239                                                     DL);
20240
20241   MI->eraseFromParent();   // The pseudo instruction is gone now.
20242   return BB;
20243 }
20244
20245 MachineBasicBlock *
20246 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20247                                       MachineBasicBlock *BB) const {
20248   // This is pretty easy.  We're taking the value that we received from
20249   // our load from the relocation, sticking it in either RDI (x86-64)
20250   // or EAX and doing an indirect call.  The return value will then
20251   // be in the normal return register.
20252   MachineFunction *F = BB->getParent();
20253   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20254   DebugLoc DL = MI->getDebugLoc();
20255
20256   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20257   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20258
20259   // Get a register mask for the lowered call.
20260   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20261   // proper register mask.
20262   const uint32_t *RegMask =
20263       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20264   if (Subtarget->is64Bit()) {
20265     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20266                                       TII->get(X86::MOV64rm), X86::RDI)
20267     .addReg(X86::RIP)
20268     .addImm(0).addReg(0)
20269     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20270                       MI->getOperand(3).getTargetFlags())
20271     .addReg(0);
20272     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20273     addDirectMem(MIB, X86::RDI);
20274     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20275   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20276     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20277                                       TII->get(X86::MOV32rm), X86::EAX)
20278     .addReg(0)
20279     .addImm(0).addReg(0)
20280     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20281                       MI->getOperand(3).getTargetFlags())
20282     .addReg(0);
20283     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20284     addDirectMem(MIB, X86::EAX);
20285     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20286   } else {
20287     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20288                                       TII->get(X86::MOV32rm), X86::EAX)
20289     .addReg(TII->getGlobalBaseReg(F))
20290     .addImm(0).addReg(0)
20291     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20292                       MI->getOperand(3).getTargetFlags())
20293     .addReg(0);
20294     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20295     addDirectMem(MIB, X86::EAX);
20296     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20297   }
20298
20299   MI->eraseFromParent(); // The pseudo instruction is gone now.
20300   return BB;
20301 }
20302
20303 MachineBasicBlock *
20304 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20305                                     MachineBasicBlock *MBB) const {
20306   DebugLoc DL = MI->getDebugLoc();
20307   MachineFunction *MF = MBB->getParent();
20308   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20309   MachineRegisterInfo &MRI = MF->getRegInfo();
20310
20311   const BasicBlock *BB = MBB->getBasicBlock();
20312   MachineFunction::iterator I = MBB;
20313   ++I;
20314
20315   // Memory Reference
20316   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20317   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20318
20319   unsigned DstReg;
20320   unsigned MemOpndSlot = 0;
20321
20322   unsigned CurOp = 0;
20323
20324   DstReg = MI->getOperand(CurOp++).getReg();
20325   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20326   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20327   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20328   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20329
20330   MemOpndSlot = CurOp;
20331
20332   MVT PVT = getPointerTy(MF->getDataLayout());
20333   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20334          "Invalid Pointer Size!");
20335
20336   // For v = setjmp(buf), we generate
20337   //
20338   // thisMBB:
20339   //  buf[LabelOffset] = restoreMBB
20340   //  SjLjSetup restoreMBB
20341   //
20342   // mainMBB:
20343   //  v_main = 0
20344   //
20345   // sinkMBB:
20346   //  v = phi(main, restore)
20347   //
20348   // restoreMBB:
20349   //  if base pointer being used, load it from frame
20350   //  v_restore = 1
20351
20352   MachineBasicBlock *thisMBB = MBB;
20353   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20354   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20355   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20356   MF->insert(I, mainMBB);
20357   MF->insert(I, sinkMBB);
20358   MF->push_back(restoreMBB);
20359
20360   MachineInstrBuilder MIB;
20361
20362   // Transfer the remainder of BB and its successor edges to sinkMBB.
20363   sinkMBB->splice(sinkMBB->begin(), MBB,
20364                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20365   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20366
20367   // thisMBB:
20368   unsigned PtrStoreOpc = 0;
20369   unsigned LabelReg = 0;
20370   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20371   Reloc::Model RM = MF->getTarget().getRelocationModel();
20372   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20373                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20374
20375   // Prepare IP either in reg or imm.
20376   if (!UseImmLabel) {
20377     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20378     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20379     LabelReg = MRI.createVirtualRegister(PtrRC);
20380     if (Subtarget->is64Bit()) {
20381       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20382               .addReg(X86::RIP)
20383               .addImm(0)
20384               .addReg(0)
20385               .addMBB(restoreMBB)
20386               .addReg(0);
20387     } else {
20388       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20389       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20390               .addReg(XII->getGlobalBaseReg(MF))
20391               .addImm(0)
20392               .addReg(0)
20393               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20394               .addReg(0);
20395     }
20396   } else
20397     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20398   // Store IP
20399   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20400   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20401     if (i == X86::AddrDisp)
20402       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20403     else
20404       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20405   }
20406   if (!UseImmLabel)
20407     MIB.addReg(LabelReg);
20408   else
20409     MIB.addMBB(restoreMBB);
20410   MIB.setMemRefs(MMOBegin, MMOEnd);
20411   // Setup
20412   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20413           .addMBB(restoreMBB);
20414
20415   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20416   MIB.addRegMask(RegInfo->getNoPreservedMask());
20417   thisMBB->addSuccessor(mainMBB);
20418   thisMBB->addSuccessor(restoreMBB);
20419
20420   // mainMBB:
20421   //  EAX = 0
20422   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20423   mainMBB->addSuccessor(sinkMBB);
20424
20425   // sinkMBB:
20426   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20427           TII->get(X86::PHI), DstReg)
20428     .addReg(mainDstReg).addMBB(mainMBB)
20429     .addReg(restoreDstReg).addMBB(restoreMBB);
20430
20431   // restoreMBB:
20432   if (RegInfo->hasBasePointer(*MF)) {
20433     const bool Uses64BitFramePtr =
20434         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20435     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20436     X86FI->setRestoreBasePointer(MF);
20437     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20438     unsigned BasePtr = RegInfo->getBaseRegister();
20439     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20440     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20441                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20442       .setMIFlag(MachineInstr::FrameSetup);
20443   }
20444   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20445   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20446   restoreMBB->addSuccessor(sinkMBB);
20447
20448   MI->eraseFromParent();
20449   return sinkMBB;
20450 }
20451
20452 MachineBasicBlock *
20453 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20454                                      MachineBasicBlock *MBB) const {
20455   DebugLoc DL = MI->getDebugLoc();
20456   MachineFunction *MF = MBB->getParent();
20457   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20458   MachineRegisterInfo &MRI = MF->getRegInfo();
20459
20460   // Memory Reference
20461   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20462   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20463
20464   MVT PVT = getPointerTy(MF->getDataLayout());
20465   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20466          "Invalid Pointer Size!");
20467
20468   const TargetRegisterClass *RC =
20469     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20470   unsigned Tmp = MRI.createVirtualRegister(RC);
20471   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20472   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20473   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20474   unsigned SP = RegInfo->getStackRegister();
20475
20476   MachineInstrBuilder MIB;
20477
20478   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20479   const int64_t SPOffset = 2 * PVT.getStoreSize();
20480
20481   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20482   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20483
20484   // Reload FP
20485   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20486   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20487     MIB.addOperand(MI->getOperand(i));
20488   MIB.setMemRefs(MMOBegin, MMOEnd);
20489   // Reload IP
20490   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20491   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20492     if (i == X86::AddrDisp)
20493       MIB.addDisp(MI->getOperand(i), LabelOffset);
20494     else
20495       MIB.addOperand(MI->getOperand(i));
20496   }
20497   MIB.setMemRefs(MMOBegin, MMOEnd);
20498   // Reload SP
20499   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20500   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20501     if (i == X86::AddrDisp)
20502       MIB.addDisp(MI->getOperand(i), SPOffset);
20503     else
20504       MIB.addOperand(MI->getOperand(i));
20505   }
20506   MIB.setMemRefs(MMOBegin, MMOEnd);
20507   // Jump
20508   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20509
20510   MI->eraseFromParent();
20511   return MBB;
20512 }
20513
20514 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20515 // accumulator loops. Writing back to the accumulator allows the coalescer
20516 // to remove extra copies in the loop.
20517 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20518 MachineBasicBlock *
20519 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20520                                  MachineBasicBlock *MBB) const {
20521   MachineOperand &AddendOp = MI->getOperand(3);
20522
20523   // Bail out early if the addend isn't a register - we can't switch these.
20524   if (!AddendOp.isReg())
20525     return MBB;
20526
20527   MachineFunction &MF = *MBB->getParent();
20528   MachineRegisterInfo &MRI = MF.getRegInfo();
20529
20530   // Check whether the addend is defined by a PHI:
20531   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20532   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20533   if (!AddendDef.isPHI())
20534     return MBB;
20535
20536   // Look for the following pattern:
20537   // loop:
20538   //   %addend = phi [%entry, 0], [%loop, %result]
20539   //   ...
20540   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20541
20542   // Replace with:
20543   //   loop:
20544   //   %addend = phi [%entry, 0], [%loop, %result]
20545   //   ...
20546   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20547
20548   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20549     assert(AddendDef.getOperand(i).isReg());
20550     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20551     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20552     if (&PHISrcInst == MI) {
20553       // Found a matching instruction.
20554       unsigned NewFMAOpc = 0;
20555       switch (MI->getOpcode()) {
20556         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20557         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20558         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20559         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20560         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20561         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20562         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20563         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20564         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20565         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20566         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20567         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20568         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20569         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20570         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20571         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20572         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20573         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20574         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20575         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20576
20577         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20578         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20579         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20580         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20581         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20582         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20583         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20584         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20585         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20586         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20587         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20588         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20589         default: llvm_unreachable("Unrecognized FMA variant.");
20590       }
20591
20592       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20593       MachineInstrBuilder MIB =
20594         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20595         .addOperand(MI->getOperand(0))
20596         .addOperand(MI->getOperand(3))
20597         .addOperand(MI->getOperand(2))
20598         .addOperand(MI->getOperand(1));
20599       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20600       MI->eraseFromParent();
20601     }
20602   }
20603
20604   return MBB;
20605 }
20606
20607 MachineBasicBlock *
20608 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20609                                                MachineBasicBlock *BB) const {
20610   switch (MI->getOpcode()) {
20611   default: llvm_unreachable("Unexpected instr type to insert");
20612   case X86::TAILJMPd64:
20613   case X86::TAILJMPr64:
20614   case X86::TAILJMPm64:
20615   case X86::TAILJMPd64_REX:
20616   case X86::TAILJMPr64_REX:
20617   case X86::TAILJMPm64_REX:
20618     llvm_unreachable("TAILJMP64 would not be touched here.");
20619   case X86::TCRETURNdi64:
20620   case X86::TCRETURNri64:
20621   case X86::TCRETURNmi64:
20622     return BB;
20623   case X86::WIN_ALLOCA:
20624     return EmitLoweredWinAlloca(MI, BB);
20625   case X86::SEG_ALLOCA_32:
20626   case X86::SEG_ALLOCA_64:
20627     return EmitLoweredSegAlloca(MI, BB);
20628   case X86::TLSCall_32:
20629   case X86::TLSCall_64:
20630     return EmitLoweredTLSCall(MI, BB);
20631   case X86::CMOV_GR8:
20632   case X86::CMOV_FR32:
20633   case X86::CMOV_FR64:
20634   case X86::CMOV_V4F32:
20635   case X86::CMOV_V2F64:
20636   case X86::CMOV_V2I64:
20637   case X86::CMOV_V8F32:
20638   case X86::CMOV_V4F64:
20639   case X86::CMOV_V4I64:
20640   case X86::CMOV_V16F32:
20641   case X86::CMOV_V8F64:
20642   case X86::CMOV_V8I64:
20643   case X86::CMOV_GR16:
20644   case X86::CMOV_GR32:
20645   case X86::CMOV_RFP32:
20646   case X86::CMOV_RFP64:
20647   case X86::CMOV_RFP80:
20648   case X86::CMOV_V8I1:
20649   case X86::CMOV_V16I1:
20650   case X86::CMOV_V32I1:
20651   case X86::CMOV_V64I1:
20652     return EmitLoweredSelect(MI, BB);
20653
20654   case X86::FP32_TO_INT16_IN_MEM:
20655   case X86::FP32_TO_INT32_IN_MEM:
20656   case X86::FP32_TO_INT64_IN_MEM:
20657   case X86::FP64_TO_INT16_IN_MEM:
20658   case X86::FP64_TO_INT32_IN_MEM:
20659   case X86::FP64_TO_INT64_IN_MEM:
20660   case X86::FP80_TO_INT16_IN_MEM:
20661   case X86::FP80_TO_INT32_IN_MEM:
20662   case X86::FP80_TO_INT64_IN_MEM: {
20663     MachineFunction *F = BB->getParent();
20664     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20665     DebugLoc DL = MI->getDebugLoc();
20666
20667     // Change the floating point control register to use "round towards zero"
20668     // mode when truncating to an integer value.
20669     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20670     addFrameReference(BuildMI(*BB, MI, DL,
20671                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20672
20673     // Load the old value of the high byte of the control word...
20674     unsigned OldCW =
20675       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20676     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20677                       CWFrameIdx);
20678
20679     // Set the high part to be round to zero...
20680     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20681       .addImm(0xC7F);
20682
20683     // Reload the modified control word now...
20684     addFrameReference(BuildMI(*BB, MI, DL,
20685                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20686
20687     // Restore the memory image of control word to original value
20688     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20689       .addReg(OldCW);
20690
20691     // Get the X86 opcode to use.
20692     unsigned Opc;
20693     switch (MI->getOpcode()) {
20694     default: llvm_unreachable("illegal opcode!");
20695     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20696     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20697     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20698     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20699     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20700     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20701     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20702     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20703     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20704     }
20705
20706     X86AddressMode AM;
20707     MachineOperand &Op = MI->getOperand(0);
20708     if (Op.isReg()) {
20709       AM.BaseType = X86AddressMode::RegBase;
20710       AM.Base.Reg = Op.getReg();
20711     } else {
20712       AM.BaseType = X86AddressMode::FrameIndexBase;
20713       AM.Base.FrameIndex = Op.getIndex();
20714     }
20715     Op = MI->getOperand(1);
20716     if (Op.isImm())
20717       AM.Scale = Op.getImm();
20718     Op = MI->getOperand(2);
20719     if (Op.isImm())
20720       AM.IndexReg = Op.getImm();
20721     Op = MI->getOperand(3);
20722     if (Op.isGlobal()) {
20723       AM.GV = Op.getGlobal();
20724     } else {
20725       AM.Disp = Op.getImm();
20726     }
20727     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20728                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20729
20730     // Reload the original control word now.
20731     addFrameReference(BuildMI(*BB, MI, DL,
20732                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20733
20734     MI->eraseFromParent();   // The pseudo instruction is gone now.
20735     return BB;
20736   }
20737     // String/text processing lowering.
20738   case X86::PCMPISTRM128REG:
20739   case X86::VPCMPISTRM128REG:
20740   case X86::PCMPISTRM128MEM:
20741   case X86::VPCMPISTRM128MEM:
20742   case X86::PCMPESTRM128REG:
20743   case X86::VPCMPESTRM128REG:
20744   case X86::PCMPESTRM128MEM:
20745   case X86::VPCMPESTRM128MEM:
20746     assert(Subtarget->hasSSE42() &&
20747            "Target must have SSE4.2 or AVX features enabled");
20748     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20749
20750   // String/text processing lowering.
20751   case X86::PCMPISTRIREG:
20752   case X86::VPCMPISTRIREG:
20753   case X86::PCMPISTRIMEM:
20754   case X86::VPCMPISTRIMEM:
20755   case X86::PCMPESTRIREG:
20756   case X86::VPCMPESTRIREG:
20757   case X86::PCMPESTRIMEM:
20758   case X86::VPCMPESTRIMEM:
20759     assert(Subtarget->hasSSE42() &&
20760            "Target must have SSE4.2 or AVX features enabled");
20761     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20762
20763   // Thread synchronization.
20764   case X86::MONITOR:
20765     return EmitMonitor(MI, BB, Subtarget);
20766
20767   // xbegin
20768   case X86::XBEGIN:
20769     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20770
20771   case X86::VASTART_SAVE_XMM_REGS:
20772     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20773
20774   case X86::VAARG_64:
20775     return EmitVAARG64WithCustomInserter(MI, BB);
20776
20777   case X86::EH_SjLj_SetJmp32:
20778   case X86::EH_SjLj_SetJmp64:
20779     return emitEHSjLjSetJmp(MI, BB);
20780
20781   case X86::EH_SjLj_LongJmp32:
20782   case X86::EH_SjLj_LongJmp64:
20783     return emitEHSjLjLongJmp(MI, BB);
20784
20785   case TargetOpcode::STATEPOINT:
20786     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20787     // this point in the process.  We diverge later.
20788     return emitPatchPoint(MI, BB);
20789
20790   case TargetOpcode::STACKMAP:
20791   case TargetOpcode::PATCHPOINT:
20792     return emitPatchPoint(MI, BB);
20793
20794   case X86::VFMADDPDr213r:
20795   case X86::VFMADDPSr213r:
20796   case X86::VFMADDSDr213r:
20797   case X86::VFMADDSSr213r:
20798   case X86::VFMSUBPDr213r:
20799   case X86::VFMSUBPSr213r:
20800   case X86::VFMSUBSDr213r:
20801   case X86::VFMSUBSSr213r:
20802   case X86::VFNMADDPDr213r:
20803   case X86::VFNMADDPSr213r:
20804   case X86::VFNMADDSDr213r:
20805   case X86::VFNMADDSSr213r:
20806   case X86::VFNMSUBPDr213r:
20807   case X86::VFNMSUBPSr213r:
20808   case X86::VFNMSUBSDr213r:
20809   case X86::VFNMSUBSSr213r:
20810   case X86::VFMADDSUBPDr213r:
20811   case X86::VFMADDSUBPSr213r:
20812   case X86::VFMSUBADDPDr213r:
20813   case X86::VFMSUBADDPSr213r:
20814   case X86::VFMADDPDr213rY:
20815   case X86::VFMADDPSr213rY:
20816   case X86::VFMSUBPDr213rY:
20817   case X86::VFMSUBPSr213rY:
20818   case X86::VFNMADDPDr213rY:
20819   case X86::VFNMADDPSr213rY:
20820   case X86::VFNMSUBPDr213rY:
20821   case X86::VFNMSUBPSr213rY:
20822   case X86::VFMADDSUBPDr213rY:
20823   case X86::VFMADDSUBPSr213rY:
20824   case X86::VFMSUBADDPDr213rY:
20825   case X86::VFMSUBADDPSr213rY:
20826     return emitFMA3Instr(MI, BB);
20827   }
20828 }
20829
20830 //===----------------------------------------------------------------------===//
20831 //                           X86 Optimization Hooks
20832 //===----------------------------------------------------------------------===//
20833
20834 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20835                                                       APInt &KnownZero,
20836                                                       APInt &KnownOne,
20837                                                       const SelectionDAG &DAG,
20838                                                       unsigned Depth) const {
20839   unsigned BitWidth = KnownZero.getBitWidth();
20840   unsigned Opc = Op.getOpcode();
20841   assert((Opc >= ISD::BUILTIN_OP_END ||
20842           Opc == ISD::INTRINSIC_WO_CHAIN ||
20843           Opc == ISD::INTRINSIC_W_CHAIN ||
20844           Opc == ISD::INTRINSIC_VOID) &&
20845          "Should use MaskedValueIsZero if you don't know whether Op"
20846          " is a target node!");
20847
20848   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20849   switch (Opc) {
20850   default: break;
20851   case X86ISD::ADD:
20852   case X86ISD::SUB:
20853   case X86ISD::ADC:
20854   case X86ISD::SBB:
20855   case X86ISD::SMUL:
20856   case X86ISD::UMUL:
20857   case X86ISD::INC:
20858   case X86ISD::DEC:
20859   case X86ISD::OR:
20860   case X86ISD::XOR:
20861   case X86ISD::AND:
20862     // These nodes' second result is a boolean.
20863     if (Op.getResNo() == 0)
20864       break;
20865     // Fallthrough
20866   case X86ISD::SETCC:
20867     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20868     break;
20869   case ISD::INTRINSIC_WO_CHAIN: {
20870     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20871     unsigned NumLoBits = 0;
20872     switch (IntId) {
20873     default: break;
20874     case Intrinsic::x86_sse_movmsk_ps:
20875     case Intrinsic::x86_avx_movmsk_ps_256:
20876     case Intrinsic::x86_sse2_movmsk_pd:
20877     case Intrinsic::x86_avx_movmsk_pd_256:
20878     case Intrinsic::x86_mmx_pmovmskb:
20879     case Intrinsic::x86_sse2_pmovmskb_128:
20880     case Intrinsic::x86_avx2_pmovmskb: {
20881       // High bits of movmskp{s|d}, pmovmskb are known zero.
20882       switch (IntId) {
20883         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
20884         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
20885         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
20886         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
20887         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
20888         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
20889         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
20890         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
20891       }
20892       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20893       break;
20894     }
20895     }
20896     break;
20897   }
20898   }
20899 }
20900
20901 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20902   SDValue Op,
20903   const SelectionDAG &,
20904   unsigned Depth) const {
20905   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20906   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20907     return Op.getValueType().getScalarType().getSizeInBits();
20908
20909   // Fallback case.
20910   return 1;
20911 }
20912
20913 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20914 /// node is a GlobalAddress + offset.
20915 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20916                                        const GlobalValue* &GA,
20917                                        int64_t &Offset) const {
20918   if (N->getOpcode() == X86ISD::Wrapper) {
20919     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20920       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20921       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20922       return true;
20923     }
20924   }
20925   return TargetLowering::isGAPlusOffset(N, GA, Offset);
20926 }
20927
20928 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20929 /// same as extracting the high 128-bit part of 256-bit vector and then
20930 /// inserting the result into the low part of a new 256-bit vector
20931 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20932   EVT VT = SVOp->getValueType(0);
20933   unsigned NumElems = VT.getVectorNumElements();
20934
20935   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20936   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20937     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20938         SVOp->getMaskElt(j) >= 0)
20939       return false;
20940
20941   return true;
20942 }
20943
20944 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20945 /// same as extracting the low 128-bit part of 256-bit vector and then
20946 /// inserting the result into the high part of a new 256-bit vector
20947 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20948   EVT VT = SVOp->getValueType(0);
20949   unsigned NumElems = VT.getVectorNumElements();
20950
20951   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20952   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20953     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20954         SVOp->getMaskElt(j) >= 0)
20955       return false;
20956
20957   return true;
20958 }
20959
20960 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20961 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20962                                         TargetLowering::DAGCombinerInfo &DCI,
20963                                         const X86Subtarget* Subtarget) {
20964   SDLoc dl(N);
20965   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20966   SDValue V1 = SVOp->getOperand(0);
20967   SDValue V2 = SVOp->getOperand(1);
20968   EVT VT = SVOp->getValueType(0);
20969   unsigned NumElems = VT.getVectorNumElements();
20970
20971   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20972       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20973     //
20974     //                   0,0,0,...
20975     //                      |
20976     //    V      UNDEF    BUILD_VECTOR    UNDEF
20977     //     \      /           \           /
20978     //  CONCAT_VECTOR         CONCAT_VECTOR
20979     //         \                  /
20980     //          \                /
20981     //          RESULT: V + zero extended
20982     //
20983     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20984         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20985         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20986       return SDValue();
20987
20988     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20989       return SDValue();
20990
20991     // To match the shuffle mask, the first half of the mask should
20992     // be exactly the first vector, and all the rest a splat with the
20993     // first element of the second one.
20994     for (unsigned i = 0; i != NumElems/2; ++i)
20995       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20996           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20997         return SDValue();
20998
20999     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21000     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21001       if (Ld->hasNUsesOfValue(1, 0)) {
21002         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21003         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21004         SDValue ResNode =
21005           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21006                                   Ld->getMemoryVT(),
21007                                   Ld->getPointerInfo(),
21008                                   Ld->getAlignment(),
21009                                   false/*isVolatile*/, true/*ReadMem*/,
21010                                   false/*WriteMem*/);
21011
21012         // Make sure the newly-created LOAD is in the same position as Ld in
21013         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21014         // and update uses of Ld's output chain to use the TokenFactor.
21015         if (Ld->hasAnyUseOfValue(1)) {
21016           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21017                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21018           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21019           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21020                                  SDValue(ResNode.getNode(), 1));
21021         }
21022
21023         return DAG.getBitcast(VT, ResNode);
21024       }
21025     }
21026
21027     // Emit a zeroed vector and insert the desired subvector on its
21028     // first half.
21029     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21030     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21031     return DCI.CombineTo(N, InsV);
21032   }
21033
21034   //===--------------------------------------------------------------------===//
21035   // Combine some shuffles into subvector extracts and inserts:
21036   //
21037
21038   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21039   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21040     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21041     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21042     return DCI.CombineTo(N, InsV);
21043   }
21044
21045   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21046   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21047     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21048     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21049     return DCI.CombineTo(N, InsV);
21050   }
21051
21052   return SDValue();
21053 }
21054
21055 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21056 /// possible.
21057 ///
21058 /// This is the leaf of the recursive combinine below. When we have found some
21059 /// chain of single-use x86 shuffle instructions and accumulated the combined
21060 /// shuffle mask represented by them, this will try to pattern match that mask
21061 /// into either a single instruction if there is a special purpose instruction
21062 /// for this operation, or into a PSHUFB instruction which is a fully general
21063 /// instruction but should only be used to replace chains over a certain depth.
21064 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21065                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21066                                    TargetLowering::DAGCombinerInfo &DCI,
21067                                    const X86Subtarget *Subtarget) {
21068   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21069
21070   // Find the operand that enters the chain. Note that multiple uses are OK
21071   // here, we're not going to remove the operand we find.
21072   SDValue Input = Op.getOperand(0);
21073   while (Input.getOpcode() == ISD::BITCAST)
21074     Input = Input.getOperand(0);
21075
21076   MVT VT = Input.getSimpleValueType();
21077   MVT RootVT = Root.getSimpleValueType();
21078   SDLoc DL(Root);
21079
21080   // Just remove no-op shuffle masks.
21081   if (Mask.size() == 1) {
21082     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21083                   /*AddTo*/ true);
21084     return true;
21085   }
21086
21087   // Use the float domain if the operand type is a floating point type.
21088   bool FloatDomain = VT.isFloatingPoint();
21089
21090   // For floating point shuffles, we don't have free copies in the shuffle
21091   // instructions or the ability to load as part of the instruction, so
21092   // canonicalize their shuffles to UNPCK or MOV variants.
21093   //
21094   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21095   // vectors because it can have a load folded into it that UNPCK cannot. This
21096   // doesn't preclude something switching to the shorter encoding post-RA.
21097   //
21098   // FIXME: Should teach these routines about AVX vector widths.
21099   if (FloatDomain && VT.getSizeInBits() == 128) {
21100     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21101       bool Lo = Mask.equals({0, 0});
21102       unsigned Shuffle;
21103       MVT ShuffleVT;
21104       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21105       // is no slower than UNPCKLPD but has the option to fold the input operand
21106       // into even an unaligned memory load.
21107       if (Lo && Subtarget->hasSSE3()) {
21108         Shuffle = X86ISD::MOVDDUP;
21109         ShuffleVT = MVT::v2f64;
21110       } else {
21111         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21112         // than the UNPCK variants.
21113         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21114         ShuffleVT = MVT::v4f32;
21115       }
21116       if (Depth == 1 && Root->getOpcode() == Shuffle)
21117         return false; // Nothing to do!
21118       Op = DAG.getBitcast(ShuffleVT, Input);
21119       DCI.AddToWorklist(Op.getNode());
21120       if (Shuffle == X86ISD::MOVDDUP)
21121         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21122       else
21123         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21124       DCI.AddToWorklist(Op.getNode());
21125       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21126                     /*AddTo*/ true);
21127       return true;
21128     }
21129     if (Subtarget->hasSSE3() &&
21130         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21131       bool Lo = Mask.equals({0, 0, 2, 2});
21132       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21133       MVT ShuffleVT = MVT::v4f32;
21134       if (Depth == 1 && Root->getOpcode() == Shuffle)
21135         return false; // Nothing to do!
21136       Op = DAG.getBitcast(ShuffleVT, Input);
21137       DCI.AddToWorklist(Op.getNode());
21138       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21139       DCI.AddToWorklist(Op.getNode());
21140       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21141                     /*AddTo*/ true);
21142       return true;
21143     }
21144     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21145       bool Lo = Mask.equals({0, 0, 1, 1});
21146       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21147       MVT ShuffleVT = MVT::v4f32;
21148       if (Depth == 1 && Root->getOpcode() == Shuffle)
21149         return false; // Nothing to do!
21150       Op = DAG.getBitcast(ShuffleVT, Input);
21151       DCI.AddToWorklist(Op.getNode());
21152       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21153       DCI.AddToWorklist(Op.getNode());
21154       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21155                     /*AddTo*/ true);
21156       return true;
21157     }
21158   }
21159
21160   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21161   // variants as none of these have single-instruction variants that are
21162   // superior to the UNPCK formulation.
21163   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21164       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21165        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21166        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21167        Mask.equals(
21168            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21169     bool Lo = Mask[0] == 0;
21170     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21171     if (Depth == 1 && Root->getOpcode() == Shuffle)
21172       return false; // Nothing to do!
21173     MVT ShuffleVT;
21174     switch (Mask.size()) {
21175     case 8:
21176       ShuffleVT = MVT::v8i16;
21177       break;
21178     case 16:
21179       ShuffleVT = MVT::v16i8;
21180       break;
21181     default:
21182       llvm_unreachable("Impossible mask size!");
21183     };
21184     Op = DAG.getBitcast(ShuffleVT, Input);
21185     DCI.AddToWorklist(Op.getNode());
21186     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21187     DCI.AddToWorklist(Op.getNode());
21188     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21189                   /*AddTo*/ true);
21190     return true;
21191   }
21192
21193   // Don't try to re-form single instruction chains under any circumstances now
21194   // that we've done encoding canonicalization for them.
21195   if (Depth < 2)
21196     return false;
21197
21198   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21199   // can replace them with a single PSHUFB instruction profitably. Intel's
21200   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21201   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21202   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21203     SmallVector<SDValue, 16> PSHUFBMask;
21204     int NumBytes = VT.getSizeInBits() / 8;
21205     int Ratio = NumBytes / Mask.size();
21206     for (int i = 0; i < NumBytes; ++i) {
21207       if (Mask[i / Ratio] == SM_SentinelUndef) {
21208         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21209         continue;
21210       }
21211       int M = Mask[i / Ratio] != SM_SentinelZero
21212                   ? Ratio * Mask[i / Ratio] + i % Ratio
21213                   : 255;
21214       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21215     }
21216     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21217     Op = DAG.getBitcast(ByteVT, Input);
21218     DCI.AddToWorklist(Op.getNode());
21219     SDValue PSHUFBMaskOp =
21220         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21221     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21222     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21223     DCI.AddToWorklist(Op.getNode());
21224     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21225                   /*AddTo*/ true);
21226     return true;
21227   }
21228
21229   // Failed to find any combines.
21230   return false;
21231 }
21232
21233 /// \brief Fully generic combining of x86 shuffle instructions.
21234 ///
21235 /// This should be the last combine run over the x86 shuffle instructions. Once
21236 /// they have been fully optimized, this will recursively consider all chains
21237 /// of single-use shuffle instructions, build a generic model of the cumulative
21238 /// shuffle operation, and check for simpler instructions which implement this
21239 /// operation. We use this primarily for two purposes:
21240 ///
21241 /// 1) Collapse generic shuffles to specialized single instructions when
21242 ///    equivalent. In most cases, this is just an encoding size win, but
21243 ///    sometimes we will collapse multiple generic shuffles into a single
21244 ///    special-purpose shuffle.
21245 /// 2) Look for sequences of shuffle instructions with 3 or more total
21246 ///    instructions, and replace them with the slightly more expensive SSSE3
21247 ///    PSHUFB instruction if available. We do this as the last combining step
21248 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21249 ///    a suitable short sequence of other instructions. The PHUFB will either
21250 ///    use a register or have to read from memory and so is slightly (but only
21251 ///    slightly) more expensive than the other shuffle instructions.
21252 ///
21253 /// Because this is inherently a quadratic operation (for each shuffle in
21254 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21255 /// This should never be an issue in practice as the shuffle lowering doesn't
21256 /// produce sequences of more than 8 instructions.
21257 ///
21258 /// FIXME: We will currently miss some cases where the redundant shuffling
21259 /// would simplify under the threshold for PSHUFB formation because of
21260 /// combine-ordering. To fix this, we should do the redundant instruction
21261 /// combining in this recursive walk.
21262 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21263                                           ArrayRef<int> RootMask,
21264                                           int Depth, bool HasPSHUFB,
21265                                           SelectionDAG &DAG,
21266                                           TargetLowering::DAGCombinerInfo &DCI,
21267                                           const X86Subtarget *Subtarget) {
21268   // Bound the depth of our recursive combine because this is ultimately
21269   // quadratic in nature.
21270   if (Depth > 8)
21271     return false;
21272
21273   // Directly rip through bitcasts to find the underlying operand.
21274   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21275     Op = Op.getOperand(0);
21276
21277   MVT VT = Op.getSimpleValueType();
21278   if (!VT.isVector())
21279     return false; // Bail if we hit a non-vector.
21280
21281   assert(Root.getSimpleValueType().isVector() &&
21282          "Shuffles operate on vector types!");
21283   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21284          "Can only combine shuffles of the same vector register size.");
21285
21286   if (!isTargetShuffle(Op.getOpcode()))
21287     return false;
21288   SmallVector<int, 16> OpMask;
21289   bool IsUnary;
21290   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21291   // We only can combine unary shuffles which we can decode the mask for.
21292   if (!HaveMask || !IsUnary)
21293     return false;
21294
21295   assert(VT.getVectorNumElements() == OpMask.size() &&
21296          "Different mask size from vector size!");
21297   assert(((RootMask.size() > OpMask.size() &&
21298            RootMask.size() % OpMask.size() == 0) ||
21299           (OpMask.size() > RootMask.size() &&
21300            OpMask.size() % RootMask.size() == 0) ||
21301           OpMask.size() == RootMask.size()) &&
21302          "The smaller number of elements must divide the larger.");
21303   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21304   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21305   assert(((RootRatio == 1 && OpRatio == 1) ||
21306           (RootRatio == 1) != (OpRatio == 1)) &&
21307          "Must not have a ratio for both incoming and op masks!");
21308
21309   SmallVector<int, 16> Mask;
21310   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21311
21312   // Merge this shuffle operation's mask into our accumulated mask. Note that
21313   // this shuffle's mask will be the first applied to the input, followed by the
21314   // root mask to get us all the way to the root value arrangement. The reason
21315   // for this order is that we are recursing up the operation chain.
21316   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21317     int RootIdx = i / RootRatio;
21318     if (RootMask[RootIdx] < 0) {
21319       // This is a zero or undef lane, we're done.
21320       Mask.push_back(RootMask[RootIdx]);
21321       continue;
21322     }
21323
21324     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21325     int OpIdx = RootMaskedIdx / OpRatio;
21326     if (OpMask[OpIdx] < 0) {
21327       // The incoming lanes are zero or undef, it doesn't matter which ones we
21328       // are using.
21329       Mask.push_back(OpMask[OpIdx]);
21330       continue;
21331     }
21332
21333     // Ok, we have non-zero lanes, map them through.
21334     Mask.push_back(OpMask[OpIdx] * OpRatio +
21335                    RootMaskedIdx % OpRatio);
21336   }
21337
21338   // See if we can recurse into the operand to combine more things.
21339   switch (Op.getOpcode()) {
21340     case X86ISD::PSHUFB:
21341       HasPSHUFB = true;
21342     case X86ISD::PSHUFD:
21343     case X86ISD::PSHUFHW:
21344     case X86ISD::PSHUFLW:
21345       if (Op.getOperand(0).hasOneUse() &&
21346           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21347                                         HasPSHUFB, DAG, DCI, Subtarget))
21348         return true;
21349       break;
21350
21351     case X86ISD::UNPCKL:
21352     case X86ISD::UNPCKH:
21353       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21354       // We can't check for single use, we have to check that this shuffle is the only user.
21355       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21356           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21357                                         HasPSHUFB, DAG, DCI, Subtarget))
21358           return true;
21359       break;
21360   }
21361
21362   // Minor canonicalization of the accumulated shuffle mask to make it easier
21363   // to match below. All this does is detect masks with squential pairs of
21364   // elements, and shrink them to the half-width mask. It does this in a loop
21365   // so it will reduce the size of the mask to the minimal width mask which
21366   // performs an equivalent shuffle.
21367   SmallVector<int, 16> WidenedMask;
21368   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21369     Mask = std::move(WidenedMask);
21370     WidenedMask.clear();
21371   }
21372
21373   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21374                                 Subtarget);
21375 }
21376
21377 /// \brief Get the PSHUF-style mask from PSHUF node.
21378 ///
21379 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21380 /// PSHUF-style masks that can be reused with such instructions.
21381 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21382   MVT VT = N.getSimpleValueType();
21383   SmallVector<int, 4> Mask;
21384   bool IsUnary;
21385   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21386   (void)HaveMask;
21387   assert(HaveMask);
21388
21389   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21390   // matter. Check that the upper masks are repeats and remove them.
21391   if (VT.getSizeInBits() > 128) {
21392     int LaneElts = 128 / VT.getScalarSizeInBits();
21393 #ifndef NDEBUG
21394     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21395       for (int j = 0; j < LaneElts; ++j)
21396         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21397                "Mask doesn't repeat in high 128-bit lanes!");
21398 #endif
21399     Mask.resize(LaneElts);
21400   }
21401
21402   switch (N.getOpcode()) {
21403   case X86ISD::PSHUFD:
21404     return Mask;
21405   case X86ISD::PSHUFLW:
21406     Mask.resize(4);
21407     return Mask;
21408   case X86ISD::PSHUFHW:
21409     Mask.erase(Mask.begin(), Mask.begin() + 4);
21410     for (int &M : Mask)
21411       M -= 4;
21412     return Mask;
21413   default:
21414     llvm_unreachable("No valid shuffle instruction found!");
21415   }
21416 }
21417
21418 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21419 ///
21420 /// We walk up the chain and look for a combinable shuffle, skipping over
21421 /// shuffles that we could hoist this shuffle's transformation past without
21422 /// altering anything.
21423 static SDValue
21424 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21425                              SelectionDAG &DAG,
21426                              TargetLowering::DAGCombinerInfo &DCI) {
21427   assert(N.getOpcode() == X86ISD::PSHUFD &&
21428          "Called with something other than an x86 128-bit half shuffle!");
21429   SDLoc DL(N);
21430
21431   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21432   // of the shuffles in the chain so that we can form a fresh chain to replace
21433   // this one.
21434   SmallVector<SDValue, 8> Chain;
21435   SDValue V = N.getOperand(0);
21436   for (; V.hasOneUse(); V = V.getOperand(0)) {
21437     switch (V.getOpcode()) {
21438     default:
21439       return SDValue(); // Nothing combined!
21440
21441     case ISD::BITCAST:
21442       // Skip bitcasts as we always know the type for the target specific
21443       // instructions.
21444       continue;
21445
21446     case X86ISD::PSHUFD:
21447       // Found another dword shuffle.
21448       break;
21449
21450     case X86ISD::PSHUFLW:
21451       // Check that the low words (being shuffled) are the identity in the
21452       // dword shuffle, and the high words are self-contained.
21453       if (Mask[0] != 0 || Mask[1] != 1 ||
21454           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21455         return SDValue();
21456
21457       Chain.push_back(V);
21458       continue;
21459
21460     case X86ISD::PSHUFHW:
21461       // Check that the high words (being shuffled) are the identity in the
21462       // dword shuffle, and the low words are self-contained.
21463       if (Mask[2] != 2 || Mask[3] != 3 ||
21464           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21465         return SDValue();
21466
21467       Chain.push_back(V);
21468       continue;
21469
21470     case X86ISD::UNPCKL:
21471     case X86ISD::UNPCKH:
21472       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21473       // shuffle into a preceding word shuffle.
21474       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21475           V.getSimpleValueType().getScalarType() != MVT::i16)
21476         return SDValue();
21477
21478       // Search for a half-shuffle which we can combine with.
21479       unsigned CombineOp =
21480           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21481       if (V.getOperand(0) != V.getOperand(1) ||
21482           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21483         return SDValue();
21484       Chain.push_back(V);
21485       V = V.getOperand(0);
21486       do {
21487         switch (V.getOpcode()) {
21488         default:
21489           return SDValue(); // Nothing to combine.
21490
21491         case X86ISD::PSHUFLW:
21492         case X86ISD::PSHUFHW:
21493           if (V.getOpcode() == CombineOp)
21494             break;
21495
21496           Chain.push_back(V);
21497
21498           // Fallthrough!
21499         case ISD::BITCAST:
21500           V = V.getOperand(0);
21501           continue;
21502         }
21503         break;
21504       } while (V.hasOneUse());
21505       break;
21506     }
21507     // Break out of the loop if we break out of the switch.
21508     break;
21509   }
21510
21511   if (!V.hasOneUse())
21512     // We fell out of the loop without finding a viable combining instruction.
21513     return SDValue();
21514
21515   // Merge this node's mask and our incoming mask.
21516   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21517   for (int &M : Mask)
21518     M = VMask[M];
21519   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21520                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21521
21522   // Rebuild the chain around this new shuffle.
21523   while (!Chain.empty()) {
21524     SDValue W = Chain.pop_back_val();
21525
21526     if (V.getValueType() != W.getOperand(0).getValueType())
21527       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21528
21529     switch (W.getOpcode()) {
21530     default:
21531       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21532
21533     case X86ISD::UNPCKL:
21534     case X86ISD::UNPCKH:
21535       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21536       break;
21537
21538     case X86ISD::PSHUFD:
21539     case X86ISD::PSHUFLW:
21540     case X86ISD::PSHUFHW:
21541       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21542       break;
21543     }
21544   }
21545   if (V.getValueType() != N.getValueType())
21546     V = DAG.getBitcast(N.getValueType(), V);
21547
21548   // Return the new chain to replace N.
21549   return V;
21550 }
21551
21552 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21553 ///
21554 /// We walk up the chain, skipping shuffles of the other half and looking
21555 /// through shuffles which switch halves trying to find a shuffle of the same
21556 /// pair of dwords.
21557 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21558                                         SelectionDAG &DAG,
21559                                         TargetLowering::DAGCombinerInfo &DCI) {
21560   assert(
21561       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21562       "Called with something other than an x86 128-bit half shuffle!");
21563   SDLoc DL(N);
21564   unsigned CombineOpcode = N.getOpcode();
21565
21566   // Walk up a single-use chain looking for a combinable shuffle.
21567   SDValue V = N.getOperand(0);
21568   for (; V.hasOneUse(); V = V.getOperand(0)) {
21569     switch (V.getOpcode()) {
21570     default:
21571       return false; // Nothing combined!
21572
21573     case ISD::BITCAST:
21574       // Skip bitcasts as we always know the type for the target specific
21575       // instructions.
21576       continue;
21577
21578     case X86ISD::PSHUFLW:
21579     case X86ISD::PSHUFHW:
21580       if (V.getOpcode() == CombineOpcode)
21581         break;
21582
21583       // Other-half shuffles are no-ops.
21584       continue;
21585     }
21586     // Break out of the loop if we break out of the switch.
21587     break;
21588   }
21589
21590   if (!V.hasOneUse())
21591     // We fell out of the loop without finding a viable combining instruction.
21592     return false;
21593
21594   // Combine away the bottom node as its shuffle will be accumulated into
21595   // a preceding shuffle.
21596   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21597
21598   // Record the old value.
21599   SDValue Old = V;
21600
21601   // Merge this node's mask and our incoming mask (adjusted to account for all
21602   // the pshufd instructions encountered).
21603   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21604   for (int &M : Mask)
21605     M = VMask[M];
21606   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21607                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21608
21609   // Check that the shuffles didn't cancel each other out. If not, we need to
21610   // combine to the new one.
21611   if (Old != V)
21612     // Replace the combinable shuffle with the combined one, updating all users
21613     // so that we re-evaluate the chain here.
21614     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21615
21616   return true;
21617 }
21618
21619 /// \brief Try to combine x86 target specific shuffles.
21620 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21621                                            TargetLowering::DAGCombinerInfo &DCI,
21622                                            const X86Subtarget *Subtarget) {
21623   SDLoc DL(N);
21624   MVT VT = N.getSimpleValueType();
21625   SmallVector<int, 4> Mask;
21626
21627   switch (N.getOpcode()) {
21628   case X86ISD::PSHUFD:
21629   case X86ISD::PSHUFLW:
21630   case X86ISD::PSHUFHW:
21631     Mask = getPSHUFShuffleMask(N);
21632     assert(Mask.size() == 4);
21633     break;
21634   default:
21635     return SDValue();
21636   }
21637
21638   // Nuke no-op shuffles that show up after combining.
21639   if (isNoopShuffleMask(Mask))
21640     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21641
21642   // Look for simplifications involving one or two shuffle instructions.
21643   SDValue V = N.getOperand(0);
21644   switch (N.getOpcode()) {
21645   default:
21646     break;
21647   case X86ISD::PSHUFLW:
21648   case X86ISD::PSHUFHW:
21649     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21650
21651     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21652       return SDValue(); // We combined away this shuffle, so we're done.
21653
21654     // See if this reduces to a PSHUFD which is no more expensive and can
21655     // combine with more operations. Note that it has to at least flip the
21656     // dwords as otherwise it would have been removed as a no-op.
21657     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21658       int DMask[] = {0, 1, 2, 3};
21659       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21660       DMask[DOffset + 0] = DOffset + 1;
21661       DMask[DOffset + 1] = DOffset + 0;
21662       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21663       V = DAG.getBitcast(DVT, V);
21664       DCI.AddToWorklist(V.getNode());
21665       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21666                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21667       DCI.AddToWorklist(V.getNode());
21668       return DAG.getBitcast(VT, V);
21669     }
21670
21671     // Look for shuffle patterns which can be implemented as a single unpack.
21672     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21673     // only works when we have a PSHUFD followed by two half-shuffles.
21674     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21675         (V.getOpcode() == X86ISD::PSHUFLW ||
21676          V.getOpcode() == X86ISD::PSHUFHW) &&
21677         V.getOpcode() != N.getOpcode() &&
21678         V.hasOneUse()) {
21679       SDValue D = V.getOperand(0);
21680       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21681         D = D.getOperand(0);
21682       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21683         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21684         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21685         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21686         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21687         int WordMask[8];
21688         for (int i = 0; i < 4; ++i) {
21689           WordMask[i + NOffset] = Mask[i] + NOffset;
21690           WordMask[i + VOffset] = VMask[i] + VOffset;
21691         }
21692         // Map the word mask through the DWord mask.
21693         int MappedMask[8];
21694         for (int i = 0; i < 8; ++i)
21695           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21696         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21697             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21698           // We can replace all three shuffles with an unpack.
21699           V = DAG.getBitcast(VT, D.getOperand(0));
21700           DCI.AddToWorklist(V.getNode());
21701           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21702                                                 : X86ISD::UNPCKH,
21703                              DL, VT, V, V);
21704         }
21705       }
21706     }
21707
21708     break;
21709
21710   case X86ISD::PSHUFD:
21711     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21712       return NewN;
21713
21714     break;
21715   }
21716
21717   return SDValue();
21718 }
21719
21720 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21721 ///
21722 /// We combine this directly on the abstract vector shuffle nodes so it is
21723 /// easier to generically match. We also insert dummy vector shuffle nodes for
21724 /// the operands which explicitly discard the lanes which are unused by this
21725 /// operation to try to flow through the rest of the combiner the fact that
21726 /// they're unused.
21727 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21728   SDLoc DL(N);
21729   EVT VT = N->getValueType(0);
21730
21731   // We only handle target-independent shuffles.
21732   // FIXME: It would be easy and harmless to use the target shuffle mask
21733   // extraction tool to support more.
21734   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21735     return SDValue();
21736
21737   auto *SVN = cast<ShuffleVectorSDNode>(N);
21738   ArrayRef<int> Mask = SVN->getMask();
21739   SDValue V1 = N->getOperand(0);
21740   SDValue V2 = N->getOperand(1);
21741
21742   // We require the first shuffle operand to be the SUB node, and the second to
21743   // be the ADD node.
21744   // FIXME: We should support the commuted patterns.
21745   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21746     return SDValue();
21747
21748   // If there are other uses of these operations we can't fold them.
21749   if (!V1->hasOneUse() || !V2->hasOneUse())
21750     return SDValue();
21751
21752   // Ensure that both operations have the same operands. Note that we can
21753   // commute the FADD operands.
21754   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21755   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21756       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21757     return SDValue();
21758
21759   // We're looking for blends between FADD and FSUB nodes. We insist on these
21760   // nodes being lined up in a specific expected pattern.
21761   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21762         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21763         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21764     return SDValue();
21765
21766   // Only specific types are legal at this point, assert so we notice if and
21767   // when these change.
21768   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21769           VT == MVT::v4f64) &&
21770          "Unknown vector type encountered!");
21771
21772   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21773 }
21774
21775 /// PerformShuffleCombine - Performs several different shuffle combines.
21776 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21777                                      TargetLowering::DAGCombinerInfo &DCI,
21778                                      const X86Subtarget *Subtarget) {
21779   SDLoc dl(N);
21780   SDValue N0 = N->getOperand(0);
21781   SDValue N1 = N->getOperand(1);
21782   EVT VT = N->getValueType(0);
21783
21784   // Don't create instructions with illegal types after legalize types has run.
21785   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21786   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21787     return SDValue();
21788
21789   // If we have legalized the vector types, look for blends of FADD and FSUB
21790   // nodes that we can fuse into an ADDSUB node.
21791   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21792     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21793       return AddSub;
21794
21795   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21796   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21797       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21798     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21799
21800   // During Type Legalization, when promoting illegal vector types,
21801   // the backend might introduce new shuffle dag nodes and bitcasts.
21802   //
21803   // This code performs the following transformation:
21804   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21805   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21806   //
21807   // We do this only if both the bitcast and the BINOP dag nodes have
21808   // one use. Also, perform this transformation only if the new binary
21809   // operation is legal. This is to avoid introducing dag nodes that
21810   // potentially need to be further expanded (or custom lowered) into a
21811   // less optimal sequence of dag nodes.
21812   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21813       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21814       N0.getOpcode() == ISD::BITCAST) {
21815     SDValue BC0 = N0.getOperand(0);
21816     EVT SVT = BC0.getValueType();
21817     unsigned Opcode = BC0.getOpcode();
21818     unsigned NumElts = VT.getVectorNumElements();
21819
21820     if (BC0.hasOneUse() && SVT.isVector() &&
21821         SVT.getVectorNumElements() * 2 == NumElts &&
21822         TLI.isOperationLegal(Opcode, VT)) {
21823       bool CanFold = false;
21824       switch (Opcode) {
21825       default : break;
21826       case ISD::ADD :
21827       case ISD::FADD :
21828       case ISD::SUB :
21829       case ISD::FSUB :
21830       case ISD::MUL :
21831       case ISD::FMUL :
21832         CanFold = true;
21833       }
21834
21835       unsigned SVTNumElts = SVT.getVectorNumElements();
21836       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21837       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21838         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21839       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21840         CanFold = SVOp->getMaskElt(i) < 0;
21841
21842       if (CanFold) {
21843         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21844         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21845         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21846         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21847       }
21848     }
21849   }
21850
21851   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21852   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21853   // consecutive, non-overlapping, and in the right order.
21854   SmallVector<SDValue, 16> Elts;
21855   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21856     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21857
21858   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21859     return LD;
21860
21861   if (isTargetShuffle(N->getOpcode())) {
21862     SDValue Shuffle =
21863         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21864     if (Shuffle.getNode())
21865       return Shuffle;
21866
21867     // Try recursively combining arbitrary sequences of x86 shuffle
21868     // instructions into higher-order shuffles. We do this after combining
21869     // specific PSHUF instruction sequences into their minimal form so that we
21870     // can evaluate how many specialized shuffle instructions are involved in
21871     // a particular chain.
21872     SmallVector<int, 1> NonceMask; // Just a placeholder.
21873     NonceMask.push_back(0);
21874     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21875                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21876                                       DCI, Subtarget))
21877       return SDValue(); // This routine will use CombineTo to replace N.
21878   }
21879
21880   return SDValue();
21881 }
21882
21883 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21884 /// specific shuffle of a load can be folded into a single element load.
21885 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21886 /// shuffles have been custom lowered so we need to handle those here.
21887 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21888                                          TargetLowering::DAGCombinerInfo &DCI) {
21889   if (DCI.isBeforeLegalizeOps())
21890     return SDValue();
21891
21892   SDValue InVec = N->getOperand(0);
21893   SDValue EltNo = N->getOperand(1);
21894
21895   if (!isa<ConstantSDNode>(EltNo))
21896     return SDValue();
21897
21898   EVT OriginalVT = InVec.getValueType();
21899
21900   if (InVec.getOpcode() == ISD::BITCAST) {
21901     // Don't duplicate a load with other uses.
21902     if (!InVec.hasOneUse())
21903       return SDValue();
21904     EVT BCVT = InVec.getOperand(0).getValueType();
21905     if (!BCVT.isVector() ||
21906         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21907       return SDValue();
21908     InVec = InVec.getOperand(0);
21909   }
21910
21911   EVT CurrentVT = InVec.getValueType();
21912
21913   if (!isTargetShuffle(InVec.getOpcode()))
21914     return SDValue();
21915
21916   // Don't duplicate a load with other uses.
21917   if (!InVec.hasOneUse())
21918     return SDValue();
21919
21920   SmallVector<int, 16> ShuffleMask;
21921   bool UnaryShuffle;
21922   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21923                             ShuffleMask, UnaryShuffle))
21924     return SDValue();
21925
21926   // Select the input vector, guarding against out of range extract vector.
21927   unsigned NumElems = CurrentVT.getVectorNumElements();
21928   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21929   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21930   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21931                                          : InVec.getOperand(1);
21932
21933   // If inputs to shuffle are the same for both ops, then allow 2 uses
21934   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21935                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21936
21937   if (LdNode.getOpcode() == ISD::BITCAST) {
21938     // Don't duplicate a load with other uses.
21939     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21940       return SDValue();
21941
21942     AllowedUses = 1; // only allow 1 load use if we have a bitcast
21943     LdNode = LdNode.getOperand(0);
21944   }
21945
21946   if (!ISD::isNormalLoad(LdNode.getNode()))
21947     return SDValue();
21948
21949   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21950
21951   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21952     return SDValue();
21953
21954   EVT EltVT = N->getValueType(0);
21955   // If there's a bitcast before the shuffle, check if the load type and
21956   // alignment is valid.
21957   unsigned Align = LN0->getAlignment();
21958   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21959   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
21960       EltVT.getTypeForEVT(*DAG.getContext()));
21961
21962   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21963     return SDValue();
21964
21965   // All checks match so transform back to vector_shuffle so that DAG combiner
21966   // can finish the job
21967   SDLoc dl(N);
21968
21969   // Create shuffle node taking into account the case that its a unary shuffle
21970   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21971                                    : InVec.getOperand(1);
21972   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21973                                  InVec.getOperand(0), Shuffle,
21974                                  &ShuffleMask[0]);
21975   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21976   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21977                      EltNo);
21978 }
21979
21980 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21981 /// special and don't usually play with other vector types, it's better to
21982 /// handle them early to be sure we emit efficient code by avoiding
21983 /// store-load conversions.
21984 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21985   if (N->getValueType(0) != MVT::x86mmx ||
21986       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21987       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21988     return SDValue();
21989
21990   SDValue V = N->getOperand(0);
21991   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21992   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21993     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21994                        N->getValueType(0), V.getOperand(0));
21995
21996   return SDValue();
21997 }
21998
21999 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22000 /// generation and convert it from being a bunch of shuffles and extracts
22001 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22002 /// storing the value and loading scalars back, while for x64 we should
22003 /// use 64-bit extracts and shifts.
22004 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22005                                          TargetLowering::DAGCombinerInfo &DCI) {
22006   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22007     return NewOp;
22008
22009   SDValue InputVector = N->getOperand(0);
22010   SDLoc dl(InputVector);
22011   // Detect mmx to i32 conversion through a v2i32 elt extract.
22012   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22013       N->getValueType(0) == MVT::i32 &&
22014       InputVector.getValueType() == MVT::v2i32) {
22015
22016     // The bitcast source is a direct mmx result.
22017     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22018     if (MMXSrc.getValueType() == MVT::x86mmx)
22019       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22020                          N->getValueType(0),
22021                          InputVector.getNode()->getOperand(0));
22022
22023     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22024     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22025     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22026         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22027         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22028         MMXSrcOp.getValueType() == MVT::v1i64 &&
22029         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22030       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22031                          N->getValueType(0),
22032                          MMXSrcOp.getOperand(0));
22033   }
22034
22035   EVT VT = N->getValueType(0);
22036
22037   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22038       InputVector.getOpcode() == ISD::BITCAST &&
22039       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22040     uint64_t ExtractedElt =
22041           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22042     uint64_t InputValue =
22043           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22044     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22045     return DAG.getConstant(Res, dl, MVT::i1);
22046   }
22047   // Only operate on vectors of 4 elements, where the alternative shuffling
22048   // gets to be more expensive.
22049   if (InputVector.getValueType() != MVT::v4i32)
22050     return SDValue();
22051
22052   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22053   // single use which is a sign-extend or zero-extend, and all elements are
22054   // used.
22055   SmallVector<SDNode *, 4> Uses;
22056   unsigned ExtractedElements = 0;
22057   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22058        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22059     if (UI.getUse().getResNo() != InputVector.getResNo())
22060       return SDValue();
22061
22062     SDNode *Extract = *UI;
22063     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22064       return SDValue();
22065
22066     if (Extract->getValueType(0) != MVT::i32)
22067       return SDValue();
22068     if (!Extract->hasOneUse())
22069       return SDValue();
22070     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22071         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22072       return SDValue();
22073     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22074       return SDValue();
22075
22076     // Record which element was extracted.
22077     ExtractedElements |=
22078       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22079
22080     Uses.push_back(Extract);
22081   }
22082
22083   // If not all the elements were used, this may not be worthwhile.
22084   if (ExtractedElements != 15)
22085     return SDValue();
22086
22087   // Ok, we've now decided to do the transformation.
22088   // If 64-bit shifts are legal, use the extract-shift sequence,
22089   // otherwise bounce the vector off the cache.
22090   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22091   SDValue Vals[4];
22092
22093   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22094     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22095     auto &DL = DAG.getDataLayout();
22096     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22097     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22098       DAG.getConstant(0, dl, VecIdxTy));
22099     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22100       DAG.getConstant(1, dl, VecIdxTy));
22101
22102     SDValue ShAmt = DAG.getConstant(
22103         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22104     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22105     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22106       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22107     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22108     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22109       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22110   } else {
22111     // Store the value to a temporary stack slot.
22112     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22113     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22114       MachinePointerInfo(), false, false, 0);
22115
22116     EVT ElementType = InputVector.getValueType().getVectorElementType();
22117     unsigned EltSize = ElementType.getSizeInBits() / 8;
22118
22119     // Replace each use (extract) with a load of the appropriate element.
22120     for (unsigned i = 0; i < 4; ++i) {
22121       uint64_t Offset = EltSize * i;
22122       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22123       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22124
22125       SDValue ScalarAddr =
22126           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22127
22128       // Load the scalar.
22129       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22130                             ScalarAddr, MachinePointerInfo(),
22131                             false, false, false, 0);
22132
22133     }
22134   }
22135
22136   // Replace the extracts
22137   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22138     UE = Uses.end(); UI != UE; ++UI) {
22139     SDNode *Extract = *UI;
22140
22141     SDValue Idx = Extract->getOperand(1);
22142     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22143     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22144   }
22145
22146   // The replacement was made in place; don't return anything.
22147   return SDValue();
22148 }
22149
22150 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22151 static std::pair<unsigned, bool>
22152 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22153                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22154   if (!VT.isVector())
22155     return std::make_pair(0, false);
22156
22157   bool NeedSplit = false;
22158   switch (VT.getSimpleVT().SimpleTy) {
22159   default: return std::make_pair(0, false);
22160   case MVT::v4i64:
22161   case MVT::v2i64:
22162     if (!Subtarget->hasVLX())
22163       return std::make_pair(0, false);
22164     break;
22165   case MVT::v64i8:
22166   case MVT::v32i16:
22167     if (!Subtarget->hasBWI())
22168       return std::make_pair(0, false);
22169     break;
22170   case MVT::v16i32:
22171   case MVT::v8i64:
22172     if (!Subtarget->hasAVX512())
22173       return std::make_pair(0, false);
22174     break;
22175   case MVT::v32i8:
22176   case MVT::v16i16:
22177   case MVT::v8i32:
22178     if (!Subtarget->hasAVX2())
22179       NeedSplit = true;
22180     if (!Subtarget->hasAVX())
22181       return std::make_pair(0, false);
22182     break;
22183   case MVT::v16i8:
22184   case MVT::v8i16:
22185   case MVT::v4i32:
22186     if (!Subtarget->hasSSE2())
22187       return std::make_pair(0, false);
22188   }
22189
22190   // SSE2 has only a small subset of the operations.
22191   bool hasUnsigned = Subtarget->hasSSE41() ||
22192                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22193   bool hasSigned = Subtarget->hasSSE41() ||
22194                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22195
22196   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22197
22198   unsigned Opc = 0;
22199   // Check for x CC y ? x : y.
22200   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22201       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22202     switch (CC) {
22203     default: break;
22204     case ISD::SETULT:
22205     case ISD::SETULE:
22206       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22207     case ISD::SETUGT:
22208     case ISD::SETUGE:
22209       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22210     case ISD::SETLT:
22211     case ISD::SETLE:
22212       Opc = hasSigned ? ISD::SMIN : 0; break;
22213     case ISD::SETGT:
22214     case ISD::SETGE:
22215       Opc = hasSigned ? ISD::SMAX : 0; break;
22216     }
22217   // Check for x CC y ? y : x -- a min/max with reversed arms.
22218   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22219              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22220     switch (CC) {
22221     default: break;
22222     case ISD::SETULT:
22223     case ISD::SETULE:
22224       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22225     case ISD::SETUGT:
22226     case ISD::SETUGE:
22227       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22228     case ISD::SETLT:
22229     case ISD::SETLE:
22230       Opc = hasSigned ? ISD::SMAX : 0; break;
22231     case ISD::SETGT:
22232     case ISD::SETGE:
22233       Opc = hasSigned ? ISD::SMIN : 0; break;
22234     }
22235   }
22236
22237   return std::make_pair(Opc, NeedSplit);
22238 }
22239
22240 static SDValue
22241 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22242                                       const X86Subtarget *Subtarget) {
22243   SDLoc dl(N);
22244   SDValue Cond = N->getOperand(0);
22245   SDValue LHS = N->getOperand(1);
22246   SDValue RHS = N->getOperand(2);
22247
22248   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22249     SDValue CondSrc = Cond->getOperand(0);
22250     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22251       Cond = CondSrc->getOperand(0);
22252   }
22253
22254   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22255     return SDValue();
22256
22257   // A vselect where all conditions and data are constants can be optimized into
22258   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22259   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22260       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22261     return SDValue();
22262
22263   unsigned MaskValue = 0;
22264   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22265     return SDValue();
22266
22267   MVT VT = N->getSimpleValueType(0);
22268   unsigned NumElems = VT.getVectorNumElements();
22269   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22270   for (unsigned i = 0; i < NumElems; ++i) {
22271     // Be sure we emit undef where we can.
22272     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22273       ShuffleMask[i] = -1;
22274     else
22275       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22276   }
22277
22278   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22279   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22280     return SDValue();
22281   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22282 }
22283
22284 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22285 /// nodes.
22286 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22287                                     TargetLowering::DAGCombinerInfo &DCI,
22288                                     const X86Subtarget *Subtarget) {
22289   SDLoc DL(N);
22290   SDValue Cond = N->getOperand(0);
22291   // Get the LHS/RHS of the select.
22292   SDValue LHS = N->getOperand(1);
22293   SDValue RHS = N->getOperand(2);
22294   EVT VT = LHS.getValueType();
22295   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22296
22297   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22298   // instructions match the semantics of the common C idiom x<y?x:y but not
22299   // x<=y?x:y, because of how they handle negative zero (which can be
22300   // ignored in unsafe-math mode).
22301   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22302   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22303       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22304       (Subtarget->hasSSE2() ||
22305        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22306     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22307
22308     unsigned Opcode = 0;
22309     // Check for x CC y ? x : y.
22310     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22311         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22312       switch (CC) {
22313       default: break;
22314       case ISD::SETULT:
22315         // Converting this to a min would handle NaNs incorrectly, and swapping
22316         // the operands would cause it to handle comparisons between positive
22317         // and negative zero incorrectly.
22318         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22319           if (!DAG.getTarget().Options.UnsafeFPMath &&
22320               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22321             break;
22322           std::swap(LHS, RHS);
22323         }
22324         Opcode = X86ISD::FMIN;
22325         break;
22326       case ISD::SETOLE:
22327         // Converting this to a min would handle comparisons between positive
22328         // and negative zero incorrectly.
22329         if (!DAG.getTarget().Options.UnsafeFPMath &&
22330             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22331           break;
22332         Opcode = X86ISD::FMIN;
22333         break;
22334       case ISD::SETULE:
22335         // Converting this to a min would handle both negative zeros and NaNs
22336         // incorrectly, but we can swap the operands to fix both.
22337         std::swap(LHS, RHS);
22338       case ISD::SETOLT:
22339       case ISD::SETLT:
22340       case ISD::SETLE:
22341         Opcode = X86ISD::FMIN;
22342         break;
22343
22344       case ISD::SETOGE:
22345         // Converting this to a max would handle comparisons between positive
22346         // and negative zero incorrectly.
22347         if (!DAG.getTarget().Options.UnsafeFPMath &&
22348             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22349           break;
22350         Opcode = X86ISD::FMAX;
22351         break;
22352       case ISD::SETUGT:
22353         // Converting this to a max would handle NaNs incorrectly, and swapping
22354         // the operands would cause it to handle comparisons between positive
22355         // and negative zero incorrectly.
22356         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22357           if (!DAG.getTarget().Options.UnsafeFPMath &&
22358               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22359             break;
22360           std::swap(LHS, RHS);
22361         }
22362         Opcode = X86ISD::FMAX;
22363         break;
22364       case ISD::SETUGE:
22365         // Converting this to a max would handle both negative zeros and NaNs
22366         // incorrectly, but we can swap the operands to fix both.
22367         std::swap(LHS, RHS);
22368       case ISD::SETOGT:
22369       case ISD::SETGT:
22370       case ISD::SETGE:
22371         Opcode = X86ISD::FMAX;
22372         break;
22373       }
22374     // Check for x CC y ? y : x -- a min/max with reversed arms.
22375     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22376                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22377       switch (CC) {
22378       default: break;
22379       case ISD::SETOGE:
22380         // Converting this to a min would handle comparisons between positive
22381         // and negative zero incorrectly, and swapping the operands would
22382         // cause it to handle NaNs incorrectly.
22383         if (!DAG.getTarget().Options.UnsafeFPMath &&
22384             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22385           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22386             break;
22387           std::swap(LHS, RHS);
22388         }
22389         Opcode = X86ISD::FMIN;
22390         break;
22391       case ISD::SETUGT:
22392         // Converting this to a min would handle NaNs incorrectly.
22393         if (!DAG.getTarget().Options.UnsafeFPMath &&
22394             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22395           break;
22396         Opcode = X86ISD::FMIN;
22397         break;
22398       case ISD::SETUGE:
22399         // Converting this to a min would handle both negative zeros and NaNs
22400         // incorrectly, but we can swap the operands to fix both.
22401         std::swap(LHS, RHS);
22402       case ISD::SETOGT:
22403       case ISD::SETGT:
22404       case ISD::SETGE:
22405         Opcode = X86ISD::FMIN;
22406         break;
22407
22408       case ISD::SETULT:
22409         // Converting this to a max would handle NaNs incorrectly.
22410         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22411           break;
22412         Opcode = X86ISD::FMAX;
22413         break;
22414       case ISD::SETOLE:
22415         // Converting this to a max would handle comparisons between positive
22416         // and negative zero incorrectly, and swapping the operands would
22417         // cause it to handle NaNs incorrectly.
22418         if (!DAG.getTarget().Options.UnsafeFPMath &&
22419             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22420           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22421             break;
22422           std::swap(LHS, RHS);
22423         }
22424         Opcode = X86ISD::FMAX;
22425         break;
22426       case ISD::SETULE:
22427         // Converting this to a max would handle both negative zeros and NaNs
22428         // incorrectly, but we can swap the operands to fix both.
22429         std::swap(LHS, RHS);
22430       case ISD::SETOLT:
22431       case ISD::SETLT:
22432       case ISD::SETLE:
22433         Opcode = X86ISD::FMAX;
22434         break;
22435       }
22436     }
22437
22438     if (Opcode)
22439       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22440   }
22441
22442   EVT CondVT = Cond.getValueType();
22443   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22444       CondVT.getVectorElementType() == MVT::i1) {
22445     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22446     // lowering on KNL. In this case we convert it to
22447     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22448     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22449     // Since SKX these selects have a proper lowering.
22450     EVT OpVT = LHS.getValueType();
22451     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22452         (OpVT.getVectorElementType() == MVT::i8 ||
22453          OpVT.getVectorElementType() == MVT::i16) &&
22454         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22455       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22456       DCI.AddToWorklist(Cond.getNode());
22457       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22458     }
22459   }
22460   // If this is a select between two integer constants, try to do some
22461   // optimizations.
22462   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22463     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22464       // Don't do this for crazy integer types.
22465       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22466         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22467         // so that TrueC (the true value) is larger than FalseC.
22468         bool NeedsCondInvert = false;
22469
22470         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22471             // Efficiently invertible.
22472             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22473              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22474               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22475           NeedsCondInvert = true;
22476           std::swap(TrueC, FalseC);
22477         }
22478
22479         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22480         if (FalseC->getAPIntValue() == 0 &&
22481             TrueC->getAPIntValue().isPowerOf2()) {
22482           if (NeedsCondInvert) // Invert the condition if needed.
22483             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22484                                DAG.getConstant(1, DL, Cond.getValueType()));
22485
22486           // Zero extend the condition if needed.
22487           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22488
22489           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22490           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22491                              DAG.getConstant(ShAmt, DL, MVT::i8));
22492         }
22493
22494         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22495         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22496           if (NeedsCondInvert) // Invert the condition if needed.
22497             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22498                                DAG.getConstant(1, DL, Cond.getValueType()));
22499
22500           // Zero extend the condition if needed.
22501           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22502                              FalseC->getValueType(0), Cond);
22503           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22504                              SDValue(FalseC, 0));
22505         }
22506
22507         // Optimize cases that will turn into an LEA instruction.  This requires
22508         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22509         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22510           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22511           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22512
22513           bool isFastMultiplier = false;
22514           if (Diff < 10) {
22515             switch ((unsigned char)Diff) {
22516               default: break;
22517               case 1:  // result = add base, cond
22518               case 2:  // result = lea base(    , cond*2)
22519               case 3:  // result = lea base(cond, cond*2)
22520               case 4:  // result = lea base(    , cond*4)
22521               case 5:  // result = lea base(cond, cond*4)
22522               case 8:  // result = lea base(    , cond*8)
22523               case 9:  // result = lea base(cond, cond*8)
22524                 isFastMultiplier = true;
22525                 break;
22526             }
22527           }
22528
22529           if (isFastMultiplier) {
22530             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22531             if (NeedsCondInvert) // Invert the condition if needed.
22532               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22533                                  DAG.getConstant(1, DL, Cond.getValueType()));
22534
22535             // Zero extend the condition if needed.
22536             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22537                                Cond);
22538             // Scale the condition by the difference.
22539             if (Diff != 1)
22540               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22541                                  DAG.getConstant(Diff, DL,
22542                                                  Cond.getValueType()));
22543
22544             // Add the base if non-zero.
22545             if (FalseC->getAPIntValue() != 0)
22546               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22547                                  SDValue(FalseC, 0));
22548             return Cond;
22549           }
22550         }
22551       }
22552   }
22553
22554   // Canonicalize max and min:
22555   // (x > y) ? x : y -> (x >= y) ? x : y
22556   // (x < y) ? x : y -> (x <= y) ? x : y
22557   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22558   // the need for an extra compare
22559   // against zero. e.g.
22560   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22561   // subl   %esi, %edi
22562   // testl  %edi, %edi
22563   // movl   $0, %eax
22564   // cmovgl %edi, %eax
22565   // =>
22566   // xorl   %eax, %eax
22567   // subl   %esi, $edi
22568   // cmovsl %eax, %edi
22569   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22570       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22571       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22572     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22573     switch (CC) {
22574     default: break;
22575     case ISD::SETLT:
22576     case ISD::SETGT: {
22577       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22578       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22579                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22580       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22581     }
22582     }
22583   }
22584
22585   // Early exit check
22586   if (!TLI.isTypeLegal(VT))
22587     return SDValue();
22588
22589   // Match VSELECTs into subs with unsigned saturation.
22590   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22591       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22592       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22593        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22594     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22595
22596     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22597     // left side invert the predicate to simplify logic below.
22598     SDValue Other;
22599     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22600       Other = RHS;
22601       CC = ISD::getSetCCInverse(CC, true);
22602     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22603       Other = LHS;
22604     }
22605
22606     if (Other.getNode() && Other->getNumOperands() == 2 &&
22607         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22608       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22609       SDValue CondRHS = Cond->getOperand(1);
22610
22611       // Look for a general sub with unsigned saturation first.
22612       // x >= y ? x-y : 0 --> subus x, y
22613       // x >  y ? x-y : 0 --> subus x, y
22614       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22615           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22616         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22617
22618       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22619         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22620           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22621             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22622               // If the RHS is a constant we have to reverse the const
22623               // canonicalization.
22624               // x > C-1 ? x+-C : 0 --> subus x, C
22625               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22626                   CondRHSConst->getAPIntValue() ==
22627                       (-OpRHSConst->getAPIntValue() - 1))
22628                 return DAG.getNode(
22629                     X86ISD::SUBUS, DL, VT, OpLHS,
22630                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22631
22632           // Another special case: If C was a sign bit, the sub has been
22633           // canonicalized into a xor.
22634           // FIXME: Would it be better to use computeKnownBits to determine
22635           //        whether it's safe to decanonicalize the xor?
22636           // x s< 0 ? x^C : 0 --> subus x, C
22637           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22638               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22639               OpRHSConst->getAPIntValue().isSignBit())
22640             // Note that we have to rebuild the RHS constant here to ensure we
22641             // don't rely on particular values of undef lanes.
22642             return DAG.getNode(
22643                 X86ISD::SUBUS, DL, VT, OpLHS,
22644                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22645         }
22646     }
22647   }
22648
22649   // Try to match a min/max vector operation.
22650   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22651     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22652     unsigned Opc = ret.first;
22653     bool NeedSplit = ret.second;
22654
22655     if (Opc && NeedSplit) {
22656       unsigned NumElems = VT.getVectorNumElements();
22657       // Extract the LHS vectors
22658       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22659       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22660
22661       // Extract the RHS vectors
22662       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22663       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22664
22665       // Create min/max for each subvector
22666       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22667       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22668
22669       // Merge the result
22670       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22671     } else if (Opc)
22672       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22673   }
22674
22675   // Simplify vector selection if condition value type matches vselect
22676   // operand type
22677   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22678     assert(Cond.getValueType().isVector() &&
22679            "vector select expects a vector selector!");
22680
22681     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22682     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22683
22684     // Try invert the condition if true value is not all 1s and false value
22685     // is not all 0s.
22686     if (!TValIsAllOnes && !FValIsAllZeros &&
22687         // Check if the selector will be produced by CMPP*/PCMP*
22688         Cond.getOpcode() == ISD::SETCC &&
22689         // Check if SETCC has already been promoted
22690         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22691             CondVT) {
22692       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22693       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22694
22695       if (TValIsAllZeros || FValIsAllOnes) {
22696         SDValue CC = Cond.getOperand(2);
22697         ISD::CondCode NewCC =
22698           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22699                                Cond.getOperand(0).getValueType().isInteger());
22700         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22701         std::swap(LHS, RHS);
22702         TValIsAllOnes = FValIsAllOnes;
22703         FValIsAllZeros = TValIsAllZeros;
22704       }
22705     }
22706
22707     if (TValIsAllOnes || FValIsAllZeros) {
22708       SDValue Ret;
22709
22710       if (TValIsAllOnes && FValIsAllZeros)
22711         Ret = Cond;
22712       else if (TValIsAllOnes)
22713         Ret =
22714             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22715       else if (FValIsAllZeros)
22716         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22717                           DAG.getBitcast(CondVT, LHS));
22718
22719       return DAG.getBitcast(VT, Ret);
22720     }
22721   }
22722
22723   // We should generate an X86ISD::BLENDI from a vselect if its argument
22724   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22725   // constants. This specific pattern gets generated when we split a
22726   // selector for a 512 bit vector in a machine without AVX512 (but with
22727   // 256-bit vectors), during legalization:
22728   //
22729   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22730   //
22731   // Iff we find this pattern and the build_vectors are built from
22732   // constants, we translate the vselect into a shuffle_vector that we
22733   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22734   if ((N->getOpcode() == ISD::VSELECT ||
22735        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22736       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22737     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22738     if (Shuffle.getNode())
22739       return Shuffle;
22740   }
22741
22742   // If this is a *dynamic* select (non-constant condition) and we can match
22743   // this node with one of the variable blend instructions, restructure the
22744   // condition so that the blends can use the high bit of each element and use
22745   // SimplifyDemandedBits to simplify the condition operand.
22746   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22747       !DCI.isBeforeLegalize() &&
22748       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22749     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22750
22751     // Don't optimize vector selects that map to mask-registers.
22752     if (BitWidth == 1)
22753       return SDValue();
22754
22755     // We can only handle the cases where VSELECT is directly legal on the
22756     // subtarget. We custom lower VSELECT nodes with constant conditions and
22757     // this makes it hard to see whether a dynamic VSELECT will correctly
22758     // lower, so we both check the operation's status and explicitly handle the
22759     // cases where a *dynamic* blend will fail even though a constant-condition
22760     // blend could be custom lowered.
22761     // FIXME: We should find a better way to handle this class of problems.
22762     // Potentially, we should combine constant-condition vselect nodes
22763     // pre-legalization into shuffles and not mark as many types as custom
22764     // lowered.
22765     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22766       return SDValue();
22767     // FIXME: We don't support i16-element blends currently. We could and
22768     // should support them by making *all* the bits in the condition be set
22769     // rather than just the high bit and using an i8-element blend.
22770     if (VT.getScalarType() == MVT::i16)
22771       return SDValue();
22772     // Dynamic blending was only available from SSE4.1 onward.
22773     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22774       return SDValue();
22775     // Byte blends are only available in AVX2
22776     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22777         !Subtarget->hasAVX2())
22778       return SDValue();
22779
22780     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22781     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22782
22783     APInt KnownZero, KnownOne;
22784     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22785                                           DCI.isBeforeLegalizeOps());
22786     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22787         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22788                                  TLO)) {
22789       // If we changed the computation somewhere in the DAG, this change
22790       // will affect all users of Cond.
22791       // Make sure it is fine and update all the nodes so that we do not
22792       // use the generic VSELECT anymore. Otherwise, we may perform
22793       // wrong optimizations as we messed up with the actual expectation
22794       // for the vector boolean values.
22795       if (Cond != TLO.Old) {
22796         // Check all uses of that condition operand to check whether it will be
22797         // consumed by non-BLEND instructions, which may depend on all bits are
22798         // set properly.
22799         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22800              I != E; ++I)
22801           if (I->getOpcode() != ISD::VSELECT)
22802             // TODO: Add other opcodes eventually lowered into BLEND.
22803             return SDValue();
22804
22805         // Update all the users of the condition, before committing the change,
22806         // so that the VSELECT optimizations that expect the correct vector
22807         // boolean value will not be triggered.
22808         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22809              I != E; ++I)
22810           DAG.ReplaceAllUsesOfValueWith(
22811               SDValue(*I, 0),
22812               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22813                           Cond, I->getOperand(1), I->getOperand(2)));
22814         DCI.CommitTargetLoweringOpt(TLO);
22815         return SDValue();
22816       }
22817       // At this point, only Cond is changed. Change the condition
22818       // just for N to keep the opportunity to optimize all other
22819       // users their own way.
22820       DAG.ReplaceAllUsesOfValueWith(
22821           SDValue(N, 0),
22822           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22823                       TLO.New, N->getOperand(1), N->getOperand(2)));
22824       return SDValue();
22825     }
22826   }
22827
22828   return SDValue();
22829 }
22830
22831 // Check whether a boolean test is testing a boolean value generated by
22832 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22833 // code.
22834 //
22835 // Simplify the following patterns:
22836 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22837 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22838 // to (Op EFLAGS Cond)
22839 //
22840 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22841 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22842 // to (Op EFLAGS !Cond)
22843 //
22844 // where Op could be BRCOND or CMOV.
22845 //
22846 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22847   // Quit if not CMP and SUB with its value result used.
22848   if (Cmp.getOpcode() != X86ISD::CMP &&
22849       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22850       return SDValue();
22851
22852   // Quit if not used as a boolean value.
22853   if (CC != X86::COND_E && CC != X86::COND_NE)
22854     return SDValue();
22855
22856   // Check CMP operands. One of them should be 0 or 1 and the other should be
22857   // an SetCC or extended from it.
22858   SDValue Op1 = Cmp.getOperand(0);
22859   SDValue Op2 = Cmp.getOperand(1);
22860
22861   SDValue SetCC;
22862   const ConstantSDNode* C = nullptr;
22863   bool needOppositeCond = (CC == X86::COND_E);
22864   bool checkAgainstTrue = false; // Is it a comparison against 1?
22865
22866   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22867     SetCC = Op2;
22868   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22869     SetCC = Op1;
22870   else // Quit if all operands are not constants.
22871     return SDValue();
22872
22873   if (C->getZExtValue() == 1) {
22874     needOppositeCond = !needOppositeCond;
22875     checkAgainstTrue = true;
22876   } else if (C->getZExtValue() != 0)
22877     // Quit if the constant is neither 0 or 1.
22878     return SDValue();
22879
22880   bool truncatedToBoolWithAnd = false;
22881   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22882   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22883          SetCC.getOpcode() == ISD::TRUNCATE ||
22884          SetCC.getOpcode() == ISD::AND) {
22885     if (SetCC.getOpcode() == ISD::AND) {
22886       int OpIdx = -1;
22887       ConstantSDNode *CS;
22888       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22889           CS->getZExtValue() == 1)
22890         OpIdx = 1;
22891       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22892           CS->getZExtValue() == 1)
22893         OpIdx = 0;
22894       if (OpIdx == -1)
22895         break;
22896       SetCC = SetCC.getOperand(OpIdx);
22897       truncatedToBoolWithAnd = true;
22898     } else
22899       SetCC = SetCC.getOperand(0);
22900   }
22901
22902   switch (SetCC.getOpcode()) {
22903   case X86ISD::SETCC_CARRY:
22904     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22905     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22906     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22907     // truncated to i1 using 'and'.
22908     if (checkAgainstTrue && !truncatedToBoolWithAnd)
22909       break;
22910     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22911            "Invalid use of SETCC_CARRY!");
22912     // FALL THROUGH
22913   case X86ISD::SETCC:
22914     // Set the condition code or opposite one if necessary.
22915     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22916     if (needOppositeCond)
22917       CC = X86::GetOppositeBranchCondition(CC);
22918     return SetCC.getOperand(1);
22919   case X86ISD::CMOV: {
22920     // Check whether false/true value has canonical one, i.e. 0 or 1.
22921     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22922     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22923     // Quit if true value is not a constant.
22924     if (!TVal)
22925       return SDValue();
22926     // Quit if false value is not a constant.
22927     if (!FVal) {
22928       SDValue Op = SetCC.getOperand(0);
22929       // Skip 'zext' or 'trunc' node.
22930       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22931           Op.getOpcode() == ISD::TRUNCATE)
22932         Op = Op.getOperand(0);
22933       // A special case for rdrand/rdseed, where 0 is set if false cond is
22934       // found.
22935       if ((Op.getOpcode() != X86ISD::RDRAND &&
22936            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22937         return SDValue();
22938     }
22939     // Quit if false value is not the constant 0 or 1.
22940     bool FValIsFalse = true;
22941     if (FVal && FVal->getZExtValue() != 0) {
22942       if (FVal->getZExtValue() != 1)
22943         return SDValue();
22944       // If FVal is 1, opposite cond is needed.
22945       needOppositeCond = !needOppositeCond;
22946       FValIsFalse = false;
22947     }
22948     // Quit if TVal is not the constant opposite of FVal.
22949     if (FValIsFalse && TVal->getZExtValue() != 1)
22950       return SDValue();
22951     if (!FValIsFalse && TVal->getZExtValue() != 0)
22952       return SDValue();
22953     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22954     if (needOppositeCond)
22955       CC = X86::GetOppositeBranchCondition(CC);
22956     return SetCC.getOperand(3);
22957   }
22958   }
22959
22960   return SDValue();
22961 }
22962
22963 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22964 /// Match:
22965 ///   (X86or (X86setcc) (X86setcc))
22966 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
22967 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22968                                            X86::CondCode &CC1, SDValue &Flags,
22969                                            bool &isAnd) {
22970   if (Cond->getOpcode() == X86ISD::CMP) {
22971     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22972     if (!CondOp1C || !CondOp1C->isNullValue())
22973       return false;
22974
22975     Cond = Cond->getOperand(0);
22976   }
22977
22978   isAnd = false;
22979
22980   SDValue SetCC0, SetCC1;
22981   switch (Cond->getOpcode()) {
22982   default: return false;
22983   case ISD::AND:
22984   case X86ISD::AND:
22985     isAnd = true;
22986     // fallthru
22987   case ISD::OR:
22988   case X86ISD::OR:
22989     SetCC0 = Cond->getOperand(0);
22990     SetCC1 = Cond->getOperand(1);
22991     break;
22992   };
22993
22994   // Make sure we have SETCC nodes, using the same flags value.
22995   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22996       SetCC1.getOpcode() != X86ISD::SETCC ||
22997       SetCC0->getOperand(1) != SetCC1->getOperand(1))
22998     return false;
22999
23000   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23001   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23002   Flags = SetCC0->getOperand(1);
23003   return true;
23004 }
23005
23006 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23007 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23008                                   TargetLowering::DAGCombinerInfo &DCI,
23009                                   const X86Subtarget *Subtarget) {
23010   SDLoc DL(N);
23011
23012   // If the flag operand isn't dead, don't touch this CMOV.
23013   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23014     return SDValue();
23015
23016   SDValue FalseOp = N->getOperand(0);
23017   SDValue TrueOp = N->getOperand(1);
23018   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23019   SDValue Cond = N->getOperand(3);
23020
23021   if (CC == X86::COND_E || CC == X86::COND_NE) {
23022     switch (Cond.getOpcode()) {
23023     default: break;
23024     case X86ISD::BSR:
23025     case X86ISD::BSF:
23026       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23027       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23028         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23029     }
23030   }
23031
23032   SDValue Flags;
23033
23034   Flags = checkBoolTestSetCCCombine(Cond, CC);
23035   if (Flags.getNode() &&
23036       // Extra check as FCMOV only supports a subset of X86 cond.
23037       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23038     SDValue Ops[] = { FalseOp, TrueOp,
23039                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23040     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23041   }
23042
23043   // If this is a select between two integer constants, try to do some
23044   // optimizations.  Note that the operands are ordered the opposite of SELECT
23045   // operands.
23046   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23047     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23048       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23049       // larger than FalseC (the false value).
23050       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23051         CC = X86::GetOppositeBranchCondition(CC);
23052         std::swap(TrueC, FalseC);
23053         std::swap(TrueOp, FalseOp);
23054       }
23055
23056       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23057       // This is efficient for any integer data type (including i8/i16) and
23058       // shift amount.
23059       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23060         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23061                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23062
23063         // Zero extend the condition if needed.
23064         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23065
23066         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23067         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23068                            DAG.getConstant(ShAmt, DL, MVT::i8));
23069         if (N->getNumValues() == 2)  // Dead flag value?
23070           return DCI.CombineTo(N, Cond, SDValue());
23071         return Cond;
23072       }
23073
23074       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23075       // for any integer data type, including i8/i16.
23076       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23077         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23078                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23079
23080         // Zero extend the condition if needed.
23081         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23082                            FalseC->getValueType(0), Cond);
23083         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23084                            SDValue(FalseC, 0));
23085
23086         if (N->getNumValues() == 2)  // Dead flag value?
23087           return DCI.CombineTo(N, Cond, SDValue());
23088         return Cond;
23089       }
23090
23091       // Optimize cases that will turn into an LEA instruction.  This requires
23092       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23093       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23094         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23095         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23096
23097         bool isFastMultiplier = false;
23098         if (Diff < 10) {
23099           switch ((unsigned char)Diff) {
23100           default: break;
23101           case 1:  // result = add base, cond
23102           case 2:  // result = lea base(    , cond*2)
23103           case 3:  // result = lea base(cond, cond*2)
23104           case 4:  // result = lea base(    , cond*4)
23105           case 5:  // result = lea base(cond, cond*4)
23106           case 8:  // result = lea base(    , cond*8)
23107           case 9:  // result = lea base(cond, cond*8)
23108             isFastMultiplier = true;
23109             break;
23110           }
23111         }
23112
23113         if (isFastMultiplier) {
23114           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23115           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23116                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23117           // Zero extend the condition if needed.
23118           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23119                              Cond);
23120           // Scale the condition by the difference.
23121           if (Diff != 1)
23122             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23123                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23124
23125           // Add the base if non-zero.
23126           if (FalseC->getAPIntValue() != 0)
23127             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23128                                SDValue(FalseC, 0));
23129           if (N->getNumValues() == 2)  // Dead flag value?
23130             return DCI.CombineTo(N, Cond, SDValue());
23131           return Cond;
23132         }
23133       }
23134     }
23135   }
23136
23137   // Handle these cases:
23138   //   (select (x != c), e, c) -> select (x != c), e, x),
23139   //   (select (x == c), c, e) -> select (x == c), x, e)
23140   // where the c is an integer constant, and the "select" is the combination
23141   // of CMOV and CMP.
23142   //
23143   // The rationale for this change is that the conditional-move from a constant
23144   // needs two instructions, however, conditional-move from a register needs
23145   // only one instruction.
23146   //
23147   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23148   //  some instruction-combining opportunities. This opt needs to be
23149   //  postponed as late as possible.
23150   //
23151   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23152     // the DCI.xxxx conditions are provided to postpone the optimization as
23153     // late as possible.
23154
23155     ConstantSDNode *CmpAgainst = nullptr;
23156     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23157         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23158         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23159
23160       if (CC == X86::COND_NE &&
23161           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23162         CC = X86::GetOppositeBranchCondition(CC);
23163         std::swap(TrueOp, FalseOp);
23164       }
23165
23166       if (CC == X86::COND_E &&
23167           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23168         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23169                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23170         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23171       }
23172     }
23173   }
23174
23175   // Fold and/or of setcc's to double CMOV:
23176   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23177   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23178   //
23179   // This combine lets us generate:
23180   //   cmovcc1 (jcc1 if we don't have CMOV)
23181   //   cmovcc2 (same)
23182   // instead of:
23183   //   setcc1
23184   //   setcc2
23185   //   and/or
23186   //   cmovne (jne if we don't have CMOV)
23187   // When we can't use the CMOV instruction, it might increase branch
23188   // mispredicts.
23189   // When we can use CMOV, or when there is no mispredict, this improves
23190   // throughput and reduces register pressure.
23191   //
23192   if (CC == X86::COND_NE) {
23193     SDValue Flags;
23194     X86::CondCode CC0, CC1;
23195     bool isAndSetCC;
23196     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23197       if (isAndSetCC) {
23198         std::swap(FalseOp, TrueOp);
23199         CC0 = X86::GetOppositeBranchCondition(CC0);
23200         CC1 = X86::GetOppositeBranchCondition(CC1);
23201       }
23202
23203       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23204         Flags};
23205       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23206       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23207       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23208       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23209       return CMOV;
23210     }
23211   }
23212
23213   return SDValue();
23214 }
23215
23216 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23217                                                 const X86Subtarget *Subtarget) {
23218   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23219   switch (IntNo) {
23220   default: return SDValue();
23221   // SSE/AVX/AVX2 blend intrinsics.
23222   case Intrinsic::x86_avx2_pblendvb:
23223     // Don't try to simplify this intrinsic if we don't have AVX2.
23224     if (!Subtarget->hasAVX2())
23225       return SDValue();
23226     // FALL-THROUGH
23227   case Intrinsic::x86_avx_blendv_pd_256:
23228   case Intrinsic::x86_avx_blendv_ps_256:
23229     // Don't try to simplify this intrinsic if we don't have AVX.
23230     if (!Subtarget->hasAVX())
23231       return SDValue();
23232     // FALL-THROUGH
23233   case Intrinsic::x86_sse41_blendvps:
23234   case Intrinsic::x86_sse41_blendvpd:
23235   case Intrinsic::x86_sse41_pblendvb: {
23236     SDValue Op0 = N->getOperand(1);
23237     SDValue Op1 = N->getOperand(2);
23238     SDValue Mask = N->getOperand(3);
23239
23240     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23241     if (!Subtarget->hasSSE41())
23242       return SDValue();
23243
23244     // fold (blend A, A, Mask) -> A
23245     if (Op0 == Op1)
23246       return Op0;
23247     // fold (blend A, B, allZeros) -> A
23248     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23249       return Op0;
23250     // fold (blend A, B, allOnes) -> B
23251     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23252       return Op1;
23253
23254     // Simplify the case where the mask is a constant i32 value.
23255     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23256       if (C->isNullValue())
23257         return Op0;
23258       if (C->isAllOnesValue())
23259         return Op1;
23260     }
23261
23262     return SDValue();
23263   }
23264
23265   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23266   case Intrinsic::x86_sse2_psrai_w:
23267   case Intrinsic::x86_sse2_psrai_d:
23268   case Intrinsic::x86_avx2_psrai_w:
23269   case Intrinsic::x86_avx2_psrai_d:
23270   case Intrinsic::x86_sse2_psra_w:
23271   case Intrinsic::x86_sse2_psra_d:
23272   case Intrinsic::x86_avx2_psra_w:
23273   case Intrinsic::x86_avx2_psra_d: {
23274     SDValue Op0 = N->getOperand(1);
23275     SDValue Op1 = N->getOperand(2);
23276     EVT VT = Op0.getValueType();
23277     assert(VT.isVector() && "Expected a vector type!");
23278
23279     if (isa<BuildVectorSDNode>(Op1))
23280       Op1 = Op1.getOperand(0);
23281
23282     if (!isa<ConstantSDNode>(Op1))
23283       return SDValue();
23284
23285     EVT SVT = VT.getVectorElementType();
23286     unsigned SVTBits = SVT.getSizeInBits();
23287
23288     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23289     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23290     uint64_t ShAmt = C.getZExtValue();
23291
23292     // Don't try to convert this shift into a ISD::SRA if the shift
23293     // count is bigger than or equal to the element size.
23294     if (ShAmt >= SVTBits)
23295       return SDValue();
23296
23297     // Trivial case: if the shift count is zero, then fold this
23298     // into the first operand.
23299     if (ShAmt == 0)
23300       return Op0;
23301
23302     // Replace this packed shift intrinsic with a target independent
23303     // shift dag node.
23304     SDLoc DL(N);
23305     SDValue Splat = DAG.getConstant(C, DL, VT);
23306     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23307   }
23308   }
23309 }
23310
23311 /// PerformMulCombine - Optimize a single multiply with constant into two
23312 /// in order to implement it with two cheaper instructions, e.g.
23313 /// LEA + SHL, LEA + LEA.
23314 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23315                                  TargetLowering::DAGCombinerInfo &DCI) {
23316   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23317     return SDValue();
23318
23319   EVT VT = N->getValueType(0);
23320   if (VT != MVT::i64 && VT != MVT::i32)
23321     return SDValue();
23322
23323   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23324   if (!C)
23325     return SDValue();
23326   uint64_t MulAmt = C->getZExtValue();
23327   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23328     return SDValue();
23329
23330   uint64_t MulAmt1 = 0;
23331   uint64_t MulAmt2 = 0;
23332   if ((MulAmt % 9) == 0) {
23333     MulAmt1 = 9;
23334     MulAmt2 = MulAmt / 9;
23335   } else if ((MulAmt % 5) == 0) {
23336     MulAmt1 = 5;
23337     MulAmt2 = MulAmt / 5;
23338   } else if ((MulAmt % 3) == 0) {
23339     MulAmt1 = 3;
23340     MulAmt2 = MulAmt / 3;
23341   }
23342   if (MulAmt2 &&
23343       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23344     SDLoc DL(N);
23345
23346     if (isPowerOf2_64(MulAmt2) &&
23347         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23348       // If second multiplifer is pow2, issue it first. We want the multiply by
23349       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23350       // is an add.
23351       std::swap(MulAmt1, MulAmt2);
23352
23353     SDValue NewMul;
23354     if (isPowerOf2_64(MulAmt1))
23355       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23356                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23357     else
23358       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23359                            DAG.getConstant(MulAmt1, DL, VT));
23360
23361     if (isPowerOf2_64(MulAmt2))
23362       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23363                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23364     else
23365       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23366                            DAG.getConstant(MulAmt2, DL, VT));
23367
23368     // Do not add new nodes to DAG combiner worklist.
23369     DCI.CombineTo(N, NewMul, false);
23370   }
23371   return SDValue();
23372 }
23373
23374 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23375   SDValue N0 = N->getOperand(0);
23376   SDValue N1 = N->getOperand(1);
23377   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23378   EVT VT = N0.getValueType();
23379
23380   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23381   // since the result of setcc_c is all zero's or all ones.
23382   if (VT.isInteger() && !VT.isVector() &&
23383       N1C && N0.getOpcode() == ISD::AND &&
23384       N0.getOperand(1).getOpcode() == ISD::Constant) {
23385     SDValue N00 = N0.getOperand(0);
23386     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23387         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23388           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23389          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23390       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23391       APInt ShAmt = N1C->getAPIntValue();
23392       Mask = Mask.shl(ShAmt);
23393       if (Mask != 0) {
23394         SDLoc DL(N);
23395         return DAG.getNode(ISD::AND, DL, VT,
23396                            N00, DAG.getConstant(Mask, DL, VT));
23397       }
23398     }
23399   }
23400
23401   // Hardware support for vector shifts is sparse which makes us scalarize the
23402   // vector operations in many cases. Also, on sandybridge ADD is faster than
23403   // shl.
23404   // (shl V, 1) -> add V,V
23405   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23406     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23407       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23408       // We shift all of the values by one. In many cases we do not have
23409       // hardware support for this operation. This is better expressed as an ADD
23410       // of two values.
23411       if (N1SplatC->getAPIntValue() == 1)
23412         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23413     }
23414
23415   return SDValue();
23416 }
23417
23418 /// \brief Returns a vector of 0s if the node in input is a vector logical
23419 /// shift by a constant amount which is known to be bigger than or equal
23420 /// to the vector element size in bits.
23421 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23422                                       const X86Subtarget *Subtarget) {
23423   EVT VT = N->getValueType(0);
23424
23425   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23426       (!Subtarget->hasInt256() ||
23427        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23428     return SDValue();
23429
23430   SDValue Amt = N->getOperand(1);
23431   SDLoc DL(N);
23432   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23433     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23434       APInt ShiftAmt = AmtSplat->getAPIntValue();
23435       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23436
23437       // SSE2/AVX2 logical shifts always return a vector of 0s
23438       // if the shift amount is bigger than or equal to
23439       // the element size. The constant shift amount will be
23440       // encoded as a 8-bit immediate.
23441       if (ShiftAmt.trunc(8).uge(MaxAmount))
23442         return getZeroVector(VT, Subtarget, DAG, DL);
23443     }
23444
23445   return SDValue();
23446 }
23447
23448 /// PerformShiftCombine - Combine shifts.
23449 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23450                                    TargetLowering::DAGCombinerInfo &DCI,
23451                                    const X86Subtarget *Subtarget) {
23452   if (N->getOpcode() == ISD::SHL)
23453     if (SDValue V = PerformSHLCombine(N, DAG))
23454       return V;
23455
23456   // Try to fold this logical shift into a zero vector.
23457   if (N->getOpcode() != ISD::SRA)
23458     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23459       return V;
23460
23461   return SDValue();
23462 }
23463
23464 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23465 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23466 // and friends.  Likewise for OR -> CMPNEQSS.
23467 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23468                             TargetLowering::DAGCombinerInfo &DCI,
23469                             const X86Subtarget *Subtarget) {
23470   unsigned opcode;
23471
23472   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23473   // we're requiring SSE2 for both.
23474   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23475     SDValue N0 = N->getOperand(0);
23476     SDValue N1 = N->getOperand(1);
23477     SDValue CMP0 = N0->getOperand(1);
23478     SDValue CMP1 = N1->getOperand(1);
23479     SDLoc DL(N);
23480
23481     // The SETCCs should both refer to the same CMP.
23482     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23483       return SDValue();
23484
23485     SDValue CMP00 = CMP0->getOperand(0);
23486     SDValue CMP01 = CMP0->getOperand(1);
23487     EVT     VT    = CMP00.getValueType();
23488
23489     if (VT == MVT::f32 || VT == MVT::f64) {
23490       bool ExpectingFlags = false;
23491       // Check for any users that want flags:
23492       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23493            !ExpectingFlags && UI != UE; ++UI)
23494         switch (UI->getOpcode()) {
23495         default:
23496         case ISD::BR_CC:
23497         case ISD::BRCOND:
23498         case ISD::SELECT:
23499           ExpectingFlags = true;
23500           break;
23501         case ISD::CopyToReg:
23502         case ISD::SIGN_EXTEND:
23503         case ISD::ZERO_EXTEND:
23504         case ISD::ANY_EXTEND:
23505           break;
23506         }
23507
23508       if (!ExpectingFlags) {
23509         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23510         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23511
23512         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23513           X86::CondCode tmp = cc0;
23514           cc0 = cc1;
23515           cc1 = tmp;
23516         }
23517
23518         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23519             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23520           // FIXME: need symbolic constants for these magic numbers.
23521           // See X86ATTInstPrinter.cpp:printSSECC().
23522           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23523           if (Subtarget->hasAVX512()) {
23524             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23525                                          CMP01,
23526                                          DAG.getConstant(x86cc, DL, MVT::i8));
23527             if (N->getValueType(0) != MVT::i1)
23528               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23529                                  FSetCC);
23530             return FSetCC;
23531           }
23532           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23533                                               CMP00.getValueType(), CMP00, CMP01,
23534                                               DAG.getConstant(x86cc, DL,
23535                                                               MVT::i8));
23536
23537           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23538           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23539
23540           if (is64BitFP && !Subtarget->is64Bit()) {
23541             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23542             // 64-bit integer, since that's not a legal type. Since
23543             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23544             // bits, but can do this little dance to extract the lowest 32 bits
23545             // and work with those going forward.
23546             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23547                                            OnesOrZeroesF);
23548             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23549             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23550                                         Vector32, DAG.getIntPtrConstant(0, DL));
23551             IntVT = MVT::i32;
23552           }
23553
23554           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23555           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23556                                       DAG.getConstant(1, DL, IntVT));
23557           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23558                                               ANDed);
23559           return OneBitOfTruth;
23560         }
23561       }
23562     }
23563   }
23564   return SDValue();
23565 }
23566
23567 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23568 /// so it can be folded inside ANDNP.
23569 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23570   EVT VT = N->getValueType(0);
23571
23572   // Match direct AllOnes for 128 and 256-bit vectors
23573   if (ISD::isBuildVectorAllOnes(N))
23574     return true;
23575
23576   // Look through a bit convert.
23577   if (N->getOpcode() == ISD::BITCAST)
23578     N = N->getOperand(0).getNode();
23579
23580   // Sometimes the operand may come from a insert_subvector building a 256-bit
23581   // allones vector
23582   if (VT.is256BitVector() &&
23583       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23584     SDValue V1 = N->getOperand(0);
23585     SDValue V2 = N->getOperand(1);
23586
23587     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23588         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23589         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23590         ISD::isBuildVectorAllOnes(V2.getNode()))
23591       return true;
23592   }
23593
23594   return false;
23595 }
23596
23597 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23598 // register. In most cases we actually compare or select YMM-sized registers
23599 // and mixing the two types creates horrible code. This method optimizes
23600 // some of the transition sequences.
23601 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23602                                  TargetLowering::DAGCombinerInfo &DCI,
23603                                  const X86Subtarget *Subtarget) {
23604   EVT VT = N->getValueType(0);
23605   if (!VT.is256BitVector())
23606     return SDValue();
23607
23608   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23609           N->getOpcode() == ISD::ZERO_EXTEND ||
23610           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23611
23612   SDValue Narrow = N->getOperand(0);
23613   EVT NarrowVT = Narrow->getValueType(0);
23614   if (!NarrowVT.is128BitVector())
23615     return SDValue();
23616
23617   if (Narrow->getOpcode() != ISD::XOR &&
23618       Narrow->getOpcode() != ISD::AND &&
23619       Narrow->getOpcode() != ISD::OR)
23620     return SDValue();
23621
23622   SDValue N0  = Narrow->getOperand(0);
23623   SDValue N1  = Narrow->getOperand(1);
23624   SDLoc DL(Narrow);
23625
23626   // The Left side has to be a trunc.
23627   if (N0.getOpcode() != ISD::TRUNCATE)
23628     return SDValue();
23629
23630   // The type of the truncated inputs.
23631   EVT WideVT = N0->getOperand(0)->getValueType(0);
23632   if (WideVT != VT)
23633     return SDValue();
23634
23635   // The right side has to be a 'trunc' or a constant vector.
23636   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23637   ConstantSDNode *RHSConstSplat = nullptr;
23638   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23639     RHSConstSplat = RHSBV->getConstantSplatNode();
23640   if (!RHSTrunc && !RHSConstSplat)
23641     return SDValue();
23642
23643   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23644
23645   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23646     return SDValue();
23647
23648   // Set N0 and N1 to hold the inputs to the new wide operation.
23649   N0 = N0->getOperand(0);
23650   if (RHSConstSplat) {
23651     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23652                      SDValue(RHSConstSplat, 0));
23653     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23654     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23655   } else if (RHSTrunc) {
23656     N1 = N1->getOperand(0);
23657   }
23658
23659   // Generate the wide operation.
23660   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23661   unsigned Opcode = N->getOpcode();
23662   switch (Opcode) {
23663   case ISD::ANY_EXTEND:
23664     return Op;
23665   case ISD::ZERO_EXTEND: {
23666     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23667     APInt Mask = APInt::getAllOnesValue(InBits);
23668     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23669     return DAG.getNode(ISD::AND, DL, VT,
23670                        Op, DAG.getConstant(Mask, DL, VT));
23671   }
23672   case ISD::SIGN_EXTEND:
23673     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23674                        Op, DAG.getValueType(NarrowVT));
23675   default:
23676     llvm_unreachable("Unexpected opcode");
23677   }
23678 }
23679
23680 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23681                                  TargetLowering::DAGCombinerInfo &DCI,
23682                                  const X86Subtarget *Subtarget) {
23683   SDValue N0 = N->getOperand(0);
23684   SDValue N1 = N->getOperand(1);
23685   SDLoc DL(N);
23686
23687   // A vector zext_in_reg may be represented as a shuffle,
23688   // feeding into a bitcast (this represents anyext) feeding into
23689   // an and with a mask.
23690   // We'd like to try to combine that into a shuffle with zero
23691   // plus a bitcast, removing the and.
23692   if (N0.getOpcode() != ISD::BITCAST ||
23693       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23694     return SDValue();
23695
23696   // The other side of the AND should be a splat of 2^C, where C
23697   // is the number of bits in the source type.
23698   if (N1.getOpcode() == ISD::BITCAST)
23699     N1 = N1.getOperand(0);
23700   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23701     return SDValue();
23702   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23703
23704   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23705   EVT SrcType = Shuffle->getValueType(0);
23706
23707   // We expect a single-source shuffle
23708   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23709     return SDValue();
23710
23711   unsigned SrcSize = SrcType.getScalarSizeInBits();
23712
23713   APInt SplatValue, SplatUndef;
23714   unsigned SplatBitSize;
23715   bool HasAnyUndefs;
23716   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23717                                 SplatBitSize, HasAnyUndefs))
23718     return SDValue();
23719
23720   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23721   // Make sure the splat matches the mask we expect
23722   if (SplatBitSize > ResSize ||
23723       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23724     return SDValue();
23725
23726   // Make sure the input and output size make sense
23727   if (SrcSize >= ResSize || ResSize % SrcSize)
23728     return SDValue();
23729
23730   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23731   // The number of u's between each two values depends on the ratio between
23732   // the source and dest type.
23733   unsigned ZextRatio = ResSize / SrcSize;
23734   bool IsZext = true;
23735   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23736     if (i % ZextRatio) {
23737       if (Shuffle->getMaskElt(i) > 0) {
23738         // Expected undef
23739         IsZext = false;
23740         break;
23741       }
23742     } else {
23743       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23744         // Expected element number
23745         IsZext = false;
23746         break;
23747       }
23748     }
23749   }
23750
23751   if (!IsZext)
23752     return SDValue();
23753
23754   // Ok, perform the transformation - replace the shuffle with
23755   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23756   // (instead of undef) where the k elements come from the zero vector.
23757   SmallVector<int, 8> Mask;
23758   unsigned NumElems = SrcType.getVectorNumElements();
23759   for (unsigned i = 0; i < NumElems; ++i)
23760     if (i % ZextRatio)
23761       Mask.push_back(NumElems);
23762     else
23763       Mask.push_back(i / ZextRatio);
23764
23765   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23766     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23767   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23768 }
23769
23770 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23771                                  TargetLowering::DAGCombinerInfo &DCI,
23772                                  const X86Subtarget *Subtarget) {
23773   if (DCI.isBeforeLegalizeOps())
23774     return SDValue();
23775
23776   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23777     return Zext;
23778
23779   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23780     return R;
23781
23782   EVT VT = N->getValueType(0);
23783   SDValue N0 = N->getOperand(0);
23784   SDValue N1 = N->getOperand(1);
23785   SDLoc DL(N);
23786
23787   // Create BEXTR instructions
23788   // BEXTR is ((X >> imm) & (2**size-1))
23789   if (VT == MVT::i32 || VT == MVT::i64) {
23790     // Check for BEXTR.
23791     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23792         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23793       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23794       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23795       if (MaskNode && ShiftNode) {
23796         uint64_t Mask = MaskNode->getZExtValue();
23797         uint64_t Shift = ShiftNode->getZExtValue();
23798         if (isMask_64(Mask)) {
23799           uint64_t MaskSize = countPopulation(Mask);
23800           if (Shift + MaskSize <= VT.getSizeInBits())
23801             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23802                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23803                                                VT));
23804         }
23805       }
23806     } // BEXTR
23807
23808     return SDValue();
23809   }
23810
23811   // Want to form ANDNP nodes:
23812   // 1) In the hopes of then easily combining them with OR and AND nodes
23813   //    to form PBLEND/PSIGN.
23814   // 2) To match ANDN packed intrinsics
23815   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23816     return SDValue();
23817
23818   // Check LHS for vnot
23819   if (N0.getOpcode() == ISD::XOR &&
23820       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23821       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23822     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23823
23824   // Check RHS for vnot
23825   if (N1.getOpcode() == ISD::XOR &&
23826       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23827       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23828     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23829
23830   return SDValue();
23831 }
23832
23833 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23834                                 TargetLowering::DAGCombinerInfo &DCI,
23835                                 const X86Subtarget *Subtarget) {
23836   if (DCI.isBeforeLegalizeOps())
23837     return SDValue();
23838
23839   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23840     return R;
23841
23842   SDValue N0 = N->getOperand(0);
23843   SDValue N1 = N->getOperand(1);
23844   EVT VT = N->getValueType(0);
23845
23846   // look for psign/blend
23847   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23848     if (!Subtarget->hasSSSE3() ||
23849         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23850       return SDValue();
23851
23852     // Canonicalize pandn to RHS
23853     if (N0.getOpcode() == X86ISD::ANDNP)
23854       std::swap(N0, N1);
23855     // or (and (m, y), (pandn m, x))
23856     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23857       SDValue Mask = N1.getOperand(0);
23858       SDValue X    = N1.getOperand(1);
23859       SDValue Y;
23860       if (N0.getOperand(0) == Mask)
23861         Y = N0.getOperand(1);
23862       if (N0.getOperand(1) == Mask)
23863         Y = N0.getOperand(0);
23864
23865       // Check to see if the mask appeared in both the AND and ANDNP and
23866       if (!Y.getNode())
23867         return SDValue();
23868
23869       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23870       // Look through mask bitcast.
23871       if (Mask.getOpcode() == ISD::BITCAST)
23872         Mask = Mask.getOperand(0);
23873       if (X.getOpcode() == ISD::BITCAST)
23874         X = X.getOperand(0);
23875       if (Y.getOpcode() == ISD::BITCAST)
23876         Y = Y.getOperand(0);
23877
23878       EVT MaskVT = Mask.getValueType();
23879
23880       // Validate that the Mask operand is a vector sra node.
23881       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23882       // there is no psrai.b
23883       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23884       unsigned SraAmt = ~0;
23885       if (Mask.getOpcode() == ISD::SRA) {
23886         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23887           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23888             SraAmt = AmtConst->getZExtValue();
23889       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23890         SDValue SraC = Mask.getOperand(1);
23891         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23892       }
23893       if ((SraAmt + 1) != EltBits)
23894         return SDValue();
23895
23896       SDLoc DL(N);
23897
23898       // Now we know we at least have a plendvb with the mask val.  See if
23899       // we can form a psignb/w/d.
23900       // psign = x.type == y.type == mask.type && y = sub(0, x);
23901       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23902           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23903           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23904         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23905                "Unsupported VT for PSIGN");
23906         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23907         return DAG.getBitcast(VT, Mask);
23908       }
23909       // PBLENDVB only available on SSE 4.1
23910       if (!Subtarget->hasSSE41())
23911         return SDValue();
23912
23913       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23914
23915       X = DAG.getBitcast(BlendVT, X);
23916       Y = DAG.getBitcast(BlendVT, Y);
23917       Mask = DAG.getBitcast(BlendVT, Mask);
23918       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23919       return DAG.getBitcast(VT, Mask);
23920     }
23921   }
23922
23923   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23924     return SDValue();
23925
23926   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23927   MachineFunction &MF = DAG.getMachineFunction();
23928   bool OptForSize =
23929       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23930
23931   // SHLD/SHRD instructions have lower register pressure, but on some
23932   // platforms they have higher latency than the equivalent
23933   // series of shifts/or that would otherwise be generated.
23934   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23935   // have higher latencies and we are not optimizing for size.
23936   if (!OptForSize && Subtarget->isSHLDSlow())
23937     return SDValue();
23938
23939   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23940     std::swap(N0, N1);
23941   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23942     return SDValue();
23943   if (!N0.hasOneUse() || !N1.hasOneUse())
23944     return SDValue();
23945
23946   SDValue ShAmt0 = N0.getOperand(1);
23947   if (ShAmt0.getValueType() != MVT::i8)
23948     return SDValue();
23949   SDValue ShAmt1 = N1.getOperand(1);
23950   if (ShAmt1.getValueType() != MVT::i8)
23951     return SDValue();
23952   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23953     ShAmt0 = ShAmt0.getOperand(0);
23954   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23955     ShAmt1 = ShAmt1.getOperand(0);
23956
23957   SDLoc DL(N);
23958   unsigned Opc = X86ISD::SHLD;
23959   SDValue Op0 = N0.getOperand(0);
23960   SDValue Op1 = N1.getOperand(0);
23961   if (ShAmt0.getOpcode() == ISD::SUB) {
23962     Opc = X86ISD::SHRD;
23963     std::swap(Op0, Op1);
23964     std::swap(ShAmt0, ShAmt1);
23965   }
23966
23967   unsigned Bits = VT.getSizeInBits();
23968   if (ShAmt1.getOpcode() == ISD::SUB) {
23969     SDValue Sum = ShAmt1.getOperand(0);
23970     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23971       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23972       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23973         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23974       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23975         return DAG.getNode(Opc, DL, VT,
23976                            Op0, Op1,
23977                            DAG.getNode(ISD::TRUNCATE, DL,
23978                                        MVT::i8, ShAmt0));
23979     }
23980   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23981     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23982     if (ShAmt0C &&
23983         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23984       return DAG.getNode(Opc, DL, VT,
23985                          N0.getOperand(0), N1.getOperand(0),
23986                          DAG.getNode(ISD::TRUNCATE, DL,
23987                                        MVT::i8, ShAmt0));
23988   }
23989
23990   return SDValue();
23991 }
23992
23993 // Generate NEG and CMOV for integer abs.
23994 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23995   EVT VT = N->getValueType(0);
23996
23997   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23998   // 8-bit integer abs to NEG and CMOV.
23999   if (VT.isInteger() && VT.getSizeInBits() == 8)
24000     return SDValue();
24001
24002   SDValue N0 = N->getOperand(0);
24003   SDValue N1 = N->getOperand(1);
24004   SDLoc DL(N);
24005
24006   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24007   // and change it to SUB and CMOV.
24008   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24009       N0.getOpcode() == ISD::ADD &&
24010       N0.getOperand(1) == N1 &&
24011       N1.getOpcode() == ISD::SRA &&
24012       N1.getOperand(0) == N0.getOperand(0))
24013     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24014       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24015         // Generate SUB & CMOV.
24016         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24017                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24018
24019         SDValue Ops[] = { N0.getOperand(0), Neg,
24020                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24021                           SDValue(Neg.getNode(), 1) };
24022         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24023       }
24024   return SDValue();
24025 }
24026
24027 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24028 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24029                                  TargetLowering::DAGCombinerInfo &DCI,
24030                                  const X86Subtarget *Subtarget) {
24031   if (DCI.isBeforeLegalizeOps())
24032     return SDValue();
24033
24034   if (Subtarget->hasCMov())
24035     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24036       return RV;
24037
24038   return SDValue();
24039 }
24040
24041 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24042 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24043                                   TargetLowering::DAGCombinerInfo &DCI,
24044                                   const X86Subtarget *Subtarget) {
24045   LoadSDNode *Ld = cast<LoadSDNode>(N);
24046   EVT RegVT = Ld->getValueType(0);
24047   EVT MemVT = Ld->getMemoryVT();
24048   SDLoc dl(Ld);
24049   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24050
24051   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24052   // into two 16-byte operations.
24053   ISD::LoadExtType Ext = Ld->getExtensionType();
24054   unsigned Alignment = Ld->getAlignment();
24055   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24056   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24057       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24058     unsigned NumElems = RegVT.getVectorNumElements();
24059     if (NumElems < 2)
24060       return SDValue();
24061
24062     SDValue Ptr = Ld->getBasePtr();
24063     SDValue Increment =
24064         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24065
24066     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24067                                   NumElems/2);
24068     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24069                                 Ld->getPointerInfo(), Ld->isVolatile(),
24070                                 Ld->isNonTemporal(), Ld->isInvariant(),
24071                                 Alignment);
24072     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24073     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24074                                 Ld->getPointerInfo(), Ld->isVolatile(),
24075                                 Ld->isNonTemporal(), Ld->isInvariant(),
24076                                 std::min(16U, Alignment));
24077     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24078                              Load1.getValue(1),
24079                              Load2.getValue(1));
24080
24081     SDValue NewVec = DAG.getUNDEF(RegVT);
24082     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24083     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24084     return DCI.CombineTo(N, NewVec, TF, true);
24085   }
24086
24087   return SDValue();
24088 }
24089
24090 /// PerformMLOADCombine - Resolve extending loads
24091 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24092                                    TargetLowering::DAGCombinerInfo &DCI,
24093                                    const X86Subtarget *Subtarget) {
24094   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24095   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24096     return SDValue();
24097
24098   EVT VT = Mld->getValueType(0);
24099   unsigned NumElems = VT.getVectorNumElements();
24100   EVT LdVT = Mld->getMemoryVT();
24101   SDLoc dl(Mld);
24102
24103   assert(LdVT != VT && "Cannot extend to the same type");
24104   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24105   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24106   // From, To sizes and ElemCount must be pow of two
24107   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24108     "Unexpected size for extending masked load");
24109
24110   unsigned SizeRatio  = ToSz / FromSz;
24111   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24112
24113   // Create a type on which we perform the shuffle
24114   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24115           LdVT.getScalarType(), NumElems*SizeRatio);
24116   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24117
24118   // Convert Src0 value
24119   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24120   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24121     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24122     for (unsigned i = 0; i != NumElems; ++i)
24123       ShuffleVec[i] = i * SizeRatio;
24124
24125     // Can't shuffle using an illegal type.
24126     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24127             && "WideVecVT should be legal");
24128     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24129                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24130   }
24131   // Prepare the new mask
24132   SDValue NewMask;
24133   SDValue Mask = Mld->getMask();
24134   if (Mask.getValueType() == VT) {
24135     // Mask and original value have the same type
24136     NewMask = DAG.getBitcast(WideVecVT, Mask);
24137     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24138     for (unsigned i = 0; i != NumElems; ++i)
24139       ShuffleVec[i] = i * SizeRatio;
24140     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24141       ShuffleVec[i] = NumElems*SizeRatio;
24142     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24143                                    DAG.getConstant(0, dl, WideVecVT),
24144                                    &ShuffleVec[0]);
24145   }
24146   else {
24147     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24148     unsigned WidenNumElts = NumElems*SizeRatio;
24149     unsigned MaskNumElts = VT.getVectorNumElements();
24150     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24151                                      WidenNumElts);
24152
24153     unsigned NumConcat = WidenNumElts / MaskNumElts;
24154     SmallVector<SDValue, 16> Ops(NumConcat);
24155     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24156     Ops[0] = Mask;
24157     for (unsigned i = 1; i != NumConcat; ++i)
24158       Ops[i] = ZeroVal;
24159
24160     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24161   }
24162
24163   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24164                                      Mld->getBasePtr(), NewMask, WideSrc0,
24165                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24166                                      ISD::NON_EXTLOAD);
24167   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24168   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24169
24170 }
24171 /// PerformMSTORECombine - Resolve truncating stores
24172 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24173                                     const X86Subtarget *Subtarget) {
24174   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24175   if (!Mst->isTruncatingStore())
24176     return SDValue();
24177
24178   EVT VT = Mst->getValue().getValueType();
24179   unsigned NumElems = VT.getVectorNumElements();
24180   EVT StVT = Mst->getMemoryVT();
24181   SDLoc dl(Mst);
24182
24183   assert(StVT != VT && "Cannot truncate to the same type");
24184   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24185   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24186
24187   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24188
24189   // The truncating store is legal in some cases. For example
24190   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24191   // are designated for truncate store.
24192   // In this case we don't need any further transformations.
24193   if (TLI.isTruncStoreLegal(VT, StVT))
24194     return SDValue();
24195
24196   // From, To sizes and ElemCount must be pow of two
24197   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24198     "Unexpected size for truncating masked store");
24199   // We are going to use the original vector elt for storing.
24200   // Accumulated smaller vector elements must be a multiple of the store size.
24201   assert (((NumElems * FromSz) % ToSz) == 0 &&
24202           "Unexpected ratio for truncating masked store");
24203
24204   unsigned SizeRatio  = FromSz / ToSz;
24205   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24206
24207   // Create a type on which we perform the shuffle
24208   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24209           StVT.getScalarType(), NumElems*SizeRatio);
24210
24211   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24212
24213   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24214   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24215   for (unsigned i = 0; i != NumElems; ++i)
24216     ShuffleVec[i] = i * SizeRatio;
24217
24218   // Can't shuffle using an illegal type.
24219   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24220           && "WideVecVT should be legal");
24221
24222   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24223                                         DAG.getUNDEF(WideVecVT),
24224                                         &ShuffleVec[0]);
24225
24226   SDValue NewMask;
24227   SDValue Mask = Mst->getMask();
24228   if (Mask.getValueType() == VT) {
24229     // Mask and original value have the same type
24230     NewMask = DAG.getBitcast(WideVecVT, Mask);
24231     for (unsigned i = 0; i != NumElems; ++i)
24232       ShuffleVec[i] = i * SizeRatio;
24233     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24234       ShuffleVec[i] = NumElems*SizeRatio;
24235     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24236                                    DAG.getConstant(0, dl, WideVecVT),
24237                                    &ShuffleVec[0]);
24238   }
24239   else {
24240     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24241     unsigned WidenNumElts = NumElems*SizeRatio;
24242     unsigned MaskNumElts = VT.getVectorNumElements();
24243     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24244                                      WidenNumElts);
24245
24246     unsigned NumConcat = WidenNumElts / MaskNumElts;
24247     SmallVector<SDValue, 16> Ops(NumConcat);
24248     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24249     Ops[0] = Mask;
24250     for (unsigned i = 1; i != NumConcat; ++i)
24251       Ops[i] = ZeroVal;
24252
24253     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24254   }
24255
24256   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24257                             NewMask, StVT, Mst->getMemOperand(), false);
24258 }
24259 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24260 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24261                                    const X86Subtarget *Subtarget) {
24262   StoreSDNode *St = cast<StoreSDNode>(N);
24263   EVT VT = St->getValue().getValueType();
24264   EVT StVT = St->getMemoryVT();
24265   SDLoc dl(St);
24266   SDValue StoredVal = St->getOperand(1);
24267   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24268
24269   // If we are saving a concatenation of two XMM registers and 32-byte stores
24270   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24271   unsigned Alignment = St->getAlignment();
24272   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24273   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24274       StVT == VT && !IsAligned) {
24275     unsigned NumElems = VT.getVectorNumElements();
24276     if (NumElems < 2)
24277       return SDValue();
24278
24279     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24280     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24281
24282     SDValue Stride =
24283         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24284     SDValue Ptr0 = St->getBasePtr();
24285     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24286
24287     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24288                                 St->getPointerInfo(), St->isVolatile(),
24289                                 St->isNonTemporal(), Alignment);
24290     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24291                                 St->getPointerInfo(), St->isVolatile(),
24292                                 St->isNonTemporal(),
24293                                 std::min(16U, Alignment));
24294     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24295   }
24296
24297   // Optimize trunc store (of multiple scalars) to shuffle and store.
24298   // First, pack all of the elements in one place. Next, store to memory
24299   // in fewer chunks.
24300   if (St->isTruncatingStore() && VT.isVector()) {
24301     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24302     unsigned NumElems = VT.getVectorNumElements();
24303     assert(StVT != VT && "Cannot truncate to the same type");
24304     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24305     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24306
24307     // The truncating store is legal in some cases. For example
24308     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24309     // are designated for truncate store.
24310     // In this case we don't need any further transformations.
24311     if (TLI.isTruncStoreLegal(VT, StVT))
24312       return SDValue();
24313
24314     // From, To sizes and ElemCount must be pow of two
24315     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24316     // We are going to use the original vector elt for storing.
24317     // Accumulated smaller vector elements must be a multiple of the store size.
24318     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24319
24320     unsigned SizeRatio  = FromSz / ToSz;
24321
24322     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24323
24324     // Create a type on which we perform the shuffle
24325     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24326             StVT.getScalarType(), NumElems*SizeRatio);
24327
24328     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24329
24330     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24331     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24332     for (unsigned i = 0; i != NumElems; ++i)
24333       ShuffleVec[i] = i * SizeRatio;
24334
24335     // Can't shuffle using an illegal type.
24336     if (!TLI.isTypeLegal(WideVecVT))
24337       return SDValue();
24338
24339     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24340                                          DAG.getUNDEF(WideVecVT),
24341                                          &ShuffleVec[0]);
24342     // At this point all of the data is stored at the bottom of the
24343     // register. We now need to save it to mem.
24344
24345     // Find the largest store unit
24346     MVT StoreType = MVT::i8;
24347     for (MVT Tp : MVT::integer_valuetypes()) {
24348       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24349         StoreType = Tp;
24350     }
24351
24352     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24353     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24354         (64 <= NumElems * ToSz))
24355       StoreType = MVT::f64;
24356
24357     // Bitcast the original vector into a vector of store-size units
24358     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24359             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24360     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24361     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24362     SmallVector<SDValue, 8> Chains;
24363     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24364                                         TLI.getPointerTy(DAG.getDataLayout()));
24365     SDValue Ptr = St->getBasePtr();
24366
24367     // Perform one or more big stores into memory.
24368     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24369       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24370                                    StoreType, ShuffWide,
24371                                    DAG.getIntPtrConstant(i, dl));
24372       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24373                                 St->getPointerInfo(), St->isVolatile(),
24374                                 St->isNonTemporal(), St->getAlignment());
24375       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24376       Chains.push_back(Ch);
24377     }
24378
24379     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24380   }
24381
24382   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24383   // the FP state in cases where an emms may be missing.
24384   // A preferable solution to the general problem is to figure out the right
24385   // places to insert EMMS.  This qualifies as a quick hack.
24386
24387   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24388   if (VT.getSizeInBits() != 64)
24389     return SDValue();
24390
24391   const Function *F = DAG.getMachineFunction().getFunction();
24392   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24393   bool F64IsLegal =
24394       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24395   if ((VT.isVector() ||
24396        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24397       isa<LoadSDNode>(St->getValue()) &&
24398       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24399       St->getChain().hasOneUse() && !St->isVolatile()) {
24400     SDNode* LdVal = St->getValue().getNode();
24401     LoadSDNode *Ld = nullptr;
24402     int TokenFactorIndex = -1;
24403     SmallVector<SDValue, 8> Ops;
24404     SDNode* ChainVal = St->getChain().getNode();
24405     // Must be a store of a load.  We currently handle two cases:  the load
24406     // is a direct child, and it's under an intervening TokenFactor.  It is
24407     // possible to dig deeper under nested TokenFactors.
24408     if (ChainVal == LdVal)
24409       Ld = cast<LoadSDNode>(St->getChain());
24410     else if (St->getValue().hasOneUse() &&
24411              ChainVal->getOpcode() == ISD::TokenFactor) {
24412       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24413         if (ChainVal->getOperand(i).getNode() == LdVal) {
24414           TokenFactorIndex = i;
24415           Ld = cast<LoadSDNode>(St->getValue());
24416         } else
24417           Ops.push_back(ChainVal->getOperand(i));
24418       }
24419     }
24420
24421     if (!Ld || !ISD::isNormalLoad(Ld))
24422       return SDValue();
24423
24424     // If this is not the MMX case, i.e. we are just turning i64 load/store
24425     // into f64 load/store, avoid the transformation if there are multiple
24426     // uses of the loaded value.
24427     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24428       return SDValue();
24429
24430     SDLoc LdDL(Ld);
24431     SDLoc StDL(N);
24432     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24433     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24434     // pair instead.
24435     if (Subtarget->is64Bit() || F64IsLegal) {
24436       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24437       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24438                                   Ld->getPointerInfo(), Ld->isVolatile(),
24439                                   Ld->isNonTemporal(), Ld->isInvariant(),
24440                                   Ld->getAlignment());
24441       SDValue NewChain = NewLd.getValue(1);
24442       if (TokenFactorIndex != -1) {
24443         Ops.push_back(NewChain);
24444         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24445       }
24446       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24447                           St->getPointerInfo(),
24448                           St->isVolatile(), St->isNonTemporal(),
24449                           St->getAlignment());
24450     }
24451
24452     // Otherwise, lower to two pairs of 32-bit loads / stores.
24453     SDValue LoAddr = Ld->getBasePtr();
24454     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24455                                  DAG.getConstant(4, LdDL, MVT::i32));
24456
24457     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24458                                Ld->getPointerInfo(),
24459                                Ld->isVolatile(), Ld->isNonTemporal(),
24460                                Ld->isInvariant(), Ld->getAlignment());
24461     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24462                                Ld->getPointerInfo().getWithOffset(4),
24463                                Ld->isVolatile(), Ld->isNonTemporal(),
24464                                Ld->isInvariant(),
24465                                MinAlign(Ld->getAlignment(), 4));
24466
24467     SDValue NewChain = LoLd.getValue(1);
24468     if (TokenFactorIndex != -1) {
24469       Ops.push_back(LoLd);
24470       Ops.push_back(HiLd);
24471       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24472     }
24473
24474     LoAddr = St->getBasePtr();
24475     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24476                          DAG.getConstant(4, StDL, MVT::i32));
24477
24478     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24479                                 St->getPointerInfo(),
24480                                 St->isVolatile(), St->isNonTemporal(),
24481                                 St->getAlignment());
24482     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24483                                 St->getPointerInfo().getWithOffset(4),
24484                                 St->isVolatile(),
24485                                 St->isNonTemporal(),
24486                                 MinAlign(St->getAlignment(), 4));
24487     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24488   }
24489
24490   // This is similar to the above case, but here we handle a scalar 64-bit
24491   // integer store that is extracted from a vector on a 32-bit target.
24492   // If we have SSE2, then we can treat it like a floating-point double
24493   // to get past legalization. The execution dependencies fixup pass will
24494   // choose the optimal machine instruction for the store if this really is
24495   // an integer or v2f32 rather than an f64.
24496   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24497       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24498     SDValue OldExtract = St->getOperand(1);
24499     SDValue ExtOp0 = OldExtract.getOperand(0);
24500     unsigned VecSize = ExtOp0.getValueSizeInBits();
24501     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24502     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24503     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24504                                      BitCast, OldExtract.getOperand(1));
24505     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24506                         St->getPointerInfo(), St->isVolatile(),
24507                         St->isNonTemporal(), St->getAlignment());
24508   }
24509
24510   return SDValue();
24511 }
24512
24513 /// Return 'true' if this vector operation is "horizontal"
24514 /// and return the operands for the horizontal operation in LHS and RHS.  A
24515 /// horizontal operation performs the binary operation on successive elements
24516 /// of its first operand, then on successive elements of its second operand,
24517 /// returning the resulting values in a vector.  For example, if
24518 ///   A = < float a0, float a1, float a2, float a3 >
24519 /// and
24520 ///   B = < float b0, float b1, float b2, float b3 >
24521 /// then the result of doing a horizontal operation on A and B is
24522 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24523 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24524 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24525 /// set to A, RHS to B, and the routine returns 'true'.
24526 /// Note that the binary operation should have the property that if one of the
24527 /// operands is UNDEF then the result is UNDEF.
24528 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24529   // Look for the following pattern: if
24530   //   A = < float a0, float a1, float a2, float a3 >
24531   //   B = < float b0, float b1, float b2, float b3 >
24532   // and
24533   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24534   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24535   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24536   // which is A horizontal-op B.
24537
24538   // At least one of the operands should be a vector shuffle.
24539   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24540       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24541     return false;
24542
24543   MVT VT = LHS.getSimpleValueType();
24544
24545   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24546          "Unsupported vector type for horizontal add/sub");
24547
24548   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24549   // operate independently on 128-bit lanes.
24550   unsigned NumElts = VT.getVectorNumElements();
24551   unsigned NumLanes = VT.getSizeInBits()/128;
24552   unsigned NumLaneElts = NumElts / NumLanes;
24553   assert((NumLaneElts % 2 == 0) &&
24554          "Vector type should have an even number of elements in each lane");
24555   unsigned HalfLaneElts = NumLaneElts/2;
24556
24557   // View LHS in the form
24558   //   LHS = VECTOR_SHUFFLE A, B, LMask
24559   // If LHS is not a shuffle then pretend it is the shuffle
24560   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24561   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24562   // type VT.
24563   SDValue A, B;
24564   SmallVector<int, 16> LMask(NumElts);
24565   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24566     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24567       A = LHS.getOperand(0);
24568     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24569       B = LHS.getOperand(1);
24570     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24571     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24572   } else {
24573     if (LHS.getOpcode() != ISD::UNDEF)
24574       A = LHS;
24575     for (unsigned i = 0; i != NumElts; ++i)
24576       LMask[i] = i;
24577   }
24578
24579   // Likewise, view RHS in the form
24580   //   RHS = VECTOR_SHUFFLE C, D, RMask
24581   SDValue C, D;
24582   SmallVector<int, 16> RMask(NumElts);
24583   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24584     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24585       C = RHS.getOperand(0);
24586     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24587       D = RHS.getOperand(1);
24588     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24589     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24590   } else {
24591     if (RHS.getOpcode() != ISD::UNDEF)
24592       C = RHS;
24593     for (unsigned i = 0; i != NumElts; ++i)
24594       RMask[i] = i;
24595   }
24596
24597   // Check that the shuffles are both shuffling the same vectors.
24598   if (!(A == C && B == D) && !(A == D && B == C))
24599     return false;
24600
24601   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24602   if (!A.getNode() && !B.getNode())
24603     return false;
24604
24605   // If A and B occur in reverse order in RHS, then "swap" them (which means
24606   // rewriting the mask).
24607   if (A != C)
24608     ShuffleVectorSDNode::commuteMask(RMask);
24609
24610   // At this point LHS and RHS are equivalent to
24611   //   LHS = VECTOR_SHUFFLE A, B, LMask
24612   //   RHS = VECTOR_SHUFFLE A, B, RMask
24613   // Check that the masks correspond to performing a horizontal operation.
24614   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24615     for (unsigned i = 0; i != NumLaneElts; ++i) {
24616       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24617
24618       // Ignore any UNDEF components.
24619       if (LIdx < 0 || RIdx < 0 ||
24620           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24621           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24622         continue;
24623
24624       // Check that successive elements are being operated on.  If not, this is
24625       // not a horizontal operation.
24626       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24627       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24628       if (!(LIdx == Index && RIdx == Index + 1) &&
24629           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24630         return false;
24631     }
24632   }
24633
24634   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24635   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24636   return true;
24637 }
24638
24639 /// Do target-specific dag combines on floating point adds.
24640 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24641                                   const X86Subtarget *Subtarget) {
24642   EVT VT = N->getValueType(0);
24643   SDValue LHS = N->getOperand(0);
24644   SDValue RHS = N->getOperand(1);
24645
24646   // Try to synthesize horizontal adds from adds of shuffles.
24647   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24648        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24649       isHorizontalBinOp(LHS, RHS, true))
24650     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24651   return SDValue();
24652 }
24653
24654 /// Do target-specific dag combines on floating point subs.
24655 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24656                                   const X86Subtarget *Subtarget) {
24657   EVT VT = N->getValueType(0);
24658   SDValue LHS = N->getOperand(0);
24659   SDValue RHS = N->getOperand(1);
24660
24661   // Try to synthesize horizontal subs from subs of shuffles.
24662   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24663        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24664       isHorizontalBinOp(LHS, RHS, false))
24665     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24666   return SDValue();
24667 }
24668
24669 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24670 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24671   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24672
24673   // F[X]OR(0.0, x) -> x
24674   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24675     if (C->getValueAPF().isPosZero())
24676       return N->getOperand(1);
24677
24678   // F[X]OR(x, 0.0) -> x
24679   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24680     if (C->getValueAPF().isPosZero())
24681       return N->getOperand(0);
24682   return SDValue();
24683 }
24684
24685 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24686 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24687   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24688
24689   // Only perform optimizations if UnsafeMath is used.
24690   if (!DAG.getTarget().Options.UnsafeFPMath)
24691     return SDValue();
24692
24693   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24694   // into FMINC and FMAXC, which are Commutative operations.
24695   unsigned NewOp = 0;
24696   switch (N->getOpcode()) {
24697     default: llvm_unreachable("unknown opcode");
24698     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24699     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24700   }
24701
24702   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24703                      N->getOperand(0), N->getOperand(1));
24704 }
24705
24706 /// Do target-specific dag combines on X86ISD::FAND nodes.
24707 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24708   // FAND(0.0, x) -> 0.0
24709   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24710     if (C->getValueAPF().isPosZero())
24711       return N->getOperand(0);
24712
24713   // FAND(x, 0.0) -> 0.0
24714   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24715     if (C->getValueAPF().isPosZero())
24716       return N->getOperand(1);
24717
24718   return SDValue();
24719 }
24720
24721 /// Do target-specific dag combines on X86ISD::FANDN nodes
24722 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24723   // FANDN(0.0, x) -> x
24724   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24725     if (C->getValueAPF().isPosZero())
24726       return N->getOperand(1);
24727
24728   // FANDN(x, 0.0) -> 0.0
24729   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24730     if (C->getValueAPF().isPosZero())
24731       return N->getOperand(1);
24732
24733   return SDValue();
24734 }
24735
24736 static SDValue PerformBTCombine(SDNode *N,
24737                                 SelectionDAG &DAG,
24738                                 TargetLowering::DAGCombinerInfo &DCI) {
24739   // BT ignores high bits in the bit index operand.
24740   SDValue Op1 = N->getOperand(1);
24741   if (Op1.hasOneUse()) {
24742     unsigned BitWidth = Op1.getValueSizeInBits();
24743     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24744     APInt KnownZero, KnownOne;
24745     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24746                                           !DCI.isBeforeLegalizeOps());
24747     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24748     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24749         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24750       DCI.CommitTargetLoweringOpt(TLO);
24751   }
24752   return SDValue();
24753 }
24754
24755 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24756   SDValue Op = N->getOperand(0);
24757   if (Op.getOpcode() == ISD::BITCAST)
24758     Op = Op.getOperand(0);
24759   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24760   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24761       VT.getVectorElementType().getSizeInBits() ==
24762       OpVT.getVectorElementType().getSizeInBits()) {
24763     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24764   }
24765   return SDValue();
24766 }
24767
24768 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24769                                                const X86Subtarget *Subtarget) {
24770   EVT VT = N->getValueType(0);
24771   if (!VT.isVector())
24772     return SDValue();
24773
24774   SDValue N0 = N->getOperand(0);
24775   SDValue N1 = N->getOperand(1);
24776   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24777   SDLoc dl(N);
24778
24779   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24780   // both SSE and AVX2 since there is no sign-extended shift right
24781   // operation on a vector with 64-bit elements.
24782   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24783   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24784   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24785       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24786     SDValue N00 = N0.getOperand(0);
24787
24788     // EXTLOAD has a better solution on AVX2,
24789     // it may be replaced with X86ISD::VSEXT node.
24790     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24791       if (!ISD::isNormalLoad(N00.getNode()))
24792         return SDValue();
24793
24794     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24795         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24796                                   N00, N1);
24797       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24798     }
24799   }
24800   return SDValue();
24801 }
24802
24803 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24804                                   TargetLowering::DAGCombinerInfo &DCI,
24805                                   const X86Subtarget *Subtarget) {
24806   SDValue N0 = N->getOperand(0);
24807   EVT VT = N->getValueType(0);
24808   EVT SVT = VT.getScalarType();
24809   EVT InVT = N0.getValueType();
24810   EVT InSVT = InVT.getScalarType();
24811   SDLoc DL(N);
24812
24813   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24814   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24815   // This exposes the sext to the sdivrem lowering, so that it directly extends
24816   // from AH (which we otherwise need to do contortions to access).
24817   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24818       InVT == MVT::i8 && VT == MVT::i32) {
24819     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24820     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24821                             N0.getOperand(0), N0.getOperand(1));
24822     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24823     return R.getValue(1);
24824   }
24825
24826   if (!DCI.isBeforeLegalizeOps()) {
24827     if (InVT == MVT::i1) {
24828       SDValue Zero = DAG.getConstant(0, DL, VT);
24829       SDValue AllOnes =
24830         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24831       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24832     }
24833     return SDValue();
24834   }
24835
24836   if (VT.isVector() && Subtarget->hasSSE2()) {
24837     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24838       EVT InVT = N.getValueType();
24839       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24840                                    Size / InVT.getScalarSizeInBits());
24841       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24842                                     DAG.getUNDEF(InVT));
24843       Opnds[0] = N;
24844       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24845     };
24846
24847     // If target-size is less than 128-bits, extend to a type that would extend
24848     // to 128 bits, extend that and extract the original target vector.
24849     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24850         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24851         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24852       unsigned Scale = 128 / VT.getSizeInBits();
24853       EVT ExVT =
24854           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24855       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24856       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24857       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24858                          DAG.getIntPtrConstant(0, DL));
24859     }
24860
24861     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24862     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24863     if (VT.getSizeInBits() == 128 &&
24864         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24865         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24866       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24867       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24868     }
24869
24870     // On pre-AVX2 targets, split into 128-bit nodes of
24871     // ISD::SIGN_EXTEND_VECTOR_INREG.
24872     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24873         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24874         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24875       unsigned NumVecs = VT.getSizeInBits() / 128;
24876       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24877       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24878       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24879
24880       SmallVector<SDValue, 8> Opnds;
24881       for (unsigned i = 0, Offset = 0; i != NumVecs;
24882            ++i, Offset += NumSubElts) {
24883         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24884                                      DAG.getIntPtrConstant(Offset, DL));
24885         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24886         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24887         Opnds.push_back(SrcVec);
24888       }
24889       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24890     }
24891   }
24892
24893   if (!Subtarget->hasFp256())
24894     return SDValue();
24895
24896   if (VT.isVector() && VT.getSizeInBits() == 256)
24897     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24898       return R;
24899
24900   return SDValue();
24901 }
24902
24903 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24904                                  const X86Subtarget* Subtarget) {
24905   SDLoc dl(N);
24906   EVT VT = N->getValueType(0);
24907
24908   // Let legalize expand this if it isn't a legal type yet.
24909   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24910     return SDValue();
24911
24912   EVT ScalarVT = VT.getScalarType();
24913   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24914       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24915        !Subtarget->hasAVX512()))
24916     return SDValue();
24917
24918   SDValue A = N->getOperand(0);
24919   SDValue B = N->getOperand(1);
24920   SDValue C = N->getOperand(2);
24921
24922   bool NegA = (A.getOpcode() == ISD::FNEG);
24923   bool NegB = (B.getOpcode() == ISD::FNEG);
24924   bool NegC = (C.getOpcode() == ISD::FNEG);
24925
24926   // Negative multiplication when NegA xor NegB
24927   bool NegMul = (NegA != NegB);
24928   if (NegA)
24929     A = A.getOperand(0);
24930   if (NegB)
24931     B = B.getOperand(0);
24932   if (NegC)
24933     C = C.getOperand(0);
24934
24935   unsigned Opcode;
24936   if (!NegMul)
24937     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24938   else
24939     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24940
24941   return DAG.getNode(Opcode, dl, VT, A, B, C);
24942 }
24943
24944 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24945                                   TargetLowering::DAGCombinerInfo &DCI,
24946                                   const X86Subtarget *Subtarget) {
24947   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24948   //           (and (i32 x86isd::setcc_carry), 1)
24949   // This eliminates the zext. This transformation is necessary because
24950   // ISD::SETCC is always legalized to i8.
24951   SDLoc dl(N);
24952   SDValue N0 = N->getOperand(0);
24953   EVT VT = N->getValueType(0);
24954
24955   if (N0.getOpcode() == ISD::AND &&
24956       N0.hasOneUse() &&
24957       N0.getOperand(0).hasOneUse()) {
24958     SDValue N00 = N0.getOperand(0);
24959     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24960       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24961       if (!C || C->getZExtValue() != 1)
24962         return SDValue();
24963       return DAG.getNode(ISD::AND, dl, VT,
24964                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24965                                      N00.getOperand(0), N00.getOperand(1)),
24966                          DAG.getConstant(1, dl, VT));
24967     }
24968   }
24969
24970   if (N0.getOpcode() == ISD::TRUNCATE &&
24971       N0.hasOneUse() &&
24972       N0.getOperand(0).hasOneUse()) {
24973     SDValue N00 = N0.getOperand(0);
24974     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24975       return DAG.getNode(ISD::AND, dl, VT,
24976                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24977                                      N00.getOperand(0), N00.getOperand(1)),
24978                          DAG.getConstant(1, dl, VT));
24979     }
24980   }
24981
24982   if (VT.is256BitVector())
24983     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24984       return R;
24985
24986   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24987   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24988   // This exposes the zext to the udivrem lowering, so that it directly extends
24989   // from AH (which we otherwise need to do contortions to access).
24990   if (N0.getOpcode() == ISD::UDIVREM &&
24991       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24992       (VT == MVT::i32 || VT == MVT::i64)) {
24993     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24994     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24995                             N0.getOperand(0), N0.getOperand(1));
24996     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24997     return R.getValue(1);
24998   }
24999
25000   return SDValue();
25001 }
25002
25003 // Optimize x == -y --> x+y == 0
25004 //          x != -y --> x+y != 0
25005 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25006                                       const X86Subtarget* Subtarget) {
25007   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25008   SDValue LHS = N->getOperand(0);
25009   SDValue RHS = N->getOperand(1);
25010   EVT VT = N->getValueType(0);
25011   SDLoc DL(N);
25012
25013   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25014     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25015       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25016         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25017                                    LHS.getOperand(1));
25018         return DAG.getSetCC(DL, N->getValueType(0), addV,
25019                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25020       }
25021   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25022     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25023       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25024         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25025                                    RHS.getOperand(1));
25026         return DAG.getSetCC(DL, N->getValueType(0), addV,
25027                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25028       }
25029
25030   if (VT.getScalarType() == MVT::i1 &&
25031       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25032     bool IsSEXT0 =
25033         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25034         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25035     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25036
25037     if (!IsSEXT0 || !IsVZero1) {
25038       // Swap the operands and update the condition code.
25039       std::swap(LHS, RHS);
25040       CC = ISD::getSetCCSwappedOperands(CC);
25041
25042       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25043                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25044       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25045     }
25046
25047     if (IsSEXT0 && IsVZero1) {
25048       assert(VT == LHS.getOperand(0).getValueType() &&
25049              "Uexpected operand type");
25050       if (CC == ISD::SETGT)
25051         return DAG.getConstant(0, DL, VT);
25052       if (CC == ISD::SETLE)
25053         return DAG.getConstant(1, DL, VT);
25054       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25055         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25056
25057       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25058              "Unexpected condition code!");
25059       return LHS.getOperand(0);
25060     }
25061   }
25062
25063   return SDValue();
25064 }
25065
25066 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25067                                          SelectionDAG &DAG) {
25068   SDLoc dl(Load);
25069   MVT VT = Load->getSimpleValueType(0);
25070   MVT EVT = VT.getVectorElementType();
25071   SDValue Addr = Load->getOperand(1);
25072   SDValue NewAddr = DAG.getNode(
25073       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25074       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25075                       Addr.getSimpleValueType()));
25076
25077   SDValue NewLoad =
25078       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25079                   DAG.getMachineFunction().getMachineMemOperand(
25080                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25081   return NewLoad;
25082 }
25083
25084 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25085                                       const X86Subtarget *Subtarget) {
25086   SDLoc dl(N);
25087   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25088   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25089          "X86insertps is only defined for v4x32");
25090
25091   SDValue Ld = N->getOperand(1);
25092   if (MayFoldLoad(Ld)) {
25093     // Extract the countS bits from the immediate so we can get the proper
25094     // address when narrowing the vector load to a specific element.
25095     // When the second source op is a memory address, insertps doesn't use
25096     // countS and just gets an f32 from that address.
25097     unsigned DestIndex =
25098         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25099
25100     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25101
25102     // Create this as a scalar to vector to match the instruction pattern.
25103     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25104     // countS bits are ignored when loading from memory on insertps, which
25105     // means we don't need to explicitly set them to 0.
25106     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25107                        LoadScalarToVector, N->getOperand(2));
25108   }
25109   return SDValue();
25110 }
25111
25112 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25113   SDValue V0 = N->getOperand(0);
25114   SDValue V1 = N->getOperand(1);
25115   SDLoc DL(N);
25116   EVT VT = N->getValueType(0);
25117
25118   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25119   // operands and changing the mask to 1. This saves us a bunch of
25120   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25121   // x86InstrInfo knows how to commute this back after instruction selection
25122   // if it would help register allocation.
25123
25124   // TODO: If optimizing for size or a processor that doesn't suffer from
25125   // partial register update stalls, this should be transformed into a MOVSD
25126   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25127
25128   if (VT == MVT::v2f64)
25129     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25130       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25131         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25132         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25133       }
25134
25135   return SDValue();
25136 }
25137
25138 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25139 // as "sbb reg,reg", since it can be extended without zext and produces
25140 // an all-ones bit which is more useful than 0/1 in some cases.
25141 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25142                                MVT VT) {
25143   if (VT == MVT::i8)
25144     return DAG.getNode(ISD::AND, DL, VT,
25145                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25146                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25147                                    EFLAGS),
25148                        DAG.getConstant(1, DL, VT));
25149   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25150   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25151                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25152                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25153                                  EFLAGS));
25154 }
25155
25156 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25157 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25158                                    TargetLowering::DAGCombinerInfo &DCI,
25159                                    const X86Subtarget *Subtarget) {
25160   SDLoc DL(N);
25161   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25162   SDValue EFLAGS = N->getOperand(1);
25163
25164   if (CC == X86::COND_A) {
25165     // Try to convert COND_A into COND_B in an attempt to facilitate
25166     // materializing "setb reg".
25167     //
25168     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25169     // cannot take an immediate as its first operand.
25170     //
25171     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25172         EFLAGS.getValueType().isInteger() &&
25173         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25174       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25175                                    EFLAGS.getNode()->getVTList(),
25176                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25177       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25178       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25179     }
25180   }
25181
25182   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25183   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25184   // cases.
25185   if (CC == X86::COND_B)
25186     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25187
25188   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25189     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25190     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25191   }
25192
25193   return SDValue();
25194 }
25195
25196 // Optimize branch condition evaluation.
25197 //
25198 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25199                                     TargetLowering::DAGCombinerInfo &DCI,
25200                                     const X86Subtarget *Subtarget) {
25201   SDLoc DL(N);
25202   SDValue Chain = N->getOperand(0);
25203   SDValue Dest = N->getOperand(1);
25204   SDValue EFLAGS = N->getOperand(3);
25205   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25206
25207   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25208     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25209     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25210                        Flags);
25211   }
25212
25213   return SDValue();
25214 }
25215
25216 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25217                                                          SelectionDAG &DAG) {
25218   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25219   // optimize away operation when it's from a constant.
25220   //
25221   // The general transformation is:
25222   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25223   //       AND(VECTOR_CMP(x,y), constant2)
25224   //    constant2 = UNARYOP(constant)
25225
25226   // Early exit if this isn't a vector operation, the operand of the
25227   // unary operation isn't a bitwise AND, or if the sizes of the operations
25228   // aren't the same.
25229   EVT VT = N->getValueType(0);
25230   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25231       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25232       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25233     return SDValue();
25234
25235   // Now check that the other operand of the AND is a constant. We could
25236   // make the transformation for non-constant splats as well, but it's unclear
25237   // that would be a benefit as it would not eliminate any operations, just
25238   // perform one more step in scalar code before moving to the vector unit.
25239   if (BuildVectorSDNode *BV =
25240           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25241     // Bail out if the vector isn't a constant.
25242     if (!BV->isConstant())
25243       return SDValue();
25244
25245     // Everything checks out. Build up the new and improved node.
25246     SDLoc DL(N);
25247     EVT IntVT = BV->getValueType(0);
25248     // Create a new constant of the appropriate type for the transformed
25249     // DAG.
25250     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25251     // The AND node needs bitcasts to/from an integer vector type around it.
25252     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25253     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25254                                  N->getOperand(0)->getOperand(0), MaskConst);
25255     SDValue Res = DAG.getBitcast(VT, NewAnd);
25256     return Res;
25257   }
25258
25259   return SDValue();
25260 }
25261
25262 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25263                                         const X86Subtarget *Subtarget) {
25264   SDValue Op0 = N->getOperand(0);
25265   EVT VT = N->getValueType(0);
25266   EVT InVT = Op0.getValueType();
25267   EVT InSVT = InVT.getScalarType();
25268   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25269
25270   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25271   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25272   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25273     SDLoc dl(N);
25274     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25275                                  InVT.getVectorNumElements());
25276     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25277
25278     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25279       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25280
25281     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25282   }
25283
25284   return SDValue();
25285 }
25286
25287 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25288                                         const X86Subtarget *Subtarget) {
25289   // First try to optimize away the conversion entirely when it's
25290   // conditionally from a constant. Vectors only.
25291   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25292     return Res;
25293
25294   // Now move on to more general possibilities.
25295   SDValue Op0 = N->getOperand(0);
25296   EVT VT = N->getValueType(0);
25297   EVT InVT = Op0.getValueType();
25298   EVT InSVT = InVT.getScalarType();
25299
25300   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25301   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25302   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25303     SDLoc dl(N);
25304     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25305                                  InVT.getVectorNumElements());
25306     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25307     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25308   }
25309
25310   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25311   // a 32-bit target where SSE doesn't support i64->FP operations.
25312   if (Op0.getOpcode() == ISD::LOAD) {
25313     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25314     EVT LdVT = Ld->getValueType(0);
25315
25316     // This transformation is not supported if the result type is f16
25317     if (VT == MVT::f16)
25318       return SDValue();
25319
25320     if (!Ld->isVolatile() && !VT.isVector() &&
25321         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25322         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25323       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25324           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25325       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25326       return FILDChain;
25327     }
25328   }
25329   return SDValue();
25330 }
25331
25332 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25333 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25334                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25335   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25336   // the result is either zero or one (depending on the input carry bit).
25337   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25338   if (X86::isZeroNode(N->getOperand(0)) &&
25339       X86::isZeroNode(N->getOperand(1)) &&
25340       // We don't have a good way to replace an EFLAGS use, so only do this when
25341       // dead right now.
25342       SDValue(N, 1).use_empty()) {
25343     SDLoc DL(N);
25344     EVT VT = N->getValueType(0);
25345     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25346     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25347                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25348                                            DAG.getConstant(X86::COND_B, DL,
25349                                                            MVT::i8),
25350                                            N->getOperand(2)),
25351                                DAG.getConstant(1, DL, VT));
25352     return DCI.CombineTo(N, Res1, CarryOut);
25353   }
25354
25355   return SDValue();
25356 }
25357
25358 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25359 //      (add Y, (setne X, 0)) -> sbb -1, Y
25360 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25361 //      (sub (setne X, 0), Y) -> adc -1, Y
25362 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25363   SDLoc DL(N);
25364
25365   // Look through ZExts.
25366   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25367   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25368     return SDValue();
25369
25370   SDValue SetCC = Ext.getOperand(0);
25371   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25372     return SDValue();
25373
25374   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25375   if (CC != X86::COND_E && CC != X86::COND_NE)
25376     return SDValue();
25377
25378   SDValue Cmp = SetCC.getOperand(1);
25379   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25380       !X86::isZeroNode(Cmp.getOperand(1)) ||
25381       !Cmp.getOperand(0).getValueType().isInteger())
25382     return SDValue();
25383
25384   SDValue CmpOp0 = Cmp.getOperand(0);
25385   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25386                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25387
25388   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25389   if (CC == X86::COND_NE)
25390     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25391                        DL, OtherVal.getValueType(), OtherVal,
25392                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25393                        NewCmp);
25394   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25395                      DL, OtherVal.getValueType(), OtherVal,
25396                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25397 }
25398
25399 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25400 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25401                                  const X86Subtarget *Subtarget) {
25402   EVT VT = N->getValueType(0);
25403   SDValue Op0 = N->getOperand(0);
25404   SDValue Op1 = N->getOperand(1);
25405
25406   // Try to synthesize horizontal adds from adds of shuffles.
25407   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25408        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25409       isHorizontalBinOp(Op0, Op1, true))
25410     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25411
25412   return OptimizeConditionalInDecrement(N, DAG);
25413 }
25414
25415 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25416                                  const X86Subtarget *Subtarget) {
25417   SDValue Op0 = N->getOperand(0);
25418   SDValue Op1 = N->getOperand(1);
25419
25420   // X86 can't encode an immediate LHS of a sub. See if we can push the
25421   // negation into a preceding instruction.
25422   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25423     // If the RHS of the sub is a XOR with one use and a constant, invert the
25424     // immediate. Then add one to the LHS of the sub so we can turn
25425     // X-Y -> X+~Y+1, saving one register.
25426     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25427         isa<ConstantSDNode>(Op1.getOperand(1))) {
25428       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25429       EVT VT = Op0.getValueType();
25430       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25431                                    Op1.getOperand(0),
25432                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25433       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25434                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25435     }
25436   }
25437
25438   // Try to synthesize horizontal adds from adds of shuffles.
25439   EVT VT = N->getValueType(0);
25440   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25441        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25442       isHorizontalBinOp(Op0, Op1, true))
25443     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25444
25445   return OptimizeConditionalInDecrement(N, DAG);
25446 }
25447
25448 /// performVZEXTCombine - Performs build vector combines
25449 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25450                                    TargetLowering::DAGCombinerInfo &DCI,
25451                                    const X86Subtarget *Subtarget) {
25452   SDLoc DL(N);
25453   MVT VT = N->getSimpleValueType(0);
25454   SDValue Op = N->getOperand(0);
25455   MVT OpVT = Op.getSimpleValueType();
25456   MVT OpEltVT = OpVT.getVectorElementType();
25457   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25458
25459   // (vzext (bitcast (vzext (x)) -> (vzext x)
25460   SDValue V = Op;
25461   while (V.getOpcode() == ISD::BITCAST)
25462     V = V.getOperand(0);
25463
25464   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25465     MVT InnerVT = V.getSimpleValueType();
25466     MVT InnerEltVT = InnerVT.getVectorElementType();
25467
25468     // If the element sizes match exactly, we can just do one larger vzext. This
25469     // is always an exact type match as vzext operates on integer types.
25470     if (OpEltVT == InnerEltVT) {
25471       assert(OpVT == InnerVT && "Types must match for vzext!");
25472       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25473     }
25474
25475     // The only other way we can combine them is if only a single element of the
25476     // inner vzext is used in the input to the outer vzext.
25477     if (InnerEltVT.getSizeInBits() < InputBits)
25478       return SDValue();
25479
25480     // In this case, the inner vzext is completely dead because we're going to
25481     // only look at bits inside of the low element. Just do the outer vzext on
25482     // a bitcast of the input to the inner.
25483     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25484   }
25485
25486   // Check if we can bypass extracting and re-inserting an element of an input
25487   // vector. Essentialy:
25488   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25489   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25490       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25491       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25492     SDValue ExtractedV = V.getOperand(0);
25493     SDValue OrigV = ExtractedV.getOperand(0);
25494     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25495       if (ExtractIdx->getZExtValue() == 0) {
25496         MVT OrigVT = OrigV.getSimpleValueType();
25497         // Extract a subvector if necessary...
25498         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25499           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25500           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25501                                     OrigVT.getVectorNumElements() / Ratio);
25502           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25503                               DAG.getIntPtrConstant(0, DL));
25504         }
25505         Op = DAG.getBitcast(OpVT, OrigV);
25506         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25507       }
25508   }
25509
25510   return SDValue();
25511 }
25512
25513 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25514                                              DAGCombinerInfo &DCI) const {
25515   SelectionDAG &DAG = DCI.DAG;
25516   switch (N->getOpcode()) {
25517   default: break;
25518   case ISD::EXTRACT_VECTOR_ELT:
25519     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25520   case ISD::VSELECT:
25521   case ISD::SELECT:
25522   case X86ISD::SHRUNKBLEND:
25523     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25524   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25525   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25526   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25527   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25528   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25529   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25530   case ISD::SHL:
25531   case ISD::SRA:
25532   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25533   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25534   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25535   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25536   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25537   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25538   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25539   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25540   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25541   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25542   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25543   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25544   case X86ISD::FXOR:
25545   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25546   case X86ISD::FMIN:
25547   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25548   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25549   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25550   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25551   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25552   case ISD::ANY_EXTEND:
25553   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25554   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25555   case ISD::SIGN_EXTEND_INREG:
25556     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25557   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25558   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25559   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25560   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25561   case X86ISD::SHUFP:       // Handle all target specific shuffles
25562   case X86ISD::PALIGNR:
25563   case X86ISD::UNPCKH:
25564   case X86ISD::UNPCKL:
25565   case X86ISD::MOVHLPS:
25566   case X86ISD::MOVLHPS:
25567   case X86ISD::PSHUFB:
25568   case X86ISD::PSHUFD:
25569   case X86ISD::PSHUFHW:
25570   case X86ISD::PSHUFLW:
25571   case X86ISD::MOVSS:
25572   case X86ISD::MOVSD:
25573   case X86ISD::VPERMILPI:
25574   case X86ISD::VPERM2X128:
25575   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25576   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25577   case ISD::INTRINSIC_WO_CHAIN:
25578     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25579   case X86ISD::INSERTPS: {
25580     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25581       return PerformINSERTPSCombine(N, DAG, Subtarget);
25582     break;
25583   }
25584   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25585   }
25586
25587   return SDValue();
25588 }
25589
25590 /// isTypeDesirableForOp - Return true if the target has native support for
25591 /// the specified value type and it is 'desirable' to use the type for the
25592 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25593 /// instruction encodings are longer and some i16 instructions are slow.
25594 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25595   if (!isTypeLegal(VT))
25596     return false;
25597   if (VT != MVT::i16)
25598     return true;
25599
25600   switch (Opc) {
25601   default:
25602     return true;
25603   case ISD::LOAD:
25604   case ISD::SIGN_EXTEND:
25605   case ISD::ZERO_EXTEND:
25606   case ISD::ANY_EXTEND:
25607   case ISD::SHL:
25608   case ISD::SRL:
25609   case ISD::SUB:
25610   case ISD::ADD:
25611   case ISD::MUL:
25612   case ISD::AND:
25613   case ISD::OR:
25614   case ISD::XOR:
25615     return false;
25616   }
25617 }
25618
25619 /// IsDesirableToPromoteOp - This method query the target whether it is
25620 /// beneficial for dag combiner to promote the specified node. If true, it
25621 /// should return the desired promotion type by reference.
25622 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25623   EVT VT = Op.getValueType();
25624   if (VT != MVT::i16)
25625     return false;
25626
25627   bool Promote = false;
25628   bool Commute = false;
25629   switch (Op.getOpcode()) {
25630   default: break;
25631   case ISD::LOAD: {
25632     LoadSDNode *LD = cast<LoadSDNode>(Op);
25633     // If the non-extending load has a single use and it's not live out, then it
25634     // might be folded.
25635     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25636                                                      Op.hasOneUse()*/) {
25637       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25638              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25639         // The only case where we'd want to promote LOAD (rather then it being
25640         // promoted as an operand is when it's only use is liveout.
25641         if (UI->getOpcode() != ISD::CopyToReg)
25642           return false;
25643       }
25644     }
25645     Promote = true;
25646     break;
25647   }
25648   case ISD::SIGN_EXTEND:
25649   case ISD::ZERO_EXTEND:
25650   case ISD::ANY_EXTEND:
25651     Promote = true;
25652     break;
25653   case ISD::SHL:
25654   case ISD::SRL: {
25655     SDValue N0 = Op.getOperand(0);
25656     // Look out for (store (shl (load), x)).
25657     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25658       return false;
25659     Promote = true;
25660     break;
25661   }
25662   case ISD::ADD:
25663   case ISD::MUL:
25664   case ISD::AND:
25665   case ISD::OR:
25666   case ISD::XOR:
25667     Commute = true;
25668     // fallthrough
25669   case ISD::SUB: {
25670     SDValue N0 = Op.getOperand(0);
25671     SDValue N1 = Op.getOperand(1);
25672     if (!Commute && MayFoldLoad(N1))
25673       return false;
25674     // Avoid disabling potential load folding opportunities.
25675     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25676       return false;
25677     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25678       return false;
25679     Promote = true;
25680   }
25681   }
25682
25683   PVT = MVT::i32;
25684   return Promote;
25685 }
25686
25687 //===----------------------------------------------------------------------===//
25688 //                           X86 Inline Assembly Support
25689 //===----------------------------------------------------------------------===//
25690
25691 // Helper to match a string separated by whitespace.
25692 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25693   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25694
25695   for (StringRef Piece : Pieces) {
25696     if (!S.startswith(Piece)) // Check if the piece matches.
25697       return false;
25698
25699     S = S.substr(Piece.size());
25700     StringRef::size_type Pos = S.find_first_not_of(" \t");
25701     if (Pos == 0) // We matched a prefix.
25702       return false;
25703
25704     S = S.substr(Pos);
25705   }
25706
25707   return S.empty();
25708 }
25709
25710 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25711
25712   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25713     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25714         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25715         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25716
25717       if (AsmPieces.size() == 3)
25718         return true;
25719       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25720         return true;
25721     }
25722   }
25723   return false;
25724 }
25725
25726 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25727   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25728
25729   std::string AsmStr = IA->getAsmString();
25730
25731   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25732   if (!Ty || Ty->getBitWidth() % 16 != 0)
25733     return false;
25734
25735   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25736   SmallVector<StringRef, 4> AsmPieces;
25737   SplitString(AsmStr, AsmPieces, ";\n");
25738
25739   switch (AsmPieces.size()) {
25740   default: return false;
25741   case 1:
25742     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25743     // we will turn this bswap into something that will be lowered to logical
25744     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25745     // lower so don't worry about this.
25746     // bswap $0
25747     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25748         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25749         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25750         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25751         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25752         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25753       // No need to check constraints, nothing other than the equivalent of
25754       // "=r,0" would be valid here.
25755       return IntrinsicLowering::LowerToByteSwap(CI);
25756     }
25757
25758     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25759     if (CI->getType()->isIntegerTy(16) &&
25760         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25761         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25762          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25763       AsmPieces.clear();
25764       StringRef ConstraintsStr = IA->getConstraintString();
25765       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25766       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25767       if (clobbersFlagRegisters(AsmPieces))
25768         return IntrinsicLowering::LowerToByteSwap(CI);
25769     }
25770     break;
25771   case 3:
25772     if (CI->getType()->isIntegerTy(32) &&
25773         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25774         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25775         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25776         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25777       AsmPieces.clear();
25778       StringRef ConstraintsStr = IA->getConstraintString();
25779       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25780       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25781       if (clobbersFlagRegisters(AsmPieces))
25782         return IntrinsicLowering::LowerToByteSwap(CI);
25783     }
25784
25785     if (CI->getType()->isIntegerTy(64)) {
25786       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25787       if (Constraints.size() >= 2 &&
25788           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25789           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25790         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25791         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25792             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25793             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25794           return IntrinsicLowering::LowerToByteSwap(CI);
25795       }
25796     }
25797     break;
25798   }
25799   return false;
25800 }
25801
25802 /// getConstraintType - Given a constraint letter, return the type of
25803 /// constraint it is for this target.
25804 X86TargetLowering::ConstraintType
25805 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25806   if (Constraint.size() == 1) {
25807     switch (Constraint[0]) {
25808     case 'R':
25809     case 'q':
25810     case 'Q':
25811     case 'f':
25812     case 't':
25813     case 'u':
25814     case 'y':
25815     case 'x':
25816     case 'Y':
25817     case 'l':
25818       return C_RegisterClass;
25819     case 'a':
25820     case 'b':
25821     case 'c':
25822     case 'd':
25823     case 'S':
25824     case 'D':
25825     case 'A':
25826       return C_Register;
25827     case 'I':
25828     case 'J':
25829     case 'K':
25830     case 'L':
25831     case 'M':
25832     case 'N':
25833     case 'G':
25834     case 'C':
25835     case 'e':
25836     case 'Z':
25837       return C_Other;
25838     default:
25839       break;
25840     }
25841   }
25842   return TargetLowering::getConstraintType(Constraint);
25843 }
25844
25845 /// Examine constraint type and operand type and determine a weight value.
25846 /// This object must already have been set up with the operand type
25847 /// and the current alternative constraint selected.
25848 TargetLowering::ConstraintWeight
25849   X86TargetLowering::getSingleConstraintMatchWeight(
25850     AsmOperandInfo &info, const char *constraint) const {
25851   ConstraintWeight weight = CW_Invalid;
25852   Value *CallOperandVal = info.CallOperandVal;
25853     // If we don't have a value, we can't do a match,
25854     // but allow it at the lowest weight.
25855   if (!CallOperandVal)
25856     return CW_Default;
25857   Type *type = CallOperandVal->getType();
25858   // Look at the constraint type.
25859   switch (*constraint) {
25860   default:
25861     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25862   case 'R':
25863   case 'q':
25864   case 'Q':
25865   case 'a':
25866   case 'b':
25867   case 'c':
25868   case 'd':
25869   case 'S':
25870   case 'D':
25871   case 'A':
25872     if (CallOperandVal->getType()->isIntegerTy())
25873       weight = CW_SpecificReg;
25874     break;
25875   case 'f':
25876   case 't':
25877   case 'u':
25878     if (type->isFloatingPointTy())
25879       weight = CW_SpecificReg;
25880     break;
25881   case 'y':
25882     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25883       weight = CW_SpecificReg;
25884     break;
25885   case 'x':
25886   case 'Y':
25887     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25888         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25889       weight = CW_Register;
25890     break;
25891   case 'I':
25892     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25893       if (C->getZExtValue() <= 31)
25894         weight = CW_Constant;
25895     }
25896     break;
25897   case 'J':
25898     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25899       if (C->getZExtValue() <= 63)
25900         weight = CW_Constant;
25901     }
25902     break;
25903   case 'K':
25904     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25905       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25906         weight = CW_Constant;
25907     }
25908     break;
25909   case 'L':
25910     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25911       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25912         weight = CW_Constant;
25913     }
25914     break;
25915   case 'M':
25916     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25917       if (C->getZExtValue() <= 3)
25918         weight = CW_Constant;
25919     }
25920     break;
25921   case 'N':
25922     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25923       if (C->getZExtValue() <= 0xff)
25924         weight = CW_Constant;
25925     }
25926     break;
25927   case 'G':
25928   case 'C':
25929     if (isa<ConstantFP>(CallOperandVal)) {
25930       weight = CW_Constant;
25931     }
25932     break;
25933   case 'e':
25934     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25935       if ((C->getSExtValue() >= -0x80000000LL) &&
25936           (C->getSExtValue() <= 0x7fffffffLL))
25937         weight = CW_Constant;
25938     }
25939     break;
25940   case 'Z':
25941     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25942       if (C->getZExtValue() <= 0xffffffff)
25943         weight = CW_Constant;
25944     }
25945     break;
25946   }
25947   return weight;
25948 }
25949
25950 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25951 /// with another that has more specific requirements based on the type of the
25952 /// corresponding operand.
25953 const char *X86TargetLowering::
25954 LowerXConstraint(EVT ConstraintVT) const {
25955   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25956   // 'f' like normal targets.
25957   if (ConstraintVT.isFloatingPoint()) {
25958     if (Subtarget->hasSSE2())
25959       return "Y";
25960     if (Subtarget->hasSSE1())
25961       return "x";
25962   }
25963
25964   return TargetLowering::LowerXConstraint(ConstraintVT);
25965 }
25966
25967 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25968 /// vector.  If it is invalid, don't add anything to Ops.
25969 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25970                                                      std::string &Constraint,
25971                                                      std::vector<SDValue>&Ops,
25972                                                      SelectionDAG &DAG) const {
25973   SDValue Result;
25974
25975   // Only support length 1 constraints for now.
25976   if (Constraint.length() > 1) return;
25977
25978   char ConstraintLetter = Constraint[0];
25979   switch (ConstraintLetter) {
25980   default: break;
25981   case 'I':
25982     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25983       if (C->getZExtValue() <= 31) {
25984         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25985                                        Op.getValueType());
25986         break;
25987       }
25988     }
25989     return;
25990   case 'J':
25991     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25992       if (C->getZExtValue() <= 63) {
25993         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25994                                        Op.getValueType());
25995         break;
25996       }
25997     }
25998     return;
25999   case 'K':
26000     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26001       if (isInt<8>(C->getSExtValue())) {
26002         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26003                                        Op.getValueType());
26004         break;
26005       }
26006     }
26007     return;
26008   case 'L':
26009     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26010       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26011           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26012         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26013                                        Op.getValueType());
26014         break;
26015       }
26016     }
26017     return;
26018   case 'M':
26019     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26020       if (C->getZExtValue() <= 3) {
26021         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26022                                        Op.getValueType());
26023         break;
26024       }
26025     }
26026     return;
26027   case 'N':
26028     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26029       if (C->getZExtValue() <= 255) {
26030         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26031                                        Op.getValueType());
26032         break;
26033       }
26034     }
26035     return;
26036   case 'O':
26037     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26038       if (C->getZExtValue() <= 127) {
26039         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26040                                        Op.getValueType());
26041         break;
26042       }
26043     }
26044     return;
26045   case 'e': {
26046     // 32-bit signed value
26047     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26048       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26049                                            C->getSExtValue())) {
26050         // Widen to 64 bits here to get it sign extended.
26051         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26052         break;
26053       }
26054     // FIXME gcc accepts some relocatable values here too, but only in certain
26055     // memory models; it's complicated.
26056     }
26057     return;
26058   }
26059   case 'Z': {
26060     // 32-bit unsigned value
26061     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26062       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26063                                            C->getZExtValue())) {
26064         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26065                                        Op.getValueType());
26066         break;
26067       }
26068     }
26069     // FIXME gcc accepts some relocatable values here too, but only in certain
26070     // memory models; it's complicated.
26071     return;
26072   }
26073   case 'i': {
26074     // Literal immediates are always ok.
26075     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26076       // Widen to 64 bits here to get it sign extended.
26077       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26078       break;
26079     }
26080
26081     // In any sort of PIC mode addresses need to be computed at runtime by
26082     // adding in a register or some sort of table lookup.  These can't
26083     // be used as immediates.
26084     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26085       return;
26086
26087     // If we are in non-pic codegen mode, we allow the address of a global (with
26088     // an optional displacement) to be used with 'i'.
26089     GlobalAddressSDNode *GA = nullptr;
26090     int64_t Offset = 0;
26091
26092     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26093     while (1) {
26094       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26095         Offset += GA->getOffset();
26096         break;
26097       } else if (Op.getOpcode() == ISD::ADD) {
26098         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26099           Offset += C->getZExtValue();
26100           Op = Op.getOperand(0);
26101           continue;
26102         }
26103       } else if (Op.getOpcode() == ISD::SUB) {
26104         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26105           Offset += -C->getZExtValue();
26106           Op = Op.getOperand(0);
26107           continue;
26108         }
26109       }
26110
26111       // Otherwise, this isn't something we can handle, reject it.
26112       return;
26113     }
26114
26115     const GlobalValue *GV = GA->getGlobal();
26116     // If we require an extra load to get this address, as in PIC mode, we
26117     // can't accept it.
26118     if (isGlobalStubReference(
26119             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26120       return;
26121
26122     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26123                                         GA->getValueType(0), Offset);
26124     break;
26125   }
26126   }
26127
26128   if (Result.getNode()) {
26129     Ops.push_back(Result);
26130     return;
26131   }
26132   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26133 }
26134
26135 std::pair<unsigned, const TargetRegisterClass *>
26136 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26137                                                 StringRef Constraint,
26138                                                 MVT VT) const {
26139   // First, see if this is a constraint that directly corresponds to an LLVM
26140   // register class.
26141   if (Constraint.size() == 1) {
26142     // GCC Constraint Letters
26143     switch (Constraint[0]) {
26144     default: break;
26145       // TODO: Slight differences here in allocation order and leaving
26146       // RIP in the class. Do they matter any more here than they do
26147       // in the normal allocation?
26148     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26149       if (Subtarget->is64Bit()) {
26150         if (VT == MVT::i32 || VT == MVT::f32)
26151           return std::make_pair(0U, &X86::GR32RegClass);
26152         if (VT == MVT::i16)
26153           return std::make_pair(0U, &X86::GR16RegClass);
26154         if (VT == MVT::i8 || VT == MVT::i1)
26155           return std::make_pair(0U, &X86::GR8RegClass);
26156         if (VT == MVT::i64 || VT == MVT::f64)
26157           return std::make_pair(0U, &X86::GR64RegClass);
26158         break;
26159       }
26160       // 32-bit fallthrough
26161     case 'Q':   // Q_REGS
26162       if (VT == MVT::i32 || VT == MVT::f32)
26163         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26164       if (VT == MVT::i16)
26165         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26166       if (VT == MVT::i8 || VT == MVT::i1)
26167         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26168       if (VT == MVT::i64)
26169         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26170       break;
26171     case 'r':   // GENERAL_REGS
26172     case 'l':   // INDEX_REGS
26173       if (VT == MVT::i8 || VT == MVT::i1)
26174         return std::make_pair(0U, &X86::GR8RegClass);
26175       if (VT == MVT::i16)
26176         return std::make_pair(0U, &X86::GR16RegClass);
26177       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26178         return std::make_pair(0U, &X86::GR32RegClass);
26179       return std::make_pair(0U, &X86::GR64RegClass);
26180     case 'R':   // LEGACY_REGS
26181       if (VT == MVT::i8 || VT == MVT::i1)
26182         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26183       if (VT == MVT::i16)
26184         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26185       if (VT == MVT::i32 || !Subtarget->is64Bit())
26186         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26187       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26188     case 'f':  // FP Stack registers.
26189       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26190       // value to the correct fpstack register class.
26191       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26192         return std::make_pair(0U, &X86::RFP32RegClass);
26193       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26194         return std::make_pair(0U, &X86::RFP64RegClass);
26195       return std::make_pair(0U, &X86::RFP80RegClass);
26196     case 'y':   // MMX_REGS if MMX allowed.
26197       if (!Subtarget->hasMMX()) break;
26198       return std::make_pair(0U, &X86::VR64RegClass);
26199     case 'Y':   // SSE_REGS if SSE2 allowed
26200       if (!Subtarget->hasSSE2()) break;
26201       // FALL THROUGH.
26202     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26203       if (!Subtarget->hasSSE1()) break;
26204
26205       switch (VT.SimpleTy) {
26206       default: break;
26207       // Scalar SSE types.
26208       case MVT::f32:
26209       case MVT::i32:
26210         return std::make_pair(0U, &X86::FR32RegClass);
26211       case MVT::f64:
26212       case MVT::i64:
26213         return std::make_pair(0U, &X86::FR64RegClass);
26214       // Vector types.
26215       case MVT::v16i8:
26216       case MVT::v8i16:
26217       case MVT::v4i32:
26218       case MVT::v2i64:
26219       case MVT::v4f32:
26220       case MVT::v2f64:
26221         return std::make_pair(0U, &X86::VR128RegClass);
26222       // AVX types.
26223       case MVT::v32i8:
26224       case MVT::v16i16:
26225       case MVT::v8i32:
26226       case MVT::v4i64:
26227       case MVT::v8f32:
26228       case MVT::v4f64:
26229         return std::make_pair(0U, &X86::VR256RegClass);
26230       case MVT::v8f64:
26231       case MVT::v16f32:
26232       case MVT::v16i32:
26233       case MVT::v8i64:
26234         return std::make_pair(0U, &X86::VR512RegClass);
26235       }
26236       break;
26237     }
26238   }
26239
26240   // Use the default implementation in TargetLowering to convert the register
26241   // constraint into a member of a register class.
26242   std::pair<unsigned, const TargetRegisterClass*> Res;
26243   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26244
26245   // Not found as a standard register?
26246   if (!Res.second) {
26247     // Map st(0) -> st(7) -> ST0
26248     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26249         tolower(Constraint[1]) == 's' &&
26250         tolower(Constraint[2]) == 't' &&
26251         Constraint[3] == '(' &&
26252         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26253         Constraint[5] == ')' &&
26254         Constraint[6] == '}') {
26255
26256       Res.first = X86::FP0+Constraint[4]-'0';
26257       Res.second = &X86::RFP80RegClass;
26258       return Res;
26259     }
26260
26261     // GCC allows "st(0)" to be called just plain "st".
26262     if (StringRef("{st}").equals_lower(Constraint)) {
26263       Res.first = X86::FP0;
26264       Res.second = &X86::RFP80RegClass;
26265       return Res;
26266     }
26267
26268     // flags -> EFLAGS
26269     if (StringRef("{flags}").equals_lower(Constraint)) {
26270       Res.first = X86::EFLAGS;
26271       Res.second = &X86::CCRRegClass;
26272       return Res;
26273     }
26274
26275     // 'A' means EAX + EDX.
26276     if (Constraint == "A") {
26277       Res.first = X86::EAX;
26278       Res.second = &X86::GR32_ADRegClass;
26279       return Res;
26280     }
26281     return Res;
26282   }
26283
26284   // Otherwise, check to see if this is a register class of the wrong value
26285   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26286   // turn into {ax},{dx}.
26287   // MVT::Other is used to specify clobber names.
26288   if (Res.second->hasType(VT) || VT == MVT::Other)
26289     return Res;   // Correct type already, nothing to do.
26290
26291   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26292   // return "eax". This should even work for things like getting 64bit integer
26293   // registers when given an f64 type.
26294   const TargetRegisterClass *Class = Res.second;
26295   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26296       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26297     unsigned Size = VT.getSizeInBits();
26298     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26299                                   : Size == 16 ? MVT::i16
26300                                   : Size == 32 ? MVT::i32
26301                                   : Size == 64 ? MVT::i64
26302                                   : MVT::Other;
26303     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26304     if (DestReg > 0) {
26305       Res.first = DestReg;
26306       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26307                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26308                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26309                  : &X86::GR64RegClass;
26310       assert(Res.second->contains(Res.first) && "Register in register class");
26311     } else {
26312       // No register found/type mismatch.
26313       Res.first = 0;
26314       Res.second = nullptr;
26315     }
26316   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26317              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26318              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26319              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26320              Class == &X86::VR512RegClass) {
26321     // Handle references to XMM physical registers that got mapped into the
26322     // wrong class.  This can happen with constraints like {xmm0} where the
26323     // target independent register mapper will just pick the first match it can
26324     // find, ignoring the required type.
26325
26326     if (VT == MVT::f32 || VT == MVT::i32)
26327       Res.second = &X86::FR32RegClass;
26328     else if (VT == MVT::f64 || VT == MVT::i64)
26329       Res.second = &X86::FR64RegClass;
26330     else if (X86::VR128RegClass.hasType(VT))
26331       Res.second = &X86::VR128RegClass;
26332     else if (X86::VR256RegClass.hasType(VT))
26333       Res.second = &X86::VR256RegClass;
26334     else if (X86::VR512RegClass.hasType(VT))
26335       Res.second = &X86::VR512RegClass;
26336     else {
26337       // Type mismatch and not a clobber: Return an error;
26338       Res.first = 0;
26339       Res.second = nullptr;
26340     }
26341   }
26342
26343   return Res;
26344 }
26345
26346 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26347                                             const AddrMode &AM, Type *Ty,
26348                                             unsigned AS) const {
26349   // Scaling factors are not free at all.
26350   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26351   // will take 2 allocations in the out of order engine instead of 1
26352   // for plain addressing mode, i.e. inst (reg1).
26353   // E.g.,
26354   // vaddps (%rsi,%drx), %ymm0, %ymm1
26355   // Requires two allocations (one for the load, one for the computation)
26356   // whereas:
26357   // vaddps (%rsi), %ymm0, %ymm1
26358   // Requires just 1 allocation, i.e., freeing allocations for other operations
26359   // and having less micro operations to execute.
26360   //
26361   // For some X86 architectures, this is even worse because for instance for
26362   // stores, the complex addressing mode forces the instruction to use the
26363   // "load" ports instead of the dedicated "store" port.
26364   // E.g., on Haswell:
26365   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26366   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26367   if (isLegalAddressingMode(DL, AM, Ty, AS))
26368     // Scale represents reg2 * scale, thus account for 1
26369     // as soon as we use a second register.
26370     return AM.Scale != 0;
26371   return -1;
26372 }
26373
26374 bool X86TargetLowering::isTargetFTOL() const {
26375   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26376 }